c++: alias template of non-template class [PR112633]
[official-gcc.git] / gcc / cp / pt.cc
blob68ce4a87372945243e4d9b0149161a16379687c3
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"
49 #include "builtins.h"
51 /* The type of functions taking a tree, and some additional data, and
52 returning an int. */
53 typedef int (*tree_fn_t) (tree, void*);
55 /* The PENDING_TEMPLATES is a list of templates whose instantiations
56 have been deferred, either because their definitions were not yet
57 available, or because we were putting off doing the work. */
58 struct GTY ((chain_next ("%h.next"))) pending_template
60 struct pending_template *next;
61 struct tinst_level *tinst;
64 static GTY(()) struct pending_template *pending_templates;
65 static GTY(()) struct pending_template *last_pending_template;
67 int processing_template_parmlist;
68 static int template_header_count;
70 static vec<int> inline_parm_levels;
72 static GTY(()) struct tinst_level *current_tinst_level;
74 static GTY(()) vec<tree, va_gc> *saved_access_scope;
76 /* Live only within one (recursive) call to tsubst_expr. We use
77 this to pass the statement expression node from the STMT_EXPR
78 to the EXPR_STMT that is its result. */
79 static tree cur_stmt_expr;
81 // -------------------------------------------------------------------------- //
82 // Local Specialization Stack
84 // Implementation of the RAII helper for creating new local
85 // specializations.
86 local_specialization_stack::local_specialization_stack (lss_policy policy)
87 : saved (local_specializations)
89 if (policy == lss_nop)
91 else if (policy == lss_blank || !saved)
92 local_specializations = new hash_map<tree, tree>;
93 else
94 local_specializations = new hash_map<tree, tree>(*saved);
97 local_specialization_stack::~local_specialization_stack ()
99 if (local_specializations != saved)
101 delete local_specializations;
102 local_specializations = saved;
106 /* True if we've recursed into fn_type_unification too many times. */
107 static bool excessive_deduction_depth;
109 struct spec_hasher : ggc_ptr_hash<spec_entry>
111 static hashval_t hash (tree, tree);
112 static hashval_t hash (spec_entry *);
113 static bool equal (spec_entry *, spec_entry *);
116 /* The general template is not in these tables. */
117 typedef hash_table<spec_hasher> spec_hash_table;
118 static GTY (()) spec_hash_table *decl_specializations;
119 static GTY (()) spec_hash_table *type_specializations;
121 /* Contains canonical template parameter types. The vector is indexed by
122 the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
123 TREE_LIST, whose TREE_VALUEs contain the canonical template
124 parameters of various types and levels. */
125 static GTY(()) vec<tree, va_gc> *canonical_template_parms;
127 #define UNIFY_ALLOW_NONE 0
128 #define UNIFY_ALLOW_MORE_CV_QUAL 1
129 #define UNIFY_ALLOW_LESS_CV_QUAL 2
130 #define UNIFY_ALLOW_DERIVED 4
131 #define UNIFY_ALLOW_INTEGER 8
132 #define UNIFY_ALLOW_OUTER_LEVEL 16
133 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
134 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
136 enum template_base_result {
137 tbr_incomplete_type,
138 tbr_ambiguous_baseclass,
139 tbr_success
142 static bool resolve_overloaded_unification (tree, tree, tree, tree,
143 unification_kind_t, int,
144 bool);
145 static int try_one_overload (tree, tree, tree, tree, tree,
146 unification_kind_t, int, bool, bool);
147 static int unify (tree, tree, tree, tree, int, bool);
148 static void add_pending_template (tree);
149 static tree reopen_tinst_level (struct tinst_level *);
150 static tree tsubst_initializer_list (tree, tree);
151 static tree get_partial_spec_bindings (tree, tree, tree);
152 static void tsubst_enum (tree, tree, tree);
153 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
154 static int check_non_deducible_conversion (tree, tree, unification_kind_t, int,
155 struct conversion **, bool, bool);
156 static int maybe_adjust_types_for_deduction (tree, unification_kind_t,
157 tree*, tree*, tree);
158 static int type_unification_real (tree, tree, tree, const tree *,
159 unsigned int, int, unification_kind_t,
160 vec<deferred_access_check, va_gc> **,
161 bool);
162 static void note_template_header (int);
163 static tree convert_nontype_argument_function (tree, tree, tsubst_flags_t);
164 static tree convert_nontype_argument (tree, tree, tsubst_flags_t);
165 static tree convert_template_argument (tree, tree, tree,
166 tsubst_flags_t, int, tree);
167 static tree for_each_template_parm (tree, tree_fn_t, void*,
168 hash_set<tree> *, bool, tree_fn_t = NULL);
169 static tree expand_template_argument_pack (tree);
170 static tree build_template_parm_index (int, int, int, tree, tree);
171 static bool inline_needs_template_parms (tree, bool);
172 static void push_inline_template_parms_recursive (tree, int);
173 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
174 static int mark_template_parm (tree, void *);
175 static int template_parm_this_level_p (tree, void *);
176 static tree tsubst_friend_function (tree, tree);
177 static tree tsubst_friend_class (tree, tree);
178 static int can_complete_type_without_circularity (tree);
179 static tree get_bindings (tree, tree, tree, bool);
180 static int template_decl_level (tree);
181 static int check_cv_quals_for_unify (int, tree, tree);
182 static int unify_pack_expansion (tree, tree, tree,
183 tree, unification_kind_t, bool, bool);
184 static tree copy_template_args (tree);
185 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
186 static void tsubst_each_template_parm_constraints (tree, tree, tsubst_flags_t);
187 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
188 static tree tsubst_aggr_type_1 (tree, tree, tsubst_flags_t, tree, int);
189 static tree tsubst_arg_types (tree, tree, tree, tsubst_flags_t, tree);
190 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
191 static bool check_specialization_scope (void);
192 static tree process_partial_specialization (tree);
193 static enum template_base_result get_template_base (tree, tree, tree, tree,
194 bool , tree *);
195 static tree try_class_unification (tree, tree, tree, tree, bool);
196 static bool class_nttp_const_wrapper_p (tree t);
197 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
198 tree, tree);
199 static bool template_template_parm_bindings_ok_p (tree, tree);
200 static void tsubst_default_arguments (tree, tsubst_flags_t);
201 static tree for_each_template_parm_r (tree *, int *, void *);
202 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
203 static void copy_default_args_to_explicit_spec (tree);
204 static bool invalid_nontype_parm_type_p (tree, tsubst_flags_t);
205 static bool dependent_template_arg_p (tree);
206 static bool dependent_type_p_r (tree);
207 static tree tsubst_stmt (tree, tree, tsubst_flags_t, tree);
208 static tree tsubst_decl (tree, tree, tsubst_flags_t, bool = true);
209 static tree tsubst_scope (tree, tree, tsubst_flags_t, tree);
210 static tree tsubst_name (tree, tree, tsubst_flags_t, tree);
211 static void perform_instantiation_time_access_checks (tree, tree);
212 static tree listify (tree);
213 static tree listify_autos (tree, tree);
214 static tree tsubst_template_parm (tree, tree, tsubst_flags_t);
215 static tree instantiate_alias_template (tree, tree, tsubst_flags_t);
216 static bool complex_alias_template_p (const_tree tmpl);
217 static tree get_underlying_template (tree);
218 static tree tsubst_attributes (tree, tree, tsubst_flags_t, tree);
219 static tree canonicalize_expr_argument (tree, tsubst_flags_t);
220 static tree make_argument_pack (tree);
221 static tree enclosing_instantiation_of (tree tctx);
222 static void instantiate_body (tree pattern, tree args, tree d, bool nested);
223 static tree maybe_dependent_member_ref (tree, tree, tsubst_flags_t, tree);
224 static void mark_template_arguments_used (tree, tree);
225 static bool uses_outer_template_parms (tree);
227 /* Make the current scope suitable for access checking when we are
228 processing T. T can be FUNCTION_DECL for instantiated function
229 template, VAR_DECL for static member variable, or TYPE_DECL for
230 for a class or alias template (needed by instantiate_decl). */
232 void
233 push_access_scope (tree t)
235 gcc_assert (VAR_OR_FUNCTION_DECL_P (t)
236 || TREE_CODE (t) == TYPE_DECL);
238 if (DECL_FRIEND_CONTEXT (t))
239 push_nested_class (DECL_FRIEND_CONTEXT (t));
240 else if (DECL_IMPLICIT_TYPEDEF_P (t)
241 && CLASS_TYPE_P (TREE_TYPE (t)))
242 push_nested_class (TREE_TYPE (t));
243 else if (DECL_CLASS_SCOPE_P (t))
244 push_nested_class (DECL_CONTEXT (t));
245 else if (deduction_guide_p (t) && DECL_ARTIFICIAL (t))
246 /* An artificial deduction guide should have the same access as
247 the constructor. */
248 push_nested_class (TREE_TYPE (TREE_TYPE (t)));
249 else
250 push_to_top_level ();
252 if (TREE_CODE (t) == FUNCTION_DECL)
254 vec_safe_push (saved_access_scope, current_function_decl);
255 current_function_decl = t;
259 /* Restore the scope set up by push_access_scope. T is the node we
260 are processing. */
262 void
263 pop_access_scope (tree t)
265 if (TREE_CODE (t) == FUNCTION_DECL)
266 current_function_decl = saved_access_scope->pop();
268 if (DECL_FRIEND_CONTEXT (t)
269 || (DECL_IMPLICIT_TYPEDEF_P (t)
270 && CLASS_TYPE_P (TREE_TYPE (t)))
271 || DECL_CLASS_SCOPE_P (t)
272 || (deduction_guide_p (t) && DECL_ARTIFICIAL (t)))
273 pop_nested_class ();
274 else
275 pop_from_top_level ();
278 /* Do any processing required when DECL (a member template
279 declaration) is finished. Returns the TEMPLATE_DECL corresponding
280 to DECL, unless it is a specialization, in which case the DECL
281 itself is returned. */
283 tree
284 finish_member_template_decl (tree decl)
286 if (decl == error_mark_node)
287 return error_mark_node;
289 gcc_assert (DECL_P (decl));
291 if (TREE_CODE (decl) == TYPE_DECL)
293 tree type;
295 type = TREE_TYPE (decl);
296 if (type == error_mark_node)
297 return error_mark_node;
298 if (MAYBE_CLASS_TYPE_P (type)
299 && CLASSTYPE_TEMPLATE_INFO (type)
300 && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
302 tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
303 check_member_template (tmpl);
304 return tmpl;
306 return NULL_TREE;
308 else if (TREE_CODE (decl) == FIELD_DECL)
309 error_at (DECL_SOURCE_LOCATION (decl),
310 "data member %qD cannot be a member template", decl);
311 else if (DECL_TEMPLATE_INFO (decl))
313 if (!DECL_TEMPLATE_SPECIALIZATION (decl))
315 check_member_template (DECL_TI_TEMPLATE (decl));
316 return DECL_TI_TEMPLATE (decl);
318 else
319 return NULL_TREE;
321 else
322 error_at (DECL_SOURCE_LOCATION (decl),
323 "invalid member template declaration %qD", decl);
325 return error_mark_node;
328 /* Create a template info node. */
330 tree
331 build_template_info (tree template_decl, tree template_args)
333 tree result = make_node (TEMPLATE_INFO);
334 TI_TEMPLATE (result) = template_decl;
335 TI_ARGS (result) = template_args;
336 return result;
339 /* Return the template info node corresponding to T, whatever T is. */
341 tree
342 get_template_info (const_tree t)
344 tree tinfo = NULL_TREE;
346 if (!t || t == error_mark_node)
347 return NULL;
349 if (TREE_CODE (t) == NAMESPACE_DECL
350 || TREE_CODE (t) == PARM_DECL)
351 return NULL;
353 if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
354 tinfo = DECL_TEMPLATE_INFO (t);
356 if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
357 t = TREE_TYPE (t);
359 if (OVERLOAD_TYPE_P (t))
360 tinfo = TYPE_TEMPLATE_INFO (t);
361 else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
362 tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
364 return tinfo;
367 /* Returns the template nesting level of the indicated class TYPE.
369 For example, in:
370 template <class T>
371 struct A
373 template <class U>
374 struct B {};
377 A<T>::B<U> has depth two, while A<T> has depth one.
378 Both A<T>::B<int> and A<int>::B<U> have depth one, if
379 they are instantiations, not specializations.
381 This function is guaranteed to return 0 if passed NULL_TREE so
382 that, for example, `template_class_depth (current_class_type)' is
383 always safe. */
386 template_class_depth (tree type)
388 int depth;
390 for (depth = 0; type && TREE_CODE (type) != NAMESPACE_DECL; )
392 tree tinfo = get_template_info (type);
394 if (tinfo
395 && TREE_CODE (TI_TEMPLATE (tinfo)) == TEMPLATE_DECL
396 && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
397 && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
398 ++depth;
400 if (DECL_P (type))
402 if (tree fctx = DECL_FRIEND_CONTEXT (type))
403 type = fctx;
404 else
405 type = CP_DECL_CONTEXT (type);
407 else if (LAMBDA_TYPE_P (type) && LAMBDA_TYPE_EXTRA_SCOPE (type))
408 type = LAMBDA_TYPE_EXTRA_SCOPE (type);
409 else
410 type = CP_TYPE_CONTEXT (type);
413 return depth;
416 /* Return TRUE if NODE instantiates a template that has arguments of
417 its own, be it directly a primary template or indirectly through a
418 partial specializations. */
419 static bool
420 instantiates_primary_template_p (tree node)
422 tree tinfo = get_template_info (node);
423 if (!tinfo)
424 return false;
426 tree tmpl = TI_TEMPLATE (tinfo);
427 if (PRIMARY_TEMPLATE_P (tmpl))
428 return true;
430 if (!DECL_TEMPLATE_SPECIALIZATION (tmpl))
431 return false;
433 /* So now we know we have a specialization, but it could be a full
434 or a partial specialization. To tell which, compare the depth of
435 its template arguments with those of its context. */
437 tree ctxt = DECL_CONTEXT (tmpl);
438 tree ctinfo = get_template_info (ctxt);
439 if (!ctinfo)
440 return true;
442 return (TMPL_ARGS_DEPTH (TI_ARGS (tinfo))
443 > TMPL_ARGS_DEPTH (TI_ARGS (ctinfo)));
446 /* Subroutine of maybe_begin_member_template_processing.
447 Returns true if processing DECL needs us to push template parms. */
449 static bool
450 inline_needs_template_parms (tree decl, bool nsdmi)
452 if (!decl || (!nsdmi && ! DECL_TEMPLATE_INFO (decl)))
453 return false;
455 return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
456 > (current_template_depth + DECL_TEMPLATE_SPECIALIZATION (decl)));
459 /* Subroutine of maybe_begin_member_template_processing.
460 Push the template parms in PARMS, starting from LEVELS steps into the
461 chain, and ending at the beginning, since template parms are listed
462 innermost first. */
464 static void
465 push_inline_template_parms_recursive (tree parmlist, int levels)
467 tree parms = TREE_VALUE (parmlist);
468 int i;
470 if (levels > 1)
471 push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
473 ++processing_template_decl;
474 current_template_parms
475 = tree_cons (size_int (current_template_depth + 1),
476 parms, current_template_parms);
477 TEMPLATE_PARMS_CONSTRAINTS (current_template_parms)
478 = TEMPLATE_PARMS_CONSTRAINTS (parmlist);
479 TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
481 begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
482 NULL);
483 for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
485 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
487 if (error_operand_p (parm))
488 continue;
490 gcc_assert (DECL_P (parm));
492 switch (TREE_CODE (parm))
494 case TYPE_DECL:
495 case TEMPLATE_DECL:
496 pushdecl (parm);
497 break;
499 case PARM_DECL:
500 /* Push the CONST_DECL. */
501 pushdecl (TEMPLATE_PARM_DECL (DECL_INITIAL (parm)));
502 break;
504 default:
505 gcc_unreachable ();
510 /* Restore the template parameter context for a member template, a
511 friend template defined in a class definition, or a non-template
512 member of template class. */
514 void
515 maybe_begin_member_template_processing (tree decl)
517 tree parms;
518 int levels = 0;
519 bool nsdmi = TREE_CODE (decl) == FIELD_DECL;
521 if (nsdmi)
523 tree ctx = DECL_CONTEXT (decl);
524 decl = (CLASSTYPE_TEMPLATE_INFO (ctx)
525 /* Disregard full specializations (c++/60999). */
526 && uses_template_parms (ctx)
527 ? CLASSTYPE_TI_TEMPLATE (ctx) : NULL_TREE);
530 if (inline_needs_template_parms (decl, nsdmi))
532 parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
533 levels = TMPL_PARMS_DEPTH (parms) - current_template_depth;
535 if (DECL_TEMPLATE_SPECIALIZATION (decl))
537 --levels;
538 parms = TREE_CHAIN (parms);
541 push_inline_template_parms_recursive (parms, levels);
544 /* Remember how many levels of template parameters we pushed so that
545 we can pop them later. */
546 inline_parm_levels.safe_push (levels);
549 /* Undo the effects of maybe_begin_member_template_processing. */
551 void
552 maybe_end_member_template_processing (void)
554 int i;
555 int last;
557 if (inline_parm_levels.length () == 0)
558 return;
560 last = inline_parm_levels.pop ();
561 for (i = 0; i < last; ++i)
563 --processing_template_decl;
564 current_template_parms = TREE_CHAIN (current_template_parms);
565 poplevel (0, 0, 0);
569 /* Return a new template argument vector which contains all of ARGS,
570 but has as its innermost set of arguments the EXTRA_ARGS. */
572 tree
573 add_to_template_args (tree args, tree extra_args)
575 tree new_args;
576 int extra_depth;
577 int i;
578 int j;
580 if (args == NULL_TREE || extra_args == error_mark_node)
581 return extra_args;
583 extra_depth = TMPL_ARGS_DEPTH (extra_args);
584 new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
586 for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
587 SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
589 for (j = 1; j <= extra_depth; ++j, ++i)
590 SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
592 return new_args;
595 /* Like add_to_template_args, but only the outermost ARGS are added to
596 the EXTRA_ARGS. In particular, all but TMPL_ARGS_DEPTH
597 (EXTRA_ARGS) levels are added. This function is used to combine
598 the template arguments from a partial instantiation with the
599 template arguments used to attain the full instantiation from the
600 partial instantiation.
602 If ARGS is a TEMPLATE_DECL, use its parameters as args. */
604 tree
605 add_outermost_template_args (tree args, tree extra_args)
607 tree new_args;
609 if (!args)
610 return extra_args;
611 if (TREE_CODE (args) == TEMPLATE_DECL)
613 tree ti = get_template_info (DECL_TEMPLATE_RESULT (args));
614 args = TI_ARGS (ti);
617 /* If there are more levels of EXTRA_ARGS than there are ARGS,
618 something very fishy is going on. */
619 gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
621 /* If *all* the new arguments will be the EXTRA_ARGS, just return
622 them. */
623 if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
624 return extra_args;
626 /* For the moment, we make ARGS look like it contains fewer levels. */
627 TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
629 new_args = add_to_template_args (args, extra_args);
631 /* Now, we restore ARGS to its full dimensions. */
632 TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
634 return new_args;
637 /* Return the N levels of innermost template arguments from the ARGS. */
639 tree
640 get_innermost_template_args (tree args, int n)
642 tree new_args;
643 int extra_levels;
644 int i;
646 gcc_assert (n >= 0);
648 /* If N is 1, just return the innermost set of template arguments. */
649 if (n == 1)
650 return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
652 /* If we're not removing anything, just return the arguments we were
653 given. */
654 extra_levels = TMPL_ARGS_DEPTH (args) - n;
655 gcc_assert (extra_levels >= 0);
656 if (extra_levels == 0)
657 return args;
659 /* Make a new set of arguments, not containing the outer arguments. */
660 new_args = make_tree_vec (n);
661 for (i = 1; i <= n; ++i)
662 SET_TMPL_ARGS_LEVEL (new_args, i,
663 TMPL_ARGS_LEVEL (args, i + extra_levels));
665 return new_args;
668 /* The inverse of get_innermost_template_args: Return all but the innermost
669 EXTRA_LEVELS levels of template arguments from the ARGS. */
671 static tree
672 strip_innermost_template_args (tree args, int extra_levels)
674 tree new_args;
675 int n = TMPL_ARGS_DEPTH (args) - extra_levels;
676 int i;
678 gcc_assert (n >= 0);
680 /* If N is 1, just return the outermost set of template arguments. */
681 if (n == 1)
682 return TMPL_ARGS_LEVEL (args, 1);
684 /* If we're not removing anything, just return the arguments we were
685 given. */
686 gcc_assert (extra_levels >= 0);
687 if (extra_levels == 0)
688 return args;
690 /* Make a new set of arguments, not containing the inner arguments. */
691 new_args = make_tree_vec (n);
692 for (i = 1; i <= n; ++i)
693 SET_TMPL_ARGS_LEVEL (new_args, i,
694 TMPL_ARGS_LEVEL (args, i));
696 return new_args;
699 /* We've got a template header coming up; push to a new level for storing
700 the parms. */
702 void
703 begin_template_parm_list (void)
705 /* We use a non-tag-transparent scope here, which causes pushtag to
706 put tags in this scope, rather than in the enclosing class or
707 namespace scope. This is the right thing, since we want
708 TEMPLATE_DECLS, and not TYPE_DECLS for template classes. For a
709 global template class, push_template_decl handles putting the
710 TEMPLATE_DECL into top-level scope. For a nested template class,
711 e.g.:
713 template <class T> struct S1 {
714 template <class T> struct S2 {};
717 pushtag contains special code to insert the TEMPLATE_DECL for S2
718 at the right scope. */
719 begin_scope (sk_template_parms, NULL);
720 ++processing_template_decl;
721 ++processing_template_parmlist;
722 note_template_header (0);
724 /* Add a dummy parameter level while we process the parameter list. */
725 current_template_parms
726 = tree_cons (size_int (current_template_depth + 1),
727 make_tree_vec (0),
728 current_template_parms);
731 /* This routine is called when a specialization is declared. If it is
732 invalid to declare a specialization here, an error is reported and
733 false is returned, otherwise this routine will return true. */
735 static bool
736 check_specialization_scope (void)
738 tree scope = current_scope ();
740 /* [temp.expl.spec]
742 An explicit specialization shall be declared in the namespace of
743 which the template is a member, or, for member templates, in the
744 namespace of which the enclosing class or enclosing class
745 template is a member. An explicit specialization of a member
746 function, member class or static data member of a class template
747 shall be declared in the namespace of which the class template
748 is a member. */
749 if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
751 error ("explicit specialization in non-namespace scope %qD", scope);
752 return false;
755 /* [temp.expl.spec]
757 In an explicit specialization declaration for a member of a class
758 template or a member template that appears in namespace scope,
759 the member template and some of its enclosing class templates may
760 remain unspecialized, except that the declaration shall not
761 explicitly specialize a class member template if its enclosing
762 class templates are not explicitly specialized as well. */
763 if (current_template_parms)
765 error ("enclosing class templates are not explicitly specialized");
766 return false;
769 return true;
772 /* We've just seen template <>. */
774 bool
775 begin_specialization (void)
777 begin_scope (sk_template_spec, NULL);
778 note_template_header (1);
779 return check_specialization_scope ();
782 /* Called at then end of processing a declaration preceded by
783 template<>. */
785 void
786 end_specialization (void)
788 finish_scope ();
789 reset_specialization ();
792 /* Any template <>'s that we have seen thus far are not referring to a
793 function specialization. */
795 void
796 reset_specialization (void)
798 processing_specialization = 0;
799 template_header_count = 0;
802 /* We've just seen a template header. If SPECIALIZATION is nonzero,
803 it was of the form template <>. */
805 static void
806 note_template_header (int specialization)
808 processing_specialization = specialization;
809 template_header_count++;
812 /* We're beginning an explicit instantiation. */
814 void
815 begin_explicit_instantiation (void)
817 gcc_assert (!processing_explicit_instantiation);
818 processing_explicit_instantiation = true;
822 void
823 end_explicit_instantiation (void)
825 gcc_assert (processing_explicit_instantiation);
826 processing_explicit_instantiation = false;
829 /* An explicit specialization or partial specialization of TMPL is being
830 declared. Check that the namespace in which the specialization is
831 occurring is permissible. Returns false iff it is invalid to
832 specialize TMPL in the current namespace. */
834 static bool
835 check_specialization_namespace (tree tmpl)
837 tree tpl_ns = decl_namespace_context (tmpl);
839 /* [tmpl.expl.spec]
841 An explicit specialization shall be declared in a namespace enclosing the
842 specialized template. An explicit specialization whose declarator-id is
843 not qualified shall be declared in the nearest enclosing namespace of the
844 template, or, if the namespace is inline (7.3.1), any namespace from its
845 enclosing namespace set. */
846 if (current_scope() != DECL_CONTEXT (tmpl)
847 && !at_namespace_scope_p ())
849 error ("specialization of %qD must appear at namespace scope", tmpl);
850 return false;
853 if (is_nested_namespace (current_namespace, tpl_ns, cxx_dialect < cxx11))
854 /* Same or enclosing namespace. */
855 return true;
856 else
858 auto_diagnostic_group d;
859 if (permerror (input_location,
860 "specialization of %qD in different namespace", tmpl))
861 inform (DECL_SOURCE_LOCATION (tmpl),
862 " from definition of %q#D", tmpl);
863 return false;
867 /* SPEC is an explicit instantiation. Check that it is valid to
868 perform this explicit instantiation in the current namespace. */
870 static void
871 check_explicit_instantiation_namespace (tree spec)
873 tree ns;
875 /* DR 275: An explicit instantiation shall appear in an enclosing
876 namespace of its template. */
877 ns = decl_namespace_context (spec);
878 if (!is_nested_namespace (current_namespace, ns))
879 permerror (input_location, "explicit instantiation of %qD in namespace %qD "
880 "(which does not enclose namespace %qD)",
881 spec, current_namespace, ns);
884 /* Returns true if TYPE is a new partial specialization that needs to be
885 set up. This may also modify TYPE to point to the correct (new or
886 existing) constrained partial specialization. */
888 static bool
889 maybe_new_partial_specialization (tree& type)
891 /* An implicit instantiation of an incomplete type implies
892 the definition of a new class template.
894 template<typename T>
895 struct S;
897 template<typename T>
898 struct S<T*>;
900 Here, S<T*> is an implicit instantiation of S whose type
901 is incomplete. */
902 if (CLASSTYPE_IMPLICIT_INSTANTIATION (type) && !COMPLETE_TYPE_P (type))
903 return true;
905 /* It can also be the case that TYPE is a completed specialization.
906 Continuing the previous example, suppose we also declare:
908 template<typename T>
909 requires Integral<T>
910 struct S<T*>;
912 Here, S<T*> refers to the specialization S<T*> defined
913 above. However, we need to differentiate definitions because
914 we intend to define a new partial specialization. In this case,
915 we rely on the fact that the constraints are different for
916 this declaration than that above.
918 Note that we also get here for injected class names and
919 late-parsed template definitions. We must ensure that we
920 do not create new type declarations for those cases. */
921 if (flag_concepts && CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
923 tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
924 tree args = CLASSTYPE_TI_ARGS (type);
926 /* If there are no template parameters, this cannot be a new
927 partial template specialization? */
928 if (!current_template_parms)
929 return false;
931 /* The injected-class-name is not a new partial specialization. */
932 if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
933 return false;
935 /* If the constraints are not the same as those of the primary
936 then, we can probably create a new specialization. */
937 tree type_constr = current_template_constraints ();
939 if (type == TREE_TYPE (tmpl))
941 tree main_constr = get_constraints (tmpl);
942 if (equivalent_constraints (type_constr, main_constr))
943 return false;
946 /* Also, if there's a pre-existing specialization with matching
947 constraints, then this also isn't new. */
948 tree specs = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
949 while (specs)
951 tree spec_tmpl = TREE_VALUE (specs);
952 tree spec_args = TREE_PURPOSE (specs);
953 tree spec_constr = get_constraints (spec_tmpl);
954 if (comp_template_args (args, spec_args)
955 && equivalent_constraints (type_constr, spec_constr))
957 type = TREE_TYPE (spec_tmpl);
958 return false;
960 specs = TREE_CHAIN (specs);
963 /* Create a new type node (and corresponding type decl)
964 for the newly declared specialization. */
965 tree t = make_class_type (TREE_CODE (type));
966 CLASSTYPE_DECLARED_CLASS (t) = CLASSTYPE_DECLARED_CLASS (type);
967 SET_TYPE_TEMPLATE_INFO (t, build_template_info (tmpl, args));
969 /* We only need a separate type node for storing the definition of this
970 partial specialization; uses of S<T*> are unconstrained, so all are
971 equivalent. So keep TYPE_CANONICAL the same. */
972 TYPE_CANONICAL (t) = TYPE_CANONICAL (type);
974 /* Build the corresponding type decl. */
975 tree d = create_implicit_typedef (DECL_NAME (tmpl), t);
976 DECL_CONTEXT (d) = TYPE_CONTEXT (t);
977 DECL_SOURCE_LOCATION (d) = input_location;
978 TREE_PRIVATE (d) = (current_access_specifier == access_private_node);
979 TREE_PROTECTED (d) = (current_access_specifier == access_protected_node);
981 set_instantiating_module (d);
982 DECL_MODULE_EXPORT_P (d) = DECL_MODULE_EXPORT_P (tmpl);
984 type = t;
985 return true;
988 return false;
991 /* The TYPE is being declared. If it is a template type, that means it
992 is a partial specialization. Do appropriate error-checking. */
994 tree
995 maybe_process_partial_specialization (tree type)
997 tree context;
999 if (type == error_mark_node)
1000 return error_mark_node;
1002 /* A lambda that appears in specialization context is not itself a
1003 specialization. */
1004 if (CLASS_TYPE_P (type) && CLASSTYPE_LAMBDA_EXPR (type))
1005 return type;
1007 /* An injected-class-name is not a specialization. */
1008 if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
1009 return type;
1011 if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
1013 error ("name of class shadows template template parameter %qD",
1014 TYPE_NAME (type));
1015 return error_mark_node;
1018 context = TYPE_CONTEXT (type);
1020 if (TYPE_ALIAS_P (type))
1022 tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (type);
1024 if (tinfo && DECL_ALIAS_TEMPLATE_P (TI_TEMPLATE (tinfo)))
1025 error ("specialization of alias template %qD",
1026 TI_TEMPLATE (tinfo));
1027 else
1028 error ("explicit specialization of non-template %qT", type);
1029 return error_mark_node;
1031 else if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
1033 /* This is for ordinary explicit specialization and partial
1034 specialization of a template class such as:
1036 template <> class C<int>;
1040 template <class T> class C<T*>;
1042 Make sure that `C<int>' and `C<T*>' are implicit instantiations. */
1044 if (maybe_new_partial_specialization (type))
1046 if (!check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type))
1047 && !at_namespace_scope_p ())
1048 return error_mark_node;
1049 SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
1050 DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
1051 if (processing_template_decl)
1053 tree decl = push_template_decl (TYPE_MAIN_DECL (type));
1054 if (decl == error_mark_node)
1055 return error_mark_node;
1056 return TREE_TYPE (decl);
1059 else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
1060 error ("specialization of %qT after instantiation", type);
1061 else if (errorcount && !processing_specialization
1062 && CLASSTYPE_TEMPLATE_SPECIALIZATION (type)
1063 && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
1064 /* Trying to define a specialization either without a template<> header
1065 or in an inappropriate place. We've already given an error, so just
1066 bail now so we don't actually define the specialization. */
1067 return error_mark_node;
1069 else if (CLASS_TYPE_P (type)
1070 && !CLASSTYPE_USE_TEMPLATE (type)
1071 && CLASSTYPE_TEMPLATE_INFO (type)
1072 && context && CLASS_TYPE_P (context)
1073 && CLASSTYPE_TEMPLATE_INFO (context))
1075 /* This is for an explicit specialization of member class
1076 template according to [temp.expl.spec/18]:
1078 template <> template <class U> class C<int>::D;
1080 The context `C<int>' must be an implicit instantiation.
1081 Otherwise this is just a member class template declared
1082 earlier like:
1084 template <> class C<int> { template <class U> class D; };
1085 template <> template <class U> class C<int>::D;
1087 In the first case, `C<int>::D' is a specialization of `C<T>::D'
1088 while in the second case, `C<int>::D' is a primary template
1089 and `C<T>::D' may not exist. */
1091 if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
1092 && !COMPLETE_TYPE_P (type))
1094 tree t;
1095 tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
1097 if (current_namespace
1098 != decl_namespace_context (tmpl))
1100 if (permerror (input_location,
1101 "specialization of %qD in different namespace",
1102 type))
1103 inform (DECL_SOURCE_LOCATION (tmpl),
1104 "from definition of %q#D", tmpl);
1107 /* Check for invalid specialization after instantiation:
1109 template <> template <> class C<int>::D<int>;
1110 template <> template <class U> class C<int>::D; */
1112 for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
1113 t; t = TREE_CHAIN (t))
1115 tree inst = TREE_VALUE (t);
1116 if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst)
1117 || !COMPLETE_OR_OPEN_TYPE_P (inst))
1119 /* We already have a full specialization of this partial
1120 instantiation, or a full specialization has been
1121 looked up but not instantiated. Reassign it to the
1122 new member specialization template. */
1123 spec_entry elt;
1124 spec_entry *entry;
1126 elt.tmpl = most_general_template (tmpl);
1127 elt.args = CLASSTYPE_TI_ARGS (inst);
1128 elt.spec = inst;
1130 type_specializations->remove_elt (&elt);
1132 elt.tmpl = tmpl;
1133 CLASSTYPE_TI_ARGS (inst)
1134 = elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
1136 spec_entry **slot
1137 = type_specializations->find_slot (&elt, INSERT);
1138 entry = ggc_alloc<spec_entry> ();
1139 *entry = elt;
1140 *slot = entry;
1142 else
1143 /* But if we've had an implicit instantiation, that's a
1144 problem ([temp.expl.spec]/6). */
1145 error ("specialization %qT after instantiation %qT",
1146 type, inst);
1149 /* Mark TYPE as a specialization. And as a result, we only
1150 have one level of template argument for the innermost
1151 class template. */
1152 SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
1153 DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
1154 CLASSTYPE_TI_ARGS (type)
1155 = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
1158 else if (processing_specialization)
1160 /* Someday C++0x may allow for enum template specialization. */
1161 if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
1162 && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
1163 pedwarn (input_location, OPT_Wpedantic, "template specialization "
1164 "of %qD not allowed by ISO C++", type);
1165 else
1167 error ("explicit specialization of non-template %qT", type);
1168 return error_mark_node;
1172 return type;
1175 /* Make sure ARGS doesn't use any inappropriate typedefs; we should have
1176 gone through coerce_template_parms by now. */
1178 static void
1179 verify_unstripped_args_1 (tree inner)
1181 for (int i = 0; i < TREE_VEC_LENGTH (inner); ++i)
1183 tree arg = TREE_VEC_ELT (inner, i);
1184 if (TREE_CODE (arg) == TEMPLATE_DECL)
1185 /* OK */;
1186 else if (TYPE_P (arg))
1187 gcc_assert (strip_typedefs (arg, NULL) == arg);
1188 else if (ARGUMENT_PACK_P (arg))
1189 verify_unstripped_args_1 (ARGUMENT_PACK_ARGS (arg));
1190 else if (strip_typedefs (TREE_TYPE (arg), NULL) != TREE_TYPE (arg))
1191 /* Allow typedefs on the type of a non-type argument, since a
1192 parameter can have them. */;
1193 else
1194 gcc_assert (strip_typedefs_expr (arg, NULL) == arg);
1198 static void
1199 verify_unstripped_args (tree args)
1201 ++processing_template_decl;
1202 if (!any_dependent_template_arguments_p (args))
1203 verify_unstripped_args_1 (INNERMOST_TEMPLATE_ARGS (args));
1204 --processing_template_decl;
1207 /* Retrieve the specialization (in the sense of [temp.spec] - a
1208 specialization is either an instantiation or an explicit
1209 specialization) of TMPL for the given template ARGS. If there is
1210 no such specialization, return NULL_TREE. The ARGS are a vector of
1211 arguments, or a vector of vectors of arguments, in the case of
1212 templates with more than one level of parameters.
1214 If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
1215 then we search for a partial specialization matching ARGS. This
1216 parameter is ignored if TMPL is not a class template.
1218 We can also look up a FIELD_DECL, if it is a lambda capture pack; the
1219 result is a NONTYPE_ARGUMENT_PACK. */
1221 static tree
1222 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
1224 if (tmpl == NULL_TREE)
1225 return NULL_TREE;
1227 if (args == error_mark_node)
1228 return NULL_TREE;
1230 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL
1231 || TREE_CODE (tmpl) == FIELD_DECL);
1233 /* There should be as many levels of arguments as there are
1234 levels of parameters. */
1235 gcc_assert (TMPL_ARGS_DEPTH (args)
1236 == (TREE_CODE (tmpl) == TEMPLATE_DECL
1237 ? TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl))
1238 : template_class_depth (DECL_CONTEXT (tmpl))));
1240 if (flag_checking)
1241 verify_unstripped_args (args);
1243 /* Lambda functions in templates aren't instantiated normally, but through
1244 tsubst_lambda_expr. */
1245 if (lambda_fn_in_template_p (tmpl))
1246 return NULL_TREE;
1248 spec_entry elt;
1249 elt.tmpl = tmpl;
1250 elt.args = args;
1251 elt.spec = NULL_TREE;
1253 spec_hash_table *specializations;
1254 if (DECL_CLASS_TEMPLATE_P (tmpl))
1255 specializations = type_specializations;
1256 else
1257 specializations = decl_specializations;
1259 if (hash == 0)
1260 hash = spec_hasher::hash (&elt);
1261 if (spec_entry *found = specializations->find_with_hash (&elt, hash))
1262 return found->spec;
1264 return NULL_TREE;
1267 /* Like retrieve_specialization, but for local declarations. */
1269 tree
1270 retrieve_local_specialization (tree tmpl)
1272 if (local_specializations == NULL)
1273 return NULL_TREE;
1275 tree *slot = local_specializations->get (tmpl);
1276 return slot ? *slot : NULL_TREE;
1279 /* Returns nonzero iff DECL is a specialization of TMPL. */
1282 is_specialization_of (tree decl, tree tmpl)
1284 tree t;
1286 if (TREE_CODE (decl) == FUNCTION_DECL)
1288 for (t = decl;
1289 t != NULL_TREE;
1290 t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1291 if (t == tmpl)
1292 return 1;
1294 else
1296 gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1298 for (t = TREE_TYPE (decl);
1299 t != NULL_TREE;
1300 t = CLASSTYPE_USE_TEMPLATE (t)
1301 ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1302 if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1303 return 1;
1306 return 0;
1309 /* Returns nonzero iff DECL is a specialization of friend declaration
1310 FRIEND_DECL according to [temp.friend]. */
1312 bool
1313 is_specialization_of_friend (tree decl, tree friend_decl)
1315 bool need_template = true;
1316 int template_depth;
1318 gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1319 || TREE_CODE (decl) == TYPE_DECL);
1321 /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1322 of a template class, we want to check if DECL is a specialization
1323 if this. */
1324 if (TREE_CODE (friend_decl) == FUNCTION_DECL
1325 && DECL_CLASS_SCOPE_P (friend_decl)
1326 && DECL_TEMPLATE_INFO (friend_decl)
1327 && !DECL_USE_TEMPLATE (friend_decl))
1329 /* We want a TEMPLATE_DECL for `is_specialization_of'. */
1330 friend_decl = DECL_TI_TEMPLATE (friend_decl);
1331 need_template = false;
1333 else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1334 && !PRIMARY_TEMPLATE_P (friend_decl))
1335 need_template = false;
1337 /* There is nothing to do if this is not a template friend. */
1338 if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1339 return false;
1341 if (is_specialization_of (decl, friend_decl))
1342 return true;
1344 /* [temp.friend/6]
1345 A member of a class template may be declared to be a friend of a
1346 non-template class. In this case, the corresponding member of
1347 every specialization of the class template is a friend of the
1348 class granting friendship.
1350 For example, given a template friend declaration
1352 template <class T> friend void A<T>::f();
1354 the member function below is considered a friend
1356 template <> struct A<int> {
1357 void f();
1360 For this type of template friend, TEMPLATE_DEPTH below will be
1361 nonzero. To determine if DECL is a friend of FRIEND, we first
1362 check if the enclosing class is a specialization of another. */
1364 template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1365 if (template_depth
1366 && DECL_CLASS_SCOPE_P (decl)
1367 && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1368 CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1370 /* Next, we check the members themselves. In order to handle
1371 a few tricky cases, such as when FRIEND_DECL's are
1373 template <class T> friend void A<T>::g(T t);
1374 template <class T> template <T t> friend void A<T>::h();
1376 and DECL's are
1378 void A<int>::g(int);
1379 template <int> void A<int>::h();
1381 we need to figure out ARGS, the template arguments from
1382 the context of DECL. This is required for template substitution
1383 of `T' in the function parameter of `g' and template parameter
1384 of `h' in the above examples. Here ARGS corresponds to `int'. */
1386 tree context = DECL_CONTEXT (decl);
1387 tree args = NULL_TREE;
1388 int current_depth = 0;
1390 while (current_depth < template_depth)
1392 if (CLASSTYPE_TEMPLATE_INFO (context))
1394 if (current_depth == 0)
1395 args = TYPE_TI_ARGS (context);
1396 else
1397 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1398 current_depth++;
1400 context = TYPE_CONTEXT (context);
1403 if (TREE_CODE (decl) == FUNCTION_DECL)
1405 bool is_template;
1406 tree friend_type;
1407 tree decl_type;
1408 tree friend_args_type;
1409 tree decl_args_type;
1411 /* Make sure that both DECL and FRIEND_DECL are templates or
1412 non-templates. */
1413 is_template = DECL_TEMPLATE_INFO (decl)
1414 && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1415 if (need_template ^ is_template)
1416 return false;
1417 else if (is_template)
1419 /* If both are templates, check template parameter list. */
1420 tree friend_parms
1421 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1422 args, tf_none);
1423 if (!comp_template_parms
1424 (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1425 friend_parms))
1426 return false;
1428 decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1430 else
1431 decl_type = TREE_TYPE (decl);
1433 friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1434 tf_none, NULL_TREE);
1435 if (friend_type == error_mark_node)
1436 return false;
1438 /* Check if return types match. */
1439 if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1440 return false;
1442 /* Check if function parameter types match, ignoring the
1443 `this' parameter. */
1444 friend_args_type = TYPE_ARG_TYPES (friend_type);
1445 decl_args_type = TYPE_ARG_TYPES (decl_type);
1446 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1447 friend_args_type = TREE_CHAIN (friend_args_type);
1448 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1449 decl_args_type = TREE_CHAIN (decl_args_type);
1451 return compparms (decl_args_type, friend_args_type);
1453 else
1455 /* DECL is a TYPE_DECL */
1456 bool is_template;
1457 tree decl_type = TREE_TYPE (decl);
1459 /* Make sure that both DECL and FRIEND_DECL are templates or
1460 non-templates. */
1461 is_template
1462 = CLASSTYPE_TEMPLATE_INFO (decl_type)
1463 && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1465 if (need_template ^ is_template)
1466 return false;
1467 else if (is_template)
1469 tree friend_parms;
1470 /* If both are templates, check the name of the two
1471 TEMPLATE_DECL's first because is_friend didn't. */
1472 if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1473 != DECL_NAME (friend_decl))
1474 return false;
1476 /* Now check template parameter list. */
1477 friend_parms
1478 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1479 args, tf_none);
1480 return comp_template_parms
1481 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1482 friend_parms);
1484 else
1485 return (DECL_NAME (decl)
1486 == DECL_NAME (friend_decl));
1489 return false;
1492 /* Register the specialization SPEC as a specialization of TMPL with
1493 the indicated ARGS. IS_FRIEND indicates whether the specialization
1494 is actually just a friend declaration. ATTRLIST is the list of
1495 attributes that the specialization is declared with or NULL when
1496 it isn't. Returns SPEC, or an equivalent prior declaration, if
1497 available.
1499 We also store instantiations of field packs in the hash table, even
1500 though they are not themselves templates, to make lookup easier. */
1502 static tree
1503 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1504 hashval_t hash)
1506 tree fn;
1508 gcc_assert ((TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec))
1509 || (TREE_CODE (tmpl) == FIELD_DECL
1510 && TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK));
1512 spec_entry elt;
1513 elt.tmpl = tmpl;
1514 elt.args = args;
1515 elt.spec = spec;
1517 if (hash == 0)
1518 hash = spec_hasher::hash (&elt);
1520 spec_entry **slot = decl_specializations->find_slot_with_hash (&elt, hash, INSERT);
1521 if (*slot)
1522 fn = (*slot)->spec;
1523 else
1524 fn = NULL_TREE;
1526 /* We can sometimes try to re-register a specialization that we've
1527 already got. In particular, regenerate_decl_from_template calls
1528 duplicate_decls which will update the specialization list. But,
1529 we'll still get called again here anyhow. It's more convenient
1530 to simply allow this than to try to prevent it. */
1531 if (fn == spec)
1532 return spec;
1533 else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1535 if (DECL_TEMPLATE_INSTANTIATION (fn))
1537 if (DECL_ODR_USED (fn)
1538 || DECL_EXPLICIT_INSTANTIATION (fn))
1540 error ("specialization of %qD after instantiation",
1541 fn);
1542 return error_mark_node;
1544 else
1546 tree clone;
1547 /* This situation should occur only if the first
1548 specialization is an implicit instantiation, the
1549 second is an explicit specialization, and the
1550 implicit instantiation has not yet been used. That
1551 situation can occur if we have implicitly
1552 instantiated a member function and then specialized
1553 it later.
1555 We can also wind up here if a friend declaration that
1556 looked like an instantiation turns out to be a
1557 specialization:
1559 template <class T> void foo(T);
1560 class S { friend void foo<>(int) };
1561 template <> void foo(int);
1563 We transform the existing DECL in place so that any
1564 pointers to it become pointers to the updated
1565 declaration.
1567 If there was a definition for the template, but not
1568 for the specialization, we want this to look as if
1569 there were no definition, and vice versa. */
1570 DECL_INITIAL (fn) = NULL_TREE;
1571 duplicate_decls (spec, fn, /*hiding=*/is_friend);
1573 /* The call to duplicate_decls will have applied
1574 [temp.expl.spec]:
1576 An explicit specialization of a function template
1577 is inline only if it is explicitly declared to be,
1578 and independently of whether its function template
1581 to the primary function; now copy the inline bits to
1582 the various clones. */
1583 FOR_EACH_CLONE (clone, fn)
1585 DECL_DECLARED_INLINE_P (clone)
1586 = DECL_DECLARED_INLINE_P (fn);
1587 DECL_SOURCE_LOCATION (clone)
1588 = DECL_SOURCE_LOCATION (fn);
1589 DECL_DELETED_FN (clone)
1590 = DECL_DELETED_FN (fn);
1592 check_specialization_namespace (tmpl);
1594 return fn;
1597 else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1599 tree dd = duplicate_decls (spec, fn, /*hiding=*/is_friend);
1600 if (dd == error_mark_node)
1601 /* We've already complained in duplicate_decls. */
1602 return error_mark_node;
1604 if (dd == NULL_TREE && DECL_INITIAL (spec))
1605 /* Dup decl failed, but this is a new definition. Set the
1606 line number so any errors match this new
1607 definition. */
1608 DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1610 return fn;
1613 else if (fn)
1614 return duplicate_decls (spec, fn, /*hiding=*/is_friend);
1616 /* A specialization must be declared in the same namespace as the
1617 template it is specializing. */
1618 if (DECL_P (spec) && DECL_TEMPLATE_SPECIALIZATION (spec)
1619 && !check_specialization_namespace (tmpl))
1620 DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1622 spec_entry *entry = ggc_alloc<spec_entry> ();
1623 gcc_assert (tmpl && args && spec);
1624 *entry = elt;
1625 *slot = entry;
1626 if ((TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1627 && PRIMARY_TEMPLATE_P (tmpl)
1628 && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1629 || variable_template_p (tmpl))
1630 /* If TMPL is a forward declaration of a template function, keep a list
1631 of all specializations in case we need to reassign them to a friend
1632 template later in tsubst_friend_function.
1634 Also keep a list of all variable template instantiations so that
1635 process_partial_specialization can check whether a later partial
1636 specialization would have used it. */
1637 DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1638 = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1640 return spec;
1643 /* Restricts tree and type comparisons. */
1644 int comparing_specializations;
1645 int comparing_dependent_aliases;
1647 /* Returns true iff two spec_entry nodes are equivalent. */
1649 bool
1650 spec_hasher::equal (spec_entry *e1, spec_entry *e2)
1652 int equal;
1654 ++comparing_specializations;
1655 ++comparing_dependent_aliases;
1656 ++processing_template_decl;
1657 equal = (e1->tmpl == e2->tmpl
1658 && comp_template_args (e1->args, e2->args));
1659 if (equal && flag_concepts
1660 /* tmpl could be a FIELD_DECL for a capture pack. */
1661 && TREE_CODE (e1->tmpl) == TEMPLATE_DECL
1662 && VAR_P (DECL_TEMPLATE_RESULT (e1->tmpl))
1663 && uses_template_parms (e1->args))
1665 /* Partial specializations of a variable template can be distinguished by
1666 constraints. */
1667 tree c1 = e1->spec ? get_constraints (e1->spec) : NULL_TREE;
1668 tree c2 = e2->spec ? get_constraints (e2->spec) : NULL_TREE;
1669 equal = equivalent_constraints (c1, c2);
1671 --processing_template_decl;
1672 --comparing_dependent_aliases;
1673 --comparing_specializations;
1675 return equal;
1678 /* Returns a hash for a template TMPL and template arguments ARGS. */
1680 static hashval_t
1681 hash_tmpl_and_args (tree tmpl, tree args)
1683 hashval_t val = iterative_hash_object (DECL_UID (tmpl), 0);
1684 return iterative_hash_template_arg (args, val);
1687 hashval_t
1688 spec_hasher::hash (tree tmpl, tree args)
1690 ++comparing_specializations;
1691 hashval_t val = hash_tmpl_and_args (tmpl, args);
1692 --comparing_specializations;
1693 return val;
1696 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1697 ignoring SPEC. */
1699 hashval_t
1700 spec_hasher::hash (spec_entry *e)
1702 return spec_hasher::hash (e->tmpl, e->args);
1705 /* Recursively calculate a hash value for a template argument ARG, for use
1706 in the hash tables of template specializations. We must be
1707 careful to (at least) skip the same entities template_args_equal
1708 does. */
1710 hashval_t
1711 iterative_hash_template_arg (tree arg, hashval_t val)
1713 if (arg == NULL_TREE)
1714 return iterative_hash_object (arg, val);
1716 if (!TYPE_P (arg))
1717 /* Strip nop-like things, but not the same as STRIP_NOPS. */
1718 while (CONVERT_EXPR_P (arg)
1719 || TREE_CODE (arg) == NON_LVALUE_EXPR
1720 || class_nttp_const_wrapper_p (arg))
1721 arg = TREE_OPERAND (arg, 0);
1723 enum tree_code code = TREE_CODE (arg);
1725 val = iterative_hash_object (code, val);
1727 switch (code)
1729 case ARGUMENT_PACK_SELECT:
1730 /* Getting here with an ARGUMENT_PACK_SELECT means we're probably
1731 preserving it in a hash table, which is bad because it will change
1732 meaning when gen_elem_of_pack_expansion_instantiation changes the
1733 ARGUMENT_PACK_SELECT_INDEX. */
1734 gcc_unreachable ();
1736 case ERROR_MARK:
1737 return val;
1739 case IDENTIFIER_NODE:
1740 return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1742 case TREE_VEC:
1743 for (tree elt : tree_vec_range (arg))
1744 val = iterative_hash_template_arg (elt, val);
1745 return val;
1747 case TYPE_PACK_EXPANSION:
1748 case EXPR_PACK_EXPANSION:
1749 val = iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1750 return iterative_hash_template_arg (PACK_EXPANSION_EXTRA_ARGS (arg), val);
1752 case TYPE_ARGUMENT_PACK:
1753 case NONTYPE_ARGUMENT_PACK:
1754 return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1756 case TREE_LIST:
1757 for (; arg; arg = TREE_CHAIN (arg))
1758 val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1759 return val;
1761 case OVERLOAD:
1762 for (lkp_iterator iter (arg); iter; ++iter)
1763 val = iterative_hash_template_arg (*iter, val);
1764 return val;
1766 case CONSTRUCTOR:
1768 iterative_hash_template_arg (TREE_TYPE (arg), val);
1769 for (auto &e: CONSTRUCTOR_ELTS (arg))
1771 val = iterative_hash_template_arg (e.index, val);
1772 val = iterative_hash_template_arg (e.value, val);
1774 return val;
1777 case PARM_DECL:
1778 if (!DECL_ARTIFICIAL (arg))
1780 val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1781 val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
1783 return iterative_hash_template_arg (TREE_TYPE (arg), val);
1785 case TARGET_EXPR:
1786 return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1788 case PTRMEM_CST:
1789 val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1790 return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1792 case TEMPLATE_PARM_INDEX:
1793 val = iterative_hash_template_arg
1794 (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1795 val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1796 return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1798 case TRAIT_EXPR:
1799 val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1800 val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1801 return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1803 case BASELINK:
1804 val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1805 val);
1806 return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1807 val);
1809 case MODOP_EXPR:
1810 val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1811 code = TREE_CODE (TREE_OPERAND (arg, 1));
1812 val = iterative_hash_object (code, val);
1813 return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1815 case LAMBDA_EXPR:
1816 /* [temp.over.link] Two lambda-expressions are never considered
1817 equivalent.
1819 So just hash the closure type. */
1820 return iterative_hash_template_arg (TREE_TYPE (arg), val);
1822 case CAST_EXPR:
1823 case IMPLICIT_CONV_EXPR:
1824 case STATIC_CAST_EXPR:
1825 case REINTERPRET_CAST_EXPR:
1826 case CONST_CAST_EXPR:
1827 case DYNAMIC_CAST_EXPR:
1828 case NEW_EXPR:
1829 val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1830 /* Now hash operands as usual. */
1831 break;
1833 case CALL_EXPR:
1835 tree fn = CALL_EXPR_FN (arg);
1836 if (tree name = call_expr_dependent_name (arg))
1838 if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
1839 val = iterative_hash_template_arg (TREE_OPERAND (fn, 1), val);
1840 fn = name;
1842 val = iterative_hash_template_arg (fn, val);
1843 call_expr_arg_iterator ai;
1844 for (tree x = first_call_expr_arg (arg, &ai); x;
1845 x = next_call_expr_arg (&ai))
1846 val = iterative_hash_template_arg (x, val);
1847 return val;
1850 default:
1851 break;
1854 char tclass = TREE_CODE_CLASS (code);
1855 switch (tclass)
1857 case tcc_type:
1858 if (tree ats = alias_template_specialization_p (arg, nt_transparent))
1860 // We want an alias specialization that survived strip_typedefs
1861 // to hash differently from its TYPE_CANONICAL, to avoid hash
1862 // collisions that compare as different in template_args_equal.
1863 // These could be dependent specializations that strip_typedefs
1864 // left alone, or untouched specializations because
1865 // coerce_template_parms returns the unconverted template
1866 // arguments if it sees incomplete argument packs.
1867 tree ti = TYPE_ALIAS_TEMPLATE_INFO (ats);
1868 return hash_tmpl_and_args (TI_TEMPLATE (ti), TI_ARGS (ti));
1871 switch (code)
1873 case DECLTYPE_TYPE:
1874 val = iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1875 break;
1877 case TYPENAME_TYPE:
1878 if (comparing_specializations)
1880 /* Hash the components that are relevant to TYPENAME_TYPE
1881 equivalence as determined by structural_comptypes. We
1882 can only coherently do this when comparing_specializations
1883 is set, because otherwise structural_comptypes tries
1884 resolving TYPENAME_TYPE via the current instantiation. */
1885 tree context = TYPE_MAIN_VARIANT (TYPE_CONTEXT (arg));
1886 tree fullname = TYPENAME_TYPE_FULLNAME (arg);
1887 val = iterative_hash_template_arg (context, val);
1888 val = iterative_hash_template_arg (fullname, val);
1890 break;
1892 default:
1893 if (tree canonical = TYPE_CANONICAL (arg))
1894 val = iterative_hash_object (TYPE_HASH (canonical), val);
1895 break;
1898 return val;
1900 case tcc_declaration:
1901 case tcc_constant:
1902 return iterative_hash_expr (arg, val);
1904 default:
1905 gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1906 for (int i = 0, n = cp_tree_operand_length (arg); i < n; ++i)
1907 val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1908 return val;
1912 /* Unregister the specialization SPEC as a specialization of TMPL.
1913 Replace it with NEW_SPEC, if NEW_SPEC is non-NULL. Returns true
1914 if the SPEC was listed as a specialization of TMPL.
1916 Note that SPEC has been ggc_freed, so we can't look inside it. */
1918 bool
1919 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1921 spec_entry *entry;
1922 spec_entry elt;
1924 elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1925 elt.args = TI_ARGS (tinfo);
1926 elt.spec = NULL_TREE;
1928 entry = decl_specializations->find (&elt);
1929 if (entry != NULL)
1931 gcc_assert (entry->spec == spec || entry->spec == new_spec);
1932 gcc_assert (new_spec != NULL_TREE);
1933 entry->spec = new_spec;
1934 return 1;
1937 return 0;
1940 /* Like register_specialization, but for local declarations. We are
1941 registering SPEC, an instantiation of TMPL. */
1943 void
1944 register_local_specialization (tree spec, tree tmpl)
1946 gcc_assert (tmpl != spec);
1947 local_specializations->put (tmpl, spec);
1950 /* Registers T as a specialization of itself. This is used to preserve
1951 the references to already-parsed parameters when instantiating
1952 postconditions. */
1954 void
1955 register_local_identity (tree t)
1957 local_specializations->put (t, t);
1960 /* TYPE is a class type. Returns true if TYPE is an explicitly
1961 specialized class. */
1963 bool
1964 explicit_class_specialization_p (tree type)
1966 if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1967 return false;
1968 return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1971 /* Print the list of functions at FNS, going through all the overloads
1972 for each element of the list. Alternatively, FNS cannot be a
1973 TREE_LIST, in which case it will be printed together with all the
1974 overloads.
1976 MORE and *STR should respectively be FALSE and NULL when the function
1977 is called from the outside. They are used internally on recursive
1978 calls. print_candidates manages the two parameters and leaves NULL
1979 in *STR when it ends. */
1981 static void
1982 print_candidates_1 (tree fns, char **str, bool more = false)
1984 if (TREE_CODE (fns) == TREE_LIST)
1985 for (; fns; fns = TREE_CHAIN (fns))
1986 print_candidates_1 (TREE_VALUE (fns), str, more || TREE_CHAIN (fns));
1987 else
1988 for (lkp_iterator iter (fns); iter;)
1990 tree cand = *iter;
1991 ++iter;
1993 const char *pfx = *str;
1994 if (!pfx)
1996 if (more || iter)
1997 pfx = _("candidates are:");
1998 else
1999 pfx = _("candidate is:");
2000 *str = get_spaces (pfx);
2002 inform (DECL_SOURCE_LOCATION (cand), "%s %#qD", pfx, cand);
2006 /* Print the list of candidate FNS in an error message. FNS can also
2007 be a TREE_LIST of non-functions in the case of an ambiguous lookup. */
2009 void
2010 print_candidates (tree fns)
2012 char *str = NULL;
2013 print_candidates_1 (fns, &str);
2014 free (str);
2017 /* Get a (possibly) constrained template declaration for the
2018 purpose of ordering candidates. */
2019 static tree
2020 get_template_for_ordering (tree list)
2022 gcc_assert (TREE_CODE (list) == TREE_LIST);
2023 tree f = TREE_VALUE (list);
2024 if (tree ti = DECL_TEMPLATE_INFO (f))
2025 return TI_TEMPLATE (ti);
2026 return f;
2029 /* Among candidates having the same signature, return the
2030 most constrained or NULL_TREE if there is no best candidate.
2031 If the signatures of candidates vary (e.g., template
2032 specialization vs. member function), then there can be no
2033 most constrained.
2035 Note that we don't compare constraints on the functions
2036 themselves, but rather those of their templates. */
2037 static tree
2038 most_constrained_function (tree candidates)
2040 // Try to find the best candidate in a first pass.
2041 tree champ = candidates;
2042 for (tree c = TREE_CHAIN (champ); c; c = TREE_CHAIN (c))
2044 int winner = more_constrained (get_template_for_ordering (champ),
2045 get_template_for_ordering (c));
2046 if (winner == -1)
2047 champ = c; // The candidate is more constrained
2048 else if (winner == 0)
2049 return NULL_TREE; // Neither is more constrained
2052 // Verify that the champ is better than previous candidates.
2053 for (tree c = candidates; c != champ; c = TREE_CHAIN (c)) {
2054 if (!more_constrained (get_template_for_ordering (champ),
2055 get_template_for_ordering (c)))
2056 return NULL_TREE;
2059 return champ;
2063 /* Returns the template (one of the functions given by TEMPLATE_ID)
2064 which can be specialized to match the indicated DECL with the
2065 explicit template args given in TEMPLATE_ID. The DECL may be
2066 NULL_TREE if none is available. In that case, the functions in
2067 TEMPLATE_ID are non-members.
2069 If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
2070 specialization of a member template.
2072 The TEMPLATE_COUNT is the number of references to qualifying
2073 template classes that appeared in the name of the function. See
2074 check_explicit_specialization for a more accurate description.
2076 TSK indicates what kind of template declaration (if any) is being
2077 declared. TSK_TEMPLATE indicates that the declaration given by
2078 DECL, though a FUNCTION_DECL, has template parameters, and is
2079 therefore a template function.
2081 The template args (those explicitly specified and those deduced)
2082 are output in a newly created vector *TARGS_OUT.
2084 If it is impossible to determine the result, an error message is
2085 issued. The error_mark_node is returned to indicate failure. */
2087 static tree
2088 determine_specialization (tree template_id,
2089 tree decl,
2090 tree* targs_out,
2091 int need_member_template,
2092 int template_count,
2093 tmpl_spec_kind tsk)
2095 tree fns;
2096 tree targs;
2097 tree explicit_targs;
2098 tree candidates = NULL_TREE;
2100 /* A TREE_LIST of templates of which DECL may be a specialization.
2101 The TREE_VALUE of each node is a TEMPLATE_DECL. The
2102 corresponding TREE_PURPOSE is the set of template arguments that,
2103 when used to instantiate the template, would produce a function
2104 with the signature of DECL. */
2105 tree templates = NULL_TREE;
2106 int header_count;
2107 cp_binding_level *b;
2109 *targs_out = NULL_TREE;
2111 if (template_id == error_mark_node || decl == error_mark_node)
2112 return error_mark_node;
2114 /* We shouldn't be specializing a member template of an
2115 unspecialized class template; we already gave an error in
2116 check_specialization_scope, now avoid crashing. */
2117 if (!VAR_P (decl)
2118 && template_count && DECL_CLASS_SCOPE_P (decl)
2119 && template_class_depth (DECL_CONTEXT (decl)) > 0)
2121 gcc_assert (errorcount);
2122 return error_mark_node;
2125 fns = TREE_OPERAND (template_id, 0);
2126 explicit_targs = TREE_OPERAND (template_id, 1);
2128 if (fns == error_mark_node)
2129 return error_mark_node;
2131 /* Check for baselinks. */
2132 if (BASELINK_P (fns))
2133 fns = BASELINK_FUNCTIONS (fns);
2135 if (TREE_CODE (decl) == FUNCTION_DECL && !is_overloaded_fn (fns))
2137 error_at (DECL_SOURCE_LOCATION (decl),
2138 "%qD is not a function template", fns);
2139 return error_mark_node;
2141 else if (VAR_P (decl) && !variable_template_p (fns))
2143 error ("%qD is not a variable template", fns);
2144 return error_mark_node;
2147 /* Count the number of template headers specified for this
2148 specialization. */
2149 header_count = 0;
2150 for (b = current_binding_level;
2151 b->kind == sk_template_parms;
2152 b = b->level_chain)
2153 ++header_count;
2155 tree orig_fns = fns;
2156 bool header_mismatch = false;
2158 if (variable_template_p (fns))
2160 tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (fns));
2161 targs = coerce_template_parms (parms, explicit_targs, fns,
2162 tf_warning_or_error);
2163 if (targs != error_mark_node
2164 && constraints_satisfied_p (fns, targs))
2165 templates = tree_cons (targs, fns, templates);
2167 else for (lkp_iterator iter (fns); iter; ++iter)
2169 tree fn = *iter;
2171 if (TREE_CODE (fn) == TEMPLATE_DECL)
2173 tree decl_arg_types;
2174 tree fn_arg_types;
2176 /* In case of explicit specialization, we need to check if
2177 the number of template headers appearing in the specialization
2178 is correct. This is usually done in check_explicit_specialization,
2179 but the check done there cannot be exhaustive when specializing
2180 member functions. Consider the following code:
2182 template <> void A<int>::f(int);
2183 template <> template <> void A<int>::f(int);
2185 Assuming that A<int> is not itself an explicit specialization
2186 already, the first line specializes "f" which is a non-template
2187 member function, whilst the second line specializes "f" which
2188 is a template member function. So both lines are syntactically
2189 correct, and check_explicit_specialization does not reject
2190 them.
2192 Here, we can do better, as we are matching the specialization
2193 against the declarations. We count the number of template
2194 headers, and we check if they match TEMPLATE_COUNT + 1
2195 (TEMPLATE_COUNT is the number of qualifying template classes,
2196 plus there must be another header for the member template
2197 itself).
2199 Notice that if header_count is zero, this is not a
2200 specialization but rather a template instantiation, so there
2201 is no check we can perform here. */
2202 if (header_count && header_count != template_count + 1)
2204 header_mismatch = true;
2205 continue;
2208 /* Check that the number of template arguments at the
2209 innermost level for DECL is the same as for FN. */
2210 if (current_binding_level->kind == sk_template_parms
2211 && !current_binding_level->explicit_spec_p
2212 && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
2213 != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
2214 (current_template_parms))))
2215 continue;
2217 /* DECL might be a specialization of FN. */
2218 decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2219 fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
2221 /* For a non-static member function, we need to make sure
2222 that the const qualification is the same. Since
2223 get_bindings does not try to merge the "this" parameter,
2224 we must do the comparison explicitly. */
2225 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn))
2227 if (!same_type_p (TREE_VALUE (fn_arg_types),
2228 TREE_VALUE (decl_arg_types)))
2229 continue;
2231 /* And the ref-qualification. */
2232 if (type_memfn_rqual (TREE_TYPE (decl))
2233 != type_memfn_rqual (TREE_TYPE (fn)))
2234 continue;
2237 /* Skip the "this" parameter and, for constructors of
2238 classes with virtual bases, the VTT parameter. A
2239 full specialization of a constructor will have a VTT
2240 parameter, but a template never will. */
2241 decl_arg_types
2242 = skip_artificial_parms_for (decl, decl_arg_types);
2243 fn_arg_types
2244 = skip_artificial_parms_for (fn, fn_arg_types);
2246 /* Function templates cannot be specializations; there are
2247 no partial specializations of functions. Therefore, if
2248 the type of DECL does not match FN, there is no
2249 match.
2251 Note that it should never be the case that we have both
2252 candidates added here, and for regular member functions
2253 below. */
2254 if (tsk == tsk_template)
2256 if (!comp_template_parms (DECL_TEMPLATE_PARMS (fn),
2257 current_template_parms))
2258 continue;
2259 if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2260 TREE_TYPE (TREE_TYPE (fn))))
2261 continue;
2262 if (!compparms (fn_arg_types, decl_arg_types))
2263 continue;
2265 tree freq = get_constraints (fn);
2266 tree dreq = get_constraints (decl);
2267 if (!freq != !dreq)
2268 continue;
2269 if (freq)
2271 /* C++20 CA104: Substitute directly into the
2272 constraint-expression. */
2273 tree fargs = DECL_TI_ARGS (fn);
2274 tsubst_flags_t complain = tf_none;
2275 freq = tsubst_constraint_info (freq, fargs, complain, fn);
2276 if (!cp_tree_equal (freq, dreq))
2277 continue;
2280 candidates = tree_cons (NULL_TREE, fn, candidates);
2281 continue;
2284 /* See whether this function might be a specialization of this
2285 template. Suppress access control because we might be trying
2286 to make this specialization a friend, and we have already done
2287 access control for the declaration of the specialization. */
2288 push_deferring_access_checks (dk_no_check);
2289 targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
2290 pop_deferring_access_checks ();
2292 if (!targs)
2293 /* We cannot deduce template arguments that when used to
2294 specialize TMPL will produce DECL. */
2295 continue;
2297 if (uses_template_parms (targs))
2298 /* We deduced something involving 'auto', which isn't a valid
2299 template argument. */
2300 continue;
2302 /* Save this template, and the arguments deduced. */
2303 templates = tree_cons (targs, fn, templates);
2305 else if (need_member_template)
2306 /* FN is an ordinary member function, and we need a
2307 specialization of a member template. */
2309 else if (TREE_CODE (fn) != FUNCTION_DECL)
2310 /* We can get IDENTIFIER_NODEs here in certain erroneous
2311 cases. */
2313 else if (!DECL_FUNCTION_MEMBER_P (fn))
2314 /* This is just an ordinary non-member function. Nothing can
2315 be a specialization of that. */
2317 else if (DECL_ARTIFICIAL (fn))
2318 /* Cannot specialize functions that are created implicitly. */
2320 else
2322 tree decl_arg_types;
2324 /* This is an ordinary member function. However, since
2325 we're here, we can assume its enclosing class is a
2326 template class. For example,
2328 template <typename T> struct S { void f(); };
2329 template <> void S<int>::f() {}
2331 Here, S<int>::f is a non-template, but S<int> is a
2332 template class. If FN has the same type as DECL, we
2333 might be in business. */
2335 if (!DECL_TEMPLATE_INFO (fn))
2336 /* Its enclosing class is an explicit specialization
2337 of a template class. This is not a candidate. */
2338 continue;
2340 if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2341 TREE_TYPE (TREE_TYPE (fn))))
2342 /* The return types differ. */
2343 continue;
2345 /* Adjust the type of DECL in case FN is a static member. */
2346 decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2347 if (DECL_STATIC_FUNCTION_P (fn)
2348 && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2349 decl_arg_types = TREE_CHAIN (decl_arg_types);
2351 if (!compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
2352 decl_arg_types))
2353 continue;
2355 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
2356 && (type_memfn_rqual (TREE_TYPE (decl))
2357 != type_memfn_rqual (TREE_TYPE (fn))))
2358 continue;
2360 // If the deduced arguments do not satisfy the constraints,
2361 // this is not a candidate.
2362 if (flag_concepts && !constraints_satisfied_p (fn))
2363 continue;
2365 // Add the candidate.
2366 candidates = tree_cons (NULL_TREE, fn, candidates);
2370 if (templates && TREE_CHAIN (templates))
2372 /* We have:
2374 [temp.expl.spec]
2376 It is possible for a specialization with a given function
2377 signature to be instantiated from more than one function
2378 template. In such cases, explicit specification of the
2379 template arguments must be used to uniquely identify the
2380 function template specialization being specialized.
2382 Note that here, there's no suggestion that we're supposed to
2383 determine which of the candidate templates is most
2384 specialized. However, we, also have:
2386 [temp.func.order]
2388 Partial ordering of overloaded function template
2389 declarations is used in the following contexts to select
2390 the function template to which a function template
2391 specialization refers:
2393 -- when an explicit specialization refers to a function
2394 template.
2396 So, we do use the partial ordering rules, at least for now.
2397 This extension can only serve to make invalid programs valid,
2398 so it's safe. And, there is strong anecdotal evidence that
2399 the committee intended the partial ordering rules to apply;
2400 the EDG front end has that behavior, and John Spicer claims
2401 that the committee simply forgot to delete the wording in
2402 [temp.expl.spec]. */
2403 tree tmpl = most_specialized_instantiation (templates);
2404 if (tmpl != error_mark_node)
2406 templates = tmpl;
2407 TREE_CHAIN (templates) = NULL_TREE;
2411 // Concepts allows multiple declarations of member functions
2412 // with the same signature. Like above, we need to rely on
2413 // on the partial ordering of those candidates to determine which
2414 // is the best.
2415 if (flag_concepts && candidates && TREE_CHAIN (candidates))
2417 if (tree cand = most_constrained_function (candidates))
2419 candidates = cand;
2420 TREE_CHAIN (cand) = NULL_TREE;
2424 if (templates == NULL_TREE && candidates == NULL_TREE)
2426 error ("template-id %qD for %q+D does not match any template "
2427 "declaration", template_id, decl);
2428 if (header_mismatch)
2429 inform (DECL_SOURCE_LOCATION (decl),
2430 "saw %d %<template<>%>, need %d for "
2431 "specializing a member function template",
2432 header_count, template_count + 1);
2433 print_candidates (orig_fns);
2434 return error_mark_node;
2436 else if ((templates && TREE_CHAIN (templates))
2437 || (candidates && TREE_CHAIN (candidates))
2438 || (templates && candidates))
2440 error ("ambiguous template specialization %qD for %q+D",
2441 template_id, decl);
2442 candidates = chainon (candidates, templates);
2443 print_candidates (candidates);
2444 return error_mark_node;
2447 /* We have one, and exactly one, match. */
2448 if (candidates)
2450 tree fn = TREE_VALUE (candidates);
2451 *targs_out = copy_node (DECL_TI_ARGS (fn));
2453 /* Propagate the candidate's constraints to the declaration. */
2454 if (tsk != tsk_template)
2455 set_constraints (decl, get_constraints (fn));
2457 /* DECL is a re-declaration or partial instantiation of a template
2458 function. */
2459 if (TREE_CODE (fn) == TEMPLATE_DECL)
2460 return fn;
2461 /* It was a specialization of an ordinary member function in a
2462 template class. */
2463 return DECL_TI_TEMPLATE (fn);
2466 /* It was a specialization of a template. */
2467 tree tmpl = TREE_VALUE (templates);
2468 *targs_out = add_outermost_template_args (tmpl, TREE_PURPOSE (templates));
2470 /* Propagate the template's constraints to the declaration. */
2471 if (tsk != tsk_template)
2472 set_constraints (decl, get_constraints (tmpl));
2474 return tmpl;
2477 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2478 but with the default argument values filled in from those in the
2479 TMPL_TYPES. */
2481 static tree
2482 copy_default_args_to_explicit_spec_1 (tree spec_types,
2483 tree tmpl_types)
2485 tree new_spec_types;
2487 if (!spec_types)
2488 return NULL_TREE;
2490 if (spec_types == void_list_node)
2491 return void_list_node;
2493 /* Substitute into the rest of the list. */
2494 new_spec_types =
2495 copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2496 TREE_CHAIN (tmpl_types));
2498 /* Add the default argument for this parameter. */
2499 return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2500 TREE_VALUE (spec_types),
2501 new_spec_types);
2504 /* DECL is an explicit specialization. Replicate default arguments
2505 from the template it specializes. (That way, code like:
2507 template <class T> void f(T = 3);
2508 template <> void f(double);
2509 void g () { f (); }
2511 works, as required.) An alternative approach would be to look up
2512 the correct default arguments at the call-site, but this approach
2513 is consistent with how implicit instantiations are handled. */
2515 static void
2516 copy_default_args_to_explicit_spec (tree decl)
2518 tree tmpl;
2519 tree spec_types;
2520 tree tmpl_types;
2521 tree new_spec_types;
2522 tree old_type;
2523 tree new_type;
2524 tree t;
2525 tree object_type = NULL_TREE;
2526 tree in_charge = NULL_TREE;
2527 tree vtt = NULL_TREE;
2529 /* See if there's anything we need to do. */
2530 tmpl = DECL_TI_TEMPLATE (decl);
2531 tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2532 for (t = tmpl_types; t; t = TREE_CHAIN (t))
2533 if (TREE_PURPOSE (t))
2534 break;
2535 if (!t)
2536 return;
2538 old_type = TREE_TYPE (decl);
2539 spec_types = TYPE_ARG_TYPES (old_type);
2541 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2543 /* Remove the this pointer, but remember the object's type for
2544 CV quals. */
2545 object_type = TREE_TYPE (TREE_VALUE (spec_types));
2546 spec_types = TREE_CHAIN (spec_types);
2547 tmpl_types = TREE_CHAIN (tmpl_types);
2549 if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2551 /* DECL may contain more parameters than TMPL due to the extra
2552 in-charge parameter in constructors and destructors. */
2553 in_charge = spec_types;
2554 spec_types = TREE_CHAIN (spec_types);
2556 if (DECL_HAS_VTT_PARM_P (decl))
2558 vtt = spec_types;
2559 spec_types = TREE_CHAIN (spec_types);
2563 /* Compute the merged default arguments. */
2564 new_spec_types =
2565 copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2567 /* Compute the new FUNCTION_TYPE. */
2568 if (object_type)
2570 if (vtt)
2571 new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2572 TREE_VALUE (vtt),
2573 new_spec_types);
2575 if (in_charge)
2576 /* Put the in-charge parameter back. */
2577 new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2578 TREE_VALUE (in_charge),
2579 new_spec_types);
2581 new_type = build_method_type_directly (object_type,
2582 TREE_TYPE (old_type),
2583 new_spec_types);
2585 else
2586 new_type = build_function_type (TREE_TYPE (old_type),
2587 new_spec_types);
2588 new_type = cp_build_type_attribute_variant (new_type,
2589 TYPE_ATTRIBUTES (old_type));
2590 new_type = cxx_copy_lang_qualifiers (new_type, old_type);
2592 TREE_TYPE (decl) = new_type;
2595 /* Return the number of template headers we expect to see for a definition
2596 or specialization of CTYPE or one of its non-template members. */
2599 num_template_headers_for_class (tree ctype)
2601 int num_templates = 0;
2603 while (ctype && CLASS_TYPE_P (ctype))
2605 /* You're supposed to have one `template <...>' for every
2606 template class, but you don't need one for a full
2607 specialization. For example:
2609 template <class T> struct S{};
2610 template <> struct S<int> { void f(); };
2611 void S<int>::f () {}
2613 is correct; there shouldn't be a `template <>' for the
2614 definition of `S<int>::f'. */
2615 if (!CLASSTYPE_TEMPLATE_INFO (ctype))
2616 /* If CTYPE does not have template information of any
2617 kind, then it is not a template, nor is it nested
2618 within a template. */
2619 break;
2620 if (explicit_class_specialization_p (ctype))
2621 break;
2622 if (PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (ctype)))
2623 ++num_templates;
2625 ctype = TYPE_CONTEXT (ctype);
2628 return num_templates;
2631 /* Do a simple sanity check on the template headers that precede the
2632 variable declaration DECL. */
2634 void
2635 check_template_variable (tree decl)
2637 tree ctx = CP_DECL_CONTEXT (decl);
2638 int wanted = num_template_headers_for_class (ctx);
2639 if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)
2640 && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl)))
2642 if (cxx_dialect < cxx14)
2643 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wc__14_extensions,
2644 "variable templates only available with "
2645 "%<-std=c++14%> or %<-std=gnu++14%>");
2647 // Namespace-scope variable templates should have a template header.
2648 ++wanted;
2650 if (template_header_count > wanted)
2652 auto_diagnostic_group d;
2653 bool warned = pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2654 "too many template headers for %qD "
2655 "(should be %d)",
2656 decl, wanted);
2657 if (warned && CLASS_TYPE_P (ctx)
2658 && CLASSTYPE_TEMPLATE_SPECIALIZATION (ctx))
2659 inform (DECL_SOURCE_LOCATION (decl),
2660 "members of an explicitly specialized class are defined "
2661 "without a template header");
2665 /* An explicit specialization whose declarator-id or class-head-name is not
2666 qualified shall be declared in the nearest enclosing namespace of the
2667 template, or, if the namespace is inline (7.3.1), any namespace from its
2668 enclosing namespace set.
2670 If the name declared in the explicit instantiation is an unqualified name,
2671 the explicit instantiation shall appear in the namespace where its template
2672 is declared or, if that namespace is inline (7.3.1), any namespace from its
2673 enclosing namespace set. */
2675 void
2676 check_unqualified_spec_or_inst (tree t, location_t loc)
2678 tree tmpl = most_general_template (t);
2679 if (DECL_NAMESPACE_SCOPE_P (tmpl)
2680 && !is_nested_namespace (current_namespace,
2681 CP_DECL_CONTEXT (tmpl), true))
2683 if (processing_specialization)
2684 permerror (loc, "explicit specialization of %qD outside its "
2685 "namespace must use a nested-name-specifier", tmpl);
2686 else if (processing_explicit_instantiation
2687 && cxx_dialect >= cxx11)
2688 /* This was allowed in C++98, so only pedwarn. */
2689 pedwarn (loc, OPT_Wpedantic, "explicit instantiation of %qD "
2690 "outside its namespace must use a nested-name-"
2691 "specifier", tmpl);
2695 /* Warn for a template specialization SPEC that is missing some of a set
2696 of function or type attributes that the template TEMPL is declared with.
2697 ATTRLIST is a list of additional attributes that SPEC should be taken
2698 to ultimately be declared with. */
2700 static void
2701 warn_spec_missing_attributes (tree tmpl, tree spec, tree attrlist)
2703 if (DECL_FUNCTION_TEMPLATE_P (tmpl))
2704 tmpl = DECL_TEMPLATE_RESULT (tmpl);
2706 /* Avoid warning if the difference between the primary and
2707 the specialization is not in one of the attributes below. */
2708 const char* const blacklist[] = {
2709 "alloc_align", "alloc_size", "assume_aligned", "format",
2710 "format_arg", "malloc", "nonnull", NULL
2713 /* Put together a list of the black listed attributes that the primary
2714 template is declared with that the specialization is not, in case
2715 it's not apparent from the most recent declaration of the primary. */
2716 pretty_printer str;
2717 unsigned nattrs = decls_mismatched_attributes (tmpl, spec, attrlist,
2718 blacklist, &str);
2720 if (!nattrs)
2721 return;
2723 auto_diagnostic_group d;
2724 if (warning_at (DECL_SOURCE_LOCATION (spec), OPT_Wmissing_attributes,
2725 "explicit specialization %q#D may be missing attributes",
2726 spec))
2727 inform (DECL_SOURCE_LOCATION (tmpl),
2728 nattrs > 1
2729 ? G_("missing primary template attributes %s")
2730 : G_("missing primary template attribute %s"),
2731 pp_formatted_text (&str));
2734 /* Check to see if the function just declared, as indicated in
2735 DECLARATOR, and in DECL, is a specialization of a function
2736 template. We may also discover that the declaration is an explicit
2737 instantiation at this point.
2739 Returns DECL, or an equivalent declaration that should be used
2740 instead if all goes well. Issues an error message if something is
2741 amiss. Returns error_mark_node if the error is not easily
2742 recoverable.
2744 FLAGS is a bitmask consisting of the following flags:
2746 2: The function has a definition.
2747 4: The function is a friend.
2749 The TEMPLATE_COUNT is the number of references to qualifying
2750 template classes that appeared in the name of the function. For
2751 example, in
2753 template <class T> struct S { void f(); };
2754 void S<int>::f();
2756 the TEMPLATE_COUNT would be 1. However, explicitly specialized
2757 classes are not counted in the TEMPLATE_COUNT, so that in
2759 template <class T> struct S {};
2760 template <> struct S<int> { void f(); }
2761 template <> void S<int>::f();
2763 the TEMPLATE_COUNT would be 0. (Note that this declaration is
2764 invalid; there should be no template <>.)
2766 If the function is a specialization, it is marked as such via
2767 DECL_TEMPLATE_SPECIALIZATION. Furthermore, its DECL_TEMPLATE_INFO
2768 is set up correctly, and it is added to the list of specializations
2769 for that template. */
2771 tree
2772 check_explicit_specialization (tree declarator,
2773 tree decl,
2774 int template_count,
2775 int flags,
2776 tree attrlist)
2778 int have_def = flags & 2;
2779 int is_friend = flags & 4;
2780 bool is_concept = flags & 8;
2781 int specialization = 0;
2782 int explicit_instantiation = 0;
2783 int member_specialization = 0;
2784 tree ctype = DECL_CLASS_CONTEXT (decl);
2785 tree dname = DECL_NAME (decl);
2786 tmpl_spec_kind tsk;
2788 if (is_friend)
2790 if (!processing_specialization)
2791 tsk = tsk_none;
2792 else
2793 tsk = tsk_excessive_parms;
2795 else
2796 tsk = current_tmpl_spec_kind (template_count);
2798 switch (tsk)
2800 case tsk_none:
2801 if (processing_specialization && !VAR_P (decl))
2803 specialization = 1;
2804 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2806 else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR
2807 || (DECL_LANG_SPECIFIC (decl)
2808 && DECL_IMPLICIT_INSTANTIATION (decl)))
2810 if (is_friend)
2811 /* This could be something like:
2813 template <class T> void f(T);
2814 class S { friend void f<>(int); } */
2815 specialization = 1;
2816 else
2818 /* This case handles bogus declarations like template <>
2819 template <class T> void f<int>(); */
2821 error_at (cp_expr_loc_or_input_loc (declarator),
2822 "template-id %qE in declaration of primary template",
2823 declarator);
2824 return decl;
2827 break;
2829 case tsk_invalid_member_spec:
2830 /* The error has already been reported in
2831 check_specialization_scope. */
2832 return error_mark_node;
2834 case tsk_invalid_expl_inst:
2835 error ("template parameter list used in explicit instantiation");
2837 /* Fall through. */
2839 case tsk_expl_inst:
2840 if (have_def)
2841 error ("definition provided for explicit instantiation");
2843 explicit_instantiation = 1;
2844 break;
2846 case tsk_excessive_parms:
2847 case tsk_insufficient_parms:
2848 if (tsk == tsk_excessive_parms)
2849 error ("too many template parameter lists in declaration of %qD",
2850 decl);
2851 else if (template_header_count)
2852 error("too few template parameter lists in declaration of %qD", decl);
2853 else
2854 error("explicit specialization of %qD must be introduced by "
2855 "%<template <>%>", decl);
2857 /* Fall through. */
2858 case tsk_expl_spec:
2859 if (is_concept)
2860 error ("explicit specialization declared %<concept%>");
2862 if (VAR_P (decl) && TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2863 /* In cases like template<> constexpr bool v = true;
2864 We'll give an error in check_template_variable. */
2865 break;
2867 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2868 if (ctype)
2869 member_specialization = 1;
2870 else
2871 specialization = 1;
2872 break;
2874 case tsk_template:
2875 if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2877 /* This case handles bogus declarations like template <>
2878 template <class T> void f<int>(); */
2880 if (!uses_template_parms (TREE_OPERAND (declarator, 1)))
2881 error_at (cp_expr_loc_or_input_loc (declarator),
2882 "template-id %qE in declaration of primary template",
2883 declarator);
2884 else if (variable_template_p (TREE_OPERAND (declarator, 0)))
2886 /* Partial specialization of variable template. */
2887 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2888 specialization = 1;
2889 goto ok;
2891 else if (cxx_dialect < cxx14)
2892 error_at (cp_expr_loc_or_input_loc (declarator),
2893 "non-type partial specialization %qE "
2894 "is not allowed", declarator);
2895 else
2896 error_at (cp_expr_loc_or_input_loc (declarator),
2897 "non-class, non-variable partial specialization %qE "
2898 "is not allowed", declarator);
2899 return decl;
2900 ok:;
2903 if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2904 /* This is a specialization of a member template, without
2905 specialization the containing class. Something like:
2907 template <class T> struct S {
2908 template <class U> void f (U);
2910 template <> template <class U> void S<int>::f(U) {}
2912 That's a specialization -- but of the entire template. */
2913 specialization = 1;
2914 break;
2916 default:
2917 gcc_unreachable ();
2920 if ((specialization || member_specialization)
2921 /* This doesn't apply to variable templates. */
2922 && FUNC_OR_METHOD_TYPE_P (TREE_TYPE (decl)))
2924 tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2925 for (; t; t = TREE_CHAIN (t))
2926 if (TREE_PURPOSE (t))
2928 permerror (input_location,
2929 "default argument specified in explicit specialization");
2930 break;
2934 if (specialization || member_specialization || explicit_instantiation)
2936 tree tmpl = NULL_TREE;
2937 tree targs = NULL_TREE;
2938 bool was_template_id = (TREE_CODE (declarator) == TEMPLATE_ID_EXPR);
2939 bool found_hidden = false;
2941 /* Make sure that the declarator is a TEMPLATE_ID_EXPR. */
2942 if (!was_template_id)
2944 tree fns;
2946 gcc_assert (identifier_p (declarator));
2947 if (ctype)
2948 fns = dname;
2949 else
2951 /* If there is no class context, the explicit instantiation
2952 must be at namespace scope. */
2953 gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2955 /* Find the namespace binding, using the declaration
2956 context. */
2957 fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2958 LOOK_want::NORMAL, true);
2959 if (fns == error_mark_node)
2961 /* If lookup fails, look for a friend declaration so we can
2962 give a better diagnostic. */
2963 fns = (lookup_qualified_name
2964 (CP_DECL_CONTEXT (decl), dname,
2965 LOOK_want::NORMAL | LOOK_want::HIDDEN_FRIEND,
2966 /*complain*/true));
2967 found_hidden = true;
2970 if (fns == error_mark_node || !is_overloaded_fn (fns))
2972 error ("%qD is not a template function", dname);
2973 fns = error_mark_node;
2977 declarator = lookup_template_function (fns, NULL_TREE);
2980 if (declarator == error_mark_node)
2981 return error_mark_node;
2983 if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2985 if (!explicit_instantiation)
2986 /* A specialization in class scope. This is invalid,
2987 but the error will already have been flagged by
2988 check_specialization_scope. */
2989 return error_mark_node;
2990 else
2992 /* It's not valid to write an explicit instantiation in
2993 class scope, e.g.:
2995 class C { template void f(); }
2997 This case is caught by the parser. However, on
2998 something like:
3000 template class C { void f(); };
3002 (which is invalid) we can get here. The error will be
3003 issued later. */
3007 return decl;
3009 else if (ctype != NULL_TREE
3010 && (identifier_p (TREE_OPERAND (declarator, 0))))
3012 // We'll match variable templates in start_decl.
3013 if (VAR_P (decl))
3014 return decl;
3016 /* Find the list of functions in ctype that have the same
3017 name as the declared function. */
3018 tree name = TREE_OPERAND (declarator, 0);
3020 if (constructor_name_p (name, ctype))
3022 if (DECL_CONSTRUCTOR_P (decl)
3023 ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
3024 : !CLASSTYPE_DESTRUCTOR (ctype))
3026 /* From [temp.expl.spec]:
3028 If such an explicit specialization for the member
3029 of a class template names an implicitly-declared
3030 special member function (clause _special_), the
3031 program is ill-formed.
3033 Similar language is found in [temp.explicit]. */
3034 error ("specialization of implicitly-declared special member function");
3035 return error_mark_node;
3038 name = DECL_NAME (decl);
3041 /* For a type-conversion operator, We might be looking for
3042 `operator int' which will be a specialization of
3043 `operator T'. Grab all the conversion operators, and
3044 then select from them. */
3045 tree fns = get_class_binding (ctype, IDENTIFIER_CONV_OP_P (name)
3046 ? conv_op_identifier : name);
3048 if (fns == NULL_TREE)
3050 error ("no member function %qD declared in %qT", name, ctype);
3051 return error_mark_node;
3053 else
3054 TREE_OPERAND (declarator, 0) = fns;
3057 /* Figure out what exactly is being specialized at this point.
3058 Note that for an explicit instantiation, even one for a
3059 member function, we cannot tell a priori whether the
3060 instantiation is for a member template, or just a member
3061 function of a template class. Even if a member template is
3062 being instantiated, the member template arguments may be
3063 elided if they can be deduced from the rest of the
3064 declaration. */
3065 tmpl = determine_specialization (declarator, decl,
3066 &targs,
3067 member_specialization,
3068 template_count,
3069 tsk);
3071 if (!tmpl || tmpl == error_mark_node)
3072 /* We couldn't figure out what this declaration was
3073 specializing. */
3074 return error_mark_node;
3075 else
3077 if (found_hidden && TREE_CODE (decl) == FUNCTION_DECL)
3079 auto_diagnostic_group d;
3080 if (pedwarn (DECL_SOURCE_LOCATION (decl), 0,
3081 "friend declaration %qD is not visible to "
3082 "explicit specialization", tmpl))
3083 inform (DECL_SOURCE_LOCATION (tmpl),
3084 "friend declaration here");
3087 if (!ctype && !is_friend
3088 && CP_DECL_CONTEXT (decl) == current_namespace)
3089 check_unqualified_spec_or_inst (tmpl, DECL_SOURCE_LOCATION (decl));
3091 tree gen_tmpl = most_general_template (tmpl);
3093 if (explicit_instantiation)
3095 /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
3096 is done by do_decl_instantiation later. */
3098 int arg_depth = TMPL_ARGS_DEPTH (targs);
3099 int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
3101 if (arg_depth > parm_depth)
3103 /* If TMPL is not the most general template (for
3104 example, if TMPL is a friend template that is
3105 injected into namespace scope), then there will
3106 be too many levels of TARGS. Remove some of them
3107 here. */
3108 int i;
3109 tree new_targs;
3111 new_targs = make_tree_vec (parm_depth);
3112 for (i = arg_depth - parm_depth; i < arg_depth; ++i)
3113 TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
3114 = TREE_VEC_ELT (targs, i);
3115 targs = new_targs;
3118 return instantiate_template (tmpl, targs, tf_error);
3121 /* If we thought that the DECL was a member function, but it
3122 turns out to be specializing a static member function,
3123 make DECL a static member function as well. */
3124 if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3125 && DECL_STATIC_FUNCTION_P (tmpl)
3126 && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
3127 revert_static_member_fn (decl);
3129 /* If this is a specialization of a member template of a
3130 template class, we want to return the TEMPLATE_DECL, not
3131 the specialization of it. */
3132 if (tsk == tsk_template && !was_template_id)
3134 tree result = DECL_TEMPLATE_RESULT (tmpl);
3135 SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3136 DECL_INITIAL (result) = NULL_TREE;
3137 if (have_def)
3139 tree parm;
3140 DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
3141 DECL_SOURCE_LOCATION (result)
3142 = DECL_SOURCE_LOCATION (decl);
3143 /* We want to use the argument list specified in the
3144 definition, not in the original declaration. */
3145 DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
3146 for (parm = DECL_ARGUMENTS (result); parm;
3147 parm = DECL_CHAIN (parm))
3148 DECL_CONTEXT (parm) = result;
3150 decl = register_specialization (tmpl, gen_tmpl, targs,
3151 is_friend, 0);
3152 remove_contract_attributes (result);
3153 return decl;
3156 /* Set up the DECL_TEMPLATE_INFO for DECL. */
3157 DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
3159 if (was_template_id)
3160 TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl)) = true;
3162 /* Inherit default function arguments from the template
3163 DECL is specializing. */
3164 if (DECL_FUNCTION_TEMPLATE_P (tmpl))
3165 copy_default_args_to_explicit_spec (decl);
3167 /* This specialization has the same protection as the
3168 template it specializes. */
3169 TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
3170 TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
3172 /* 7.1.1-1 [dcl.stc]
3174 A storage-class-specifier shall not be specified in an
3175 explicit specialization...
3177 The parser rejects these, so unless action is taken here,
3178 explicit function specializations will always appear with
3179 global linkage.
3181 The action recommended by the C++ CWG in response to C++
3182 defect report 605 is to make the storage class and linkage
3183 of the explicit specialization match the templated function:
3185 http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
3187 if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
3189 tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
3190 gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
3192 /* A concept cannot be specialized. */
3193 if (DECL_DECLARED_CONCEPT_P (tmpl_func))
3195 error ("explicit specialization of function concept %qD",
3196 gen_tmpl);
3197 return error_mark_node;
3200 /* This specialization has the same linkage and visibility as
3201 the function template it specializes. */
3202 TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
3203 if (! TREE_PUBLIC (decl))
3205 DECL_INTERFACE_KNOWN (decl) = 1;
3206 DECL_NOT_REALLY_EXTERN (decl) = 1;
3208 DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
3209 if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
3211 DECL_VISIBILITY_SPECIFIED (decl) = 1;
3212 DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
3216 /* If DECL is a friend declaration, declared using an
3217 unqualified name, the namespace associated with DECL may
3218 have been set incorrectly. For example, in:
3220 template <typename T> void f(T);
3221 namespace N {
3222 struct S { friend void f<int>(int); }
3225 we will have set the DECL_CONTEXT for the friend
3226 declaration to N, rather than to the global namespace. */
3227 if (DECL_NAMESPACE_SCOPE_P (decl))
3228 DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
3230 if (is_friend && !have_def)
3231 /* This is not really a declaration of a specialization.
3232 It's just the name of an instantiation. But, it's not
3233 a request for an instantiation, either. */
3234 SET_DECL_IMPLICIT_INSTANTIATION (decl);
3235 else if (TREE_CODE (decl) == FUNCTION_DECL)
3236 /* A specialization is not necessarily COMDAT. */
3237 DECL_COMDAT (decl) = (TREE_PUBLIC (decl)
3238 && DECL_DECLARED_INLINE_P (decl));
3239 else if (VAR_P (decl))
3240 DECL_COMDAT (decl) = false;
3242 /* If this is a full specialization, register it so that we can find
3243 it again. Partial specializations will be registered in
3244 process_partial_specialization. */
3245 if (!processing_template_decl)
3247 warn_spec_missing_attributes (gen_tmpl, decl, attrlist);
3249 decl = register_specialization (decl, gen_tmpl, targs,
3250 is_friend, 0);
3253 /* If this is a specialization, splice any contracts that may have
3254 been inherited from the template, removing them. */
3255 if (decl != error_mark_node && DECL_TEMPLATE_SPECIALIZATION (decl))
3256 remove_contract_attributes (decl);
3258 /* A 'structor should already have clones. */
3259 gcc_assert (decl == error_mark_node
3260 || variable_template_p (tmpl)
3261 || !(DECL_CONSTRUCTOR_P (decl)
3262 || DECL_DESTRUCTOR_P (decl))
3263 || DECL_CLONED_FUNCTION_P (DECL_CHAIN (decl)));
3267 return decl;
3270 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
3271 parameters. These are represented in the same format used for
3272 DECL_TEMPLATE_PARMS. */
3275 comp_template_parms (const_tree parms1, const_tree parms2)
3277 if (parms1 == parms2)
3278 return 1;
3280 tree t1 = TREE_VALUE (parms1);
3281 tree t2 = TREE_VALUE (parms2);
3282 int i;
3284 gcc_assert (TREE_CODE (t1) == TREE_VEC);
3285 gcc_assert (TREE_CODE (t2) == TREE_VEC);
3287 if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
3288 return 0;
3290 for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
3292 tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
3293 tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
3295 /* If either of the template parameters are invalid, assume
3296 they match for the sake of error recovery. */
3297 if (error_operand_p (parm1) || error_operand_p (parm2))
3298 return 1;
3300 if (TREE_CODE (parm1) != TREE_CODE (parm2))
3301 return 0;
3303 if (TREE_CODE (parm1) == TYPE_DECL
3304 && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm1))
3305 == TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm2))))
3306 continue;
3307 else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
3308 return 0;
3311 return 1;
3314 /* Returns true if two template parameters are declared with
3315 equivalent constraints. */
3317 static bool
3318 template_parameter_constraints_equivalent_p (const_tree parm1, const_tree parm2)
3320 tree req1 = TREE_TYPE (parm1);
3321 tree req2 = TREE_TYPE (parm2);
3322 if (!req1 != !req2)
3323 return false;
3324 if (req1)
3325 return cp_tree_equal (req1, req2);
3326 return true;
3329 /* Returns true when two template parameters are equivalent. */
3331 static bool
3332 template_parameters_equivalent_p (const_tree parm1, const_tree parm2)
3334 tree decl1 = TREE_VALUE (parm1);
3335 tree decl2 = TREE_VALUE (parm2);
3337 /* If either of the template parameters are invalid, assume
3338 they match for the sake of error recovery. */
3339 if (error_operand_p (decl1) || error_operand_p (decl2))
3340 return true;
3342 /* ... they declare parameters of the same kind. */
3343 if (TREE_CODE (decl1) != TREE_CODE (decl2))
3344 return false;
3346 /* ... one parameter was introduced by a parameter declaration, then
3347 both are. This case arises as a result of eagerly rewriting declarations
3348 during parsing. */
3349 if (DECL_IMPLICIT_TEMPLATE_PARM_P (decl1)
3350 != DECL_IMPLICIT_TEMPLATE_PARM_P (decl2))
3351 return false;
3353 /* ... if either declares a pack, they both do. */
3354 if (template_parameter_pack_p (decl1) != template_parameter_pack_p (decl2))
3355 return false;
3357 if (TREE_CODE (decl1) == PARM_DECL)
3359 /* ... if they declare non-type parameters, the types are equivalent. */
3360 if (!same_type_p (TREE_TYPE (decl1), TREE_TYPE (decl2)))
3361 return false;
3363 else if (TREE_CODE (decl2) == TEMPLATE_DECL)
3365 /* ... if they declare template template parameters, their template
3366 parameter lists are equivalent. */
3367 if (!template_heads_equivalent_p (decl1, decl2))
3368 return false;
3371 /* ... if they are declared with a qualified-concept name, they both
3372 are, and those names are equivalent. */
3373 return template_parameter_constraints_equivalent_p (parm1, parm2);
3376 /* Returns true if two template parameters lists are equivalent.
3377 Two template parameter lists are equivalent if they have the
3378 same length and their corresponding parameters are equivalent.
3380 PARMS1 and PARMS2 are TREE_LISTs containing TREE_VECs: the
3381 data structure returned by DECL_TEMPLATE_PARMS.
3383 This is generally the same implementation as comp_template_parms
3384 except that it also the concept names and arguments used to
3385 introduce parameters. */
3387 static bool
3388 template_parameter_lists_equivalent_p (const_tree parms1, const_tree parms2)
3390 if (parms1 == parms2)
3391 return true;
3393 tree list1 = TREE_VALUE (parms1);
3394 tree list2 = TREE_VALUE (parms2);
3396 if (TREE_VEC_LENGTH (list1) != TREE_VEC_LENGTH (list2))
3397 return 0;
3399 for (int i = 0; i < TREE_VEC_LENGTH (list2); ++i)
3401 tree parm1 = TREE_VEC_ELT (list1, i);
3402 tree parm2 = TREE_VEC_ELT (list2, i);
3403 if (!template_parameters_equivalent_p (parm1, parm2))
3404 return false;
3407 return true;
3410 /* Return true if the requires-clause of the template parameter lists are
3411 equivalent and false otherwise. */
3412 static bool
3413 template_requirements_equivalent_p (const_tree parms1, const_tree parms2)
3415 tree req1 = TEMPLATE_PARMS_CONSTRAINTS (parms1);
3416 tree req2 = TEMPLATE_PARMS_CONSTRAINTS (parms2);
3417 if ((req1 != NULL_TREE) != (req2 != NULL_TREE))
3418 return false;
3419 if (!cp_tree_equal (req1, req2))
3420 return false;
3421 return true;
3424 /* Returns true if two template heads are equivalent. 17.6.6.1p6:
3425 Two template heads are equivalent if their template parameter
3426 lists are equivalent and their requires clauses are equivalent.
3428 In pre-C++20, this is equivalent to calling comp_template_parms
3429 for the template parameters of TMPL1 and TMPL2. */
3431 bool
3432 template_heads_equivalent_p (const_tree tmpl1, const_tree tmpl2)
3434 tree parms1 = DECL_TEMPLATE_PARMS (tmpl1);
3435 tree parms2 = DECL_TEMPLATE_PARMS (tmpl2);
3437 /* Don't change the matching rules for pre-C++20. */
3438 if (cxx_dialect < cxx20)
3439 return comp_template_parms (parms1, parms2);
3441 /* ... have the same number of template parameters, and their
3442 corresponding parameters are equivalent. */
3443 if (!template_parameter_lists_equivalent_p (parms1, parms2))
3444 return false;
3446 /* ... if either has a requires-clause, they both do and their
3447 corresponding constraint-expressions are equivalent. */
3448 return template_requirements_equivalent_p (parms1, parms2);
3451 /* Determine whether PARM is a parameter pack. */
3453 bool
3454 template_parameter_pack_p (const_tree parm)
3456 /* Determine if we have a non-type template parameter pack. */
3457 if (TREE_CODE (parm) == PARM_DECL)
3458 return (DECL_TEMPLATE_PARM_P (parm)
3459 && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
3460 if (TREE_CODE (parm) == TEMPLATE_PARM_INDEX)
3461 return TEMPLATE_PARM_PARAMETER_PACK (parm);
3463 /* If this is a list of template parameters, we could get a
3464 TYPE_DECL or a TEMPLATE_DECL. */
3465 if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
3466 parm = TREE_TYPE (parm);
3468 /* Otherwise it must be a type template parameter. */
3469 return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
3470 || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
3471 && TEMPLATE_TYPE_PARAMETER_PACK (parm));
3474 /* Determine if T is a function parameter pack. */
3476 bool
3477 function_parameter_pack_p (const_tree t)
3479 if (t && TREE_CODE (t) == PARM_DECL)
3480 return DECL_PACK_P (t);
3481 return false;
3484 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
3485 PRIMARY_FUNC_TMPL_INST is a primary function template instantiation. */
3487 tree
3488 get_function_template_decl (const_tree primary_func_tmpl_inst)
3490 if (! primary_func_tmpl_inst
3491 || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
3492 || ! primary_template_specialization_p (primary_func_tmpl_inst))
3493 return NULL;
3495 return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
3498 /* Return true iff the function parameter PARAM_DECL was expanded
3499 from the function parameter pack PACK. */
3501 bool
3502 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
3504 if (DECL_ARTIFICIAL (param_decl)
3505 || !function_parameter_pack_p (pack))
3506 return false;
3508 /* The parameter pack and its pack arguments have the same
3509 DECL_PARM_INDEX. */
3510 return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
3513 /* Determine whether ARGS describes a variadic template args list,
3514 i.e., one that is terminated by a template argument pack. */
3516 static bool
3517 template_args_variadic_p (tree args)
3519 int nargs;
3520 tree last_parm;
3522 if (args == NULL_TREE)
3523 return false;
3525 args = INNERMOST_TEMPLATE_ARGS (args);
3526 nargs = TREE_VEC_LENGTH (args);
3528 if (nargs == 0)
3529 return false;
3531 last_parm = TREE_VEC_ELT (args, nargs - 1);
3533 return ARGUMENT_PACK_P (last_parm);
3536 /* Generate a new name for the parameter pack name NAME (an
3537 IDENTIFIER_NODE) that incorporates its */
3539 static tree
3540 make_ith_pack_parameter_name (tree name, int i)
3542 /* Munge the name to include the parameter index. */
3543 #define NUMBUF_LEN 128
3544 char numbuf[NUMBUF_LEN];
3545 char* newname;
3546 int newname_len;
3548 if (name == NULL_TREE)
3549 return name;
3550 snprintf (numbuf, NUMBUF_LEN, "%i", i);
3551 newname_len = IDENTIFIER_LENGTH (name)
3552 + strlen (numbuf) + 2;
3553 newname = (char*)alloca (newname_len);
3554 snprintf (newname, newname_len,
3555 "%s#%i", IDENTIFIER_POINTER (name), i);
3556 return get_identifier (newname);
3559 /* Return true if T is a primary function, class or alias template
3560 specialization, not including the template pattern. */
3562 bool
3563 primary_template_specialization_p (const_tree t)
3565 if (!t)
3566 return false;
3568 if (VAR_OR_FUNCTION_DECL_P (t))
3569 return (DECL_LANG_SPECIFIC (t)
3570 && DECL_USE_TEMPLATE (t)
3571 && DECL_TEMPLATE_INFO (t)
3572 && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t)));
3573 else if (CLASS_TYPE_P (t) && !TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
3574 return (CLASSTYPE_TEMPLATE_INFO (t)
3575 && CLASSTYPE_USE_TEMPLATE (t)
3576 && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)));
3577 else if (alias_template_specialization_p (t, nt_transparent))
3578 return true;
3579 return false;
3582 /* Return true if PARM is a template template parameter. */
3584 bool
3585 template_template_parameter_p (const_tree parm)
3587 return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
3590 /* Return true iff PARM is a DECL representing a type template
3591 parameter. */
3593 bool
3594 template_type_parameter_p (const_tree parm)
3596 return (parm
3597 && (TREE_CODE (parm) == TYPE_DECL
3598 || TREE_CODE (parm) == TEMPLATE_DECL)
3599 && DECL_TEMPLATE_PARM_P (parm));
3602 /* Return the template parameters of T if T is a
3603 primary template instantiation, NULL otherwise. */
3605 tree
3606 get_primary_template_innermost_parameters (const_tree t)
3608 tree parms = NULL, template_info = NULL;
3610 if ((template_info = get_template_info (t))
3611 && primary_template_specialization_p (t))
3612 parms = INNERMOST_TEMPLATE_PARMS
3613 (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
3615 return parms;
3618 /* Returns the template arguments of T if T is a template instantiation,
3619 NULL otherwise. */
3621 tree
3622 get_template_innermost_arguments (const_tree t)
3624 tree args = NULL, template_info = NULL;
3626 if ((template_info = get_template_info (t))
3627 && TI_ARGS (template_info))
3628 args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
3630 return args;
3633 /* Return the argument pack elements of T if T is a template argument pack,
3634 NULL otherwise. */
3636 tree
3637 get_template_argument_pack_elems (const_tree t)
3639 if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
3640 && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
3641 return NULL;
3643 return ARGUMENT_PACK_ARGS (t);
3646 /* In an ARGUMENT_PACK_SELECT, the actual underlying argument that the
3647 ARGUMENT_PACK_SELECT represents. */
3649 static tree
3650 argument_pack_select_arg (tree t)
3652 tree args = ARGUMENT_PACK_ARGS (ARGUMENT_PACK_SELECT_FROM_PACK (t));
3653 tree arg = TREE_VEC_ELT (args, ARGUMENT_PACK_SELECT_INDEX (t));
3655 /* If the selected argument is an expansion E, that most likely means we were
3656 called from gen_elem_of_pack_expansion_instantiation during the
3657 substituting of an argument pack (of which the Ith element is a pack
3658 expansion, where I is ARGUMENT_PACK_SELECT_INDEX) into a pack expansion.
3659 In this case, the Ith element resulting from this substituting is going to
3660 be a pack expansion, which pattern is the pattern of E. Let's return the
3661 pattern of E, and gen_elem_of_pack_expansion_instantiation will build the
3662 resulting pack expansion from it. */
3663 if (PACK_EXPANSION_P (arg))
3665 /* Make sure we aren't throwing away arg info. */
3666 gcc_assert (!PACK_EXPANSION_EXTRA_ARGS (arg));
3667 arg = PACK_EXPANSION_PATTERN (arg);
3670 return arg;
3673 /* Return a modification of ARGS that's suitable for preserving inside a hash
3674 table. In particular, this replaces each ARGUMENT_PACK_SELECT with its
3675 underlying argument. ARGS is copied (upon modification) iff COW_P. */
3677 static tree
3678 preserve_args (tree args, bool cow_p = true)
3680 if (!args)
3681 return NULL_TREE;
3683 for (int i = 0, len = TREE_VEC_LENGTH (args); i < len; ++i)
3685 tree t = TREE_VEC_ELT (args, i);
3686 tree r;
3687 if (!t)
3688 r = NULL_TREE;
3689 else if (TREE_CODE (t) == ARGUMENT_PACK_SELECT)
3690 r = argument_pack_select_arg (t);
3691 else if (TREE_CODE (t) == TREE_VEC)
3692 r = preserve_args (t, cow_p);
3693 else
3694 r = t;
3695 if (r != t)
3697 if (cow_p)
3699 args = copy_template_args (args);
3700 cow_p = false;
3702 TREE_VEC_ELT (args, i) = r;
3706 return args;
3709 /* True iff FN is a function representing a built-in variadic parameter
3710 pack. */
3712 bool
3713 builtin_pack_fn_p (tree fn)
3715 if (!fn
3716 || TREE_CODE (fn) != FUNCTION_DECL
3717 || !DECL_IS_UNDECLARED_BUILTIN (fn))
3718 return false;
3720 if (id_equal (DECL_NAME (fn), "__integer_pack"))
3721 return true;
3723 return false;
3726 /* True iff CALL is a call to a function representing a built-in variadic
3727 parameter pack. */
3729 static bool
3730 builtin_pack_call_p (tree call)
3732 if (TREE_CODE (call) != CALL_EXPR)
3733 return false;
3734 return builtin_pack_fn_p (CALL_EXPR_FN (call));
3737 /* Return a TREE_VEC for the expansion of __integer_pack(HI). */
3739 static tree
3740 expand_integer_pack (tree call, tree args, tsubst_flags_t complain,
3741 tree in_decl)
3743 tree ohi = CALL_EXPR_ARG (call, 0);
3744 tree hi = tsubst_expr (ohi, args, complain, in_decl);
3746 if (instantiation_dependent_expression_p (hi))
3748 if (hi != ohi)
3750 /* Work around maybe_convert_nontype_argument not doing this for
3751 dependent arguments. Don't use IMPLICIT_CONV_EXPR_NONTYPE_ARG
3752 because that will make tsubst_expr ignore it. */
3753 tree type = tsubst (TREE_TYPE (ohi), args, complain, in_decl);
3754 if (!TREE_TYPE (hi) || !same_type_p (type, TREE_TYPE (hi)))
3755 hi = build1 (IMPLICIT_CONV_EXPR, type, hi);
3757 call = copy_node (call);
3758 CALL_EXPR_ARG (call, 0) = hi;
3760 tree ex = make_pack_expansion (call, complain);
3761 tree vec = make_tree_vec (1);
3762 TREE_VEC_ELT (vec, 0) = ex;
3763 return vec;
3765 else
3767 hi = instantiate_non_dependent_expr (hi, complain);
3768 hi = cxx_constant_value (hi, complain);
3769 int len = valid_constant_size_p (hi) ? tree_to_shwi (hi) : -1;
3771 /* Calculate the largest value of len that won't make the size of the vec
3772 overflow an int. The compiler will exceed resource limits long before
3773 this, but it seems a decent place to diagnose. */
3774 int max = ((INT_MAX - sizeof (tree_vec)) / sizeof (tree)) + 1;
3776 if (len < 0 || len > max)
3778 if ((complain & tf_error)
3779 && hi != error_mark_node)
3780 error ("argument to %<__integer_pack%> must be between 0 and %d",
3781 max);
3782 return error_mark_node;
3785 tree vec = make_tree_vec (len);
3787 for (int i = 0; i < len; ++i)
3788 TREE_VEC_ELT (vec, i) = size_int (i);
3790 return vec;
3794 /* Return a TREE_VEC for the expansion of built-in template parameter pack
3795 CALL. */
3797 static tree
3798 expand_builtin_pack_call (tree call, tree args, tsubst_flags_t complain,
3799 tree in_decl)
3801 if (!builtin_pack_call_p (call))
3802 return NULL_TREE;
3804 tree fn = CALL_EXPR_FN (call);
3806 if (id_equal (DECL_NAME (fn), "__integer_pack"))
3807 return expand_integer_pack (call, args, complain, in_decl);
3809 return NULL_TREE;
3812 /* Return true if the tree T has the extra args mechanism for
3813 avoiding partial instantiation. */
3815 static bool
3816 has_extra_args_mechanism_p (const_tree t)
3818 return (PACK_EXPANSION_P (t) /* PACK_EXPANSION_EXTRA_ARGS */
3819 || TREE_CODE (t) == REQUIRES_EXPR /* REQUIRES_EXPR_EXTRA_ARGS */
3820 || (TREE_CODE (t) == IF_STMT
3821 && IF_STMT_CONSTEXPR_P (t))); /* IF_STMT_EXTRA_ARGS */
3824 /* Structure used to track the progress of find_parameter_packs_r. */
3825 struct find_parameter_pack_data
3827 /* TREE_LIST that will contain all of the parameter packs found by
3828 the traversal. */
3829 tree* parameter_packs;
3831 /* Set of AST nodes that have been visited by the traversal. */
3832 hash_set<tree> *visited;
3834 /* True iff we're making a type pack expansion. */
3835 bool type_pack_expansion_p;
3837 /* True iff we found a subtree that has the extra args mechanism. */
3838 bool found_extra_args_tree_p = false;
3841 /* Identifies all of the argument packs that occur in a template
3842 argument and appends them to the TREE_LIST inside DATA, which is a
3843 find_parameter_pack_data structure. This is a subroutine of
3844 make_pack_expansion and uses_parameter_packs. */
3845 static tree
3846 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
3848 tree t = *tp;
3849 struct find_parameter_pack_data* ppd =
3850 (struct find_parameter_pack_data*)data;
3851 bool parameter_pack_p = false;
3853 #define WALK_SUBTREE(NODE) \
3854 cp_walk_tree (&(NODE), &find_parameter_packs_r, \
3855 ppd, ppd->visited) \
3857 /* Don't look through typedefs; we are interested in whether a
3858 parameter pack is actually written in the expression/type we're
3859 looking at, not the target type. */
3860 if (TYPE_P (t) && typedef_variant_p (t))
3862 /* But do look at arguments for an alias template. */
3863 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
3864 cp_walk_tree (&TI_ARGS (tinfo),
3865 &find_parameter_packs_r,
3866 ppd, ppd->visited);
3867 *walk_subtrees = 0;
3868 return NULL_TREE;
3871 /* Identify whether this is a parameter pack or not. */
3872 switch (TREE_CODE (t))
3874 case TEMPLATE_PARM_INDEX:
3875 if (TEMPLATE_PARM_PARAMETER_PACK (t))
3876 parameter_pack_p = true;
3877 break;
3879 case TEMPLATE_TYPE_PARM:
3880 t = TYPE_MAIN_VARIANT (t);
3881 /* FALLTHRU */
3882 case TEMPLATE_TEMPLATE_PARM:
3883 /* If the placeholder appears in the decl-specifier-seq of a function
3884 parameter pack (14.6.3), or the type-specifier-seq of a type-id that
3885 is a pack expansion, the invented template parameter is a template
3886 parameter pack. */
3887 if (ppd->type_pack_expansion_p && is_auto (t))
3888 TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
3889 if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3890 parameter_pack_p = true;
3891 break;
3893 case FIELD_DECL:
3894 case PARM_DECL:
3895 if (DECL_PACK_P (t))
3897 /* We don't want to walk into the type of a PARM_DECL,
3898 because we don't want to see the type parameter pack. */
3899 *walk_subtrees = 0;
3900 parameter_pack_p = true;
3902 break;
3904 case VAR_DECL:
3905 if (DECL_PACK_P (t))
3907 /* We don't want to walk into the type of a variadic capture proxy,
3908 because we don't want to see the type parameter pack. */
3909 *walk_subtrees = 0;
3910 parameter_pack_p = true;
3912 else if (variable_template_specialization_p (t))
3914 cp_walk_tree (&DECL_TI_ARGS (t),
3915 find_parameter_packs_r,
3916 ppd, ppd->visited);
3917 *walk_subtrees = 0;
3919 break;
3921 case CALL_EXPR:
3922 if (builtin_pack_call_p (t))
3923 parameter_pack_p = true;
3924 break;
3926 case BASES:
3927 parameter_pack_p = true;
3928 break;
3929 default:
3930 /* Not a parameter pack. */
3931 break;
3934 if (parameter_pack_p)
3936 /* Add this parameter pack to the list. */
3937 *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
3940 if (has_extra_args_mechanism_p (t) && !PACK_EXPANSION_P (t))
3941 ppd->found_extra_args_tree_p = true;
3943 if (TYPE_P (t))
3944 cp_walk_tree (&TYPE_CONTEXT (t),
3945 &find_parameter_packs_r, ppd, ppd->visited);
3947 /* This switch statement will return immediately if we don't find a
3948 parameter pack. ??? Should some of these be in cp_walk_subtrees? */
3949 switch (TREE_CODE (t))
3951 case BOUND_TEMPLATE_TEMPLATE_PARM:
3952 /* Check the template itself. */
3953 cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)),
3954 &find_parameter_packs_r, ppd, ppd->visited);
3955 return NULL_TREE;
3957 case DECL_EXPR:
3959 tree decl = DECL_EXPR_DECL (t);
3960 /* Ignore the declaration of a capture proxy for a parameter pack. */
3961 if (is_capture_proxy (decl))
3962 *walk_subtrees = 0;
3963 if (is_typedef_decl (decl))
3964 /* Since we stop at typedefs above, we need to look through them at
3965 the point of the DECL_EXPR. */
3966 cp_walk_tree (&DECL_ORIGINAL_TYPE (decl),
3967 &find_parameter_packs_r, ppd, ppd->visited);
3968 return NULL_TREE;
3971 case TEMPLATE_DECL:
3972 if (!DECL_TEMPLATE_TEMPLATE_PARM_P (t))
3973 return NULL_TREE;
3974 cp_walk_tree (&TREE_TYPE (t),
3975 &find_parameter_packs_r, ppd, ppd->visited);
3976 return NULL_TREE;
3978 case TYPE_PACK_EXPANSION:
3979 case EXPR_PACK_EXPANSION:
3980 *walk_subtrees = 0;
3981 return NULL_TREE;
3983 case INTEGER_TYPE:
3984 cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r,
3985 ppd, ppd->visited);
3986 *walk_subtrees = 0;
3987 return NULL_TREE;
3989 case IDENTIFIER_NODE:
3990 cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd,
3991 ppd->visited);
3992 *walk_subtrees = 0;
3993 return NULL_TREE;
3995 case LAMBDA_EXPR:
3997 /* Since we defer implicit capture, look in the parms and body. */
3998 tree fn = lambda_function (t);
3999 cp_walk_tree (&TREE_TYPE (fn), &find_parameter_packs_r, ppd,
4000 ppd->visited);
4001 cp_walk_tree (&DECL_SAVED_TREE (fn), &find_parameter_packs_r, ppd,
4002 ppd->visited);
4003 return NULL_TREE;
4006 case DECLTYPE_TYPE:
4008 /* When traversing a DECLTYPE_TYPE_EXPR, we need to set
4009 type_pack_expansion_p to false so that any placeholders
4010 within the expression don't get marked as parameter packs. */
4011 bool type_pack_expansion_p = ppd->type_pack_expansion_p;
4012 ppd->type_pack_expansion_p = false;
4013 cp_walk_tree (&DECLTYPE_TYPE_EXPR (t), &find_parameter_packs_r,
4014 ppd, ppd->visited);
4015 ppd->type_pack_expansion_p = type_pack_expansion_p;
4016 *walk_subtrees = 0;
4017 return NULL_TREE;
4020 case IF_STMT:
4021 cp_walk_tree (&IF_COND (t), &find_parameter_packs_r,
4022 ppd, ppd->visited);
4023 cp_walk_tree (&THEN_CLAUSE (t), &find_parameter_packs_r,
4024 ppd, ppd->visited);
4025 cp_walk_tree (&ELSE_CLAUSE (t), &find_parameter_packs_r,
4026 ppd, ppd->visited);
4027 /* Don't walk into IF_STMT_EXTRA_ARGS. */
4028 *walk_subtrees = 0;
4029 return NULL_TREE;
4031 case TAG_DEFN:
4032 t = TREE_TYPE (t);
4033 if (CLASS_TYPE_P (t))
4035 /* Local class, need to look through the whole definition.
4036 TYPE_BINFO might be unset for a partial instantiation. */
4037 if (TYPE_BINFO (t))
4038 for (tree bb : BINFO_BASE_BINFOS (TYPE_BINFO (t)))
4039 cp_walk_tree (&BINFO_TYPE (bb), &find_parameter_packs_r,
4040 ppd, ppd->visited);
4042 else
4043 /* Enum, look at the values. */
4044 for (tree l = TYPE_VALUES (t); l; l = TREE_CHAIN (l))
4045 cp_walk_tree (&DECL_INITIAL (TREE_VALUE (l)),
4046 &find_parameter_packs_r,
4047 ppd, ppd->visited);
4048 return NULL_TREE;
4050 case FUNCTION_TYPE:
4051 case METHOD_TYPE:
4052 WALK_SUBTREE (TYPE_RAISES_EXCEPTIONS (t));
4053 break;
4055 default:
4056 return NULL_TREE;
4059 #undef WALK_SUBTREE
4061 return NULL_TREE;
4064 /* Determines if the expression or type T uses any parameter packs. */
4065 tree
4066 uses_parameter_packs (tree t)
4068 tree parameter_packs = NULL_TREE;
4069 struct find_parameter_pack_data ppd;
4070 ppd.parameter_packs = &parameter_packs;
4071 ppd.visited = new hash_set<tree>;
4072 ppd.type_pack_expansion_p = false;
4073 cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4074 delete ppd.visited;
4075 return parameter_packs;
4078 /* Turn ARG, which may be an expression, type, or a TREE_LIST
4079 representation a base-class initializer into a parameter pack
4080 expansion. If all goes well, the resulting node will be an
4081 EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
4082 respectively. */
4083 tree
4084 make_pack_expansion (tree arg, tsubst_flags_t complain)
4086 tree result;
4087 tree parameter_packs = NULL_TREE;
4088 bool for_types = false;
4089 struct find_parameter_pack_data ppd;
4091 if (!arg || arg == error_mark_node)
4092 return arg;
4094 if (TREE_CODE (arg) == TREE_LIST && TREE_PURPOSE (arg))
4096 /* A TREE_LIST with a non-null TREE_PURPOSE is for a base
4097 class initializer. In this case, the TREE_PURPOSE will be a
4098 _TYPE node (representing the base class expansion we're
4099 initializing) and the TREE_VALUE will be a TREE_LIST
4100 containing the initialization arguments.
4102 The resulting expansion looks somewhat different from most
4103 expansions. Rather than returning just one _EXPANSION, we
4104 return a TREE_LIST whose TREE_PURPOSE is a
4105 TYPE_PACK_EXPANSION containing the bases that will be
4106 initialized. The TREE_VALUE will be identical to the
4107 original TREE_VALUE, which is a list of arguments that will
4108 be passed to each base. We do not introduce any new pack
4109 expansion nodes into the TREE_VALUE (although it is possible
4110 that some already exist), because the TREE_PURPOSE and
4111 TREE_VALUE all need to be expanded together with the same
4112 _EXPANSION node. Note that the TYPE_PACK_EXPANSION in the
4113 resulting TREE_PURPOSE will mention the parameter packs in
4114 both the bases and the arguments to the bases. */
4115 tree purpose;
4116 tree value;
4117 tree parameter_packs = NULL_TREE;
4119 /* Determine which parameter packs will be used by the base
4120 class expansion. */
4121 ppd.visited = new hash_set<tree>;
4122 ppd.parameter_packs = &parameter_packs;
4123 ppd.type_pack_expansion_p = false;
4124 gcc_assert (TYPE_P (TREE_PURPOSE (arg)));
4125 cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r,
4126 &ppd, ppd.visited);
4128 if (parameter_packs == NULL_TREE)
4130 if (complain & tf_error)
4131 error ("base initializer expansion %qT contains no parameter packs",
4132 arg);
4133 delete ppd.visited;
4134 return error_mark_node;
4137 if (TREE_VALUE (arg) != void_type_node)
4139 /* Collect the sets of parameter packs used in each of the
4140 initialization arguments. */
4141 for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
4143 /* Determine which parameter packs will be expanded in this
4144 argument. */
4145 cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r,
4146 &ppd, ppd.visited);
4150 delete ppd.visited;
4152 /* Create the pack expansion type for the base type. */
4153 purpose = cxx_make_type (TYPE_PACK_EXPANSION);
4154 PACK_EXPANSION_PATTERN (purpose) = TREE_PURPOSE (arg);
4155 PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
4156 PACK_EXPANSION_LOCAL_P (purpose) = at_function_scope_p ();
4158 /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
4159 they will rarely be compared to anything. */
4160 SET_TYPE_STRUCTURAL_EQUALITY (purpose);
4162 return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
4165 if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
4166 for_types = true;
4168 /* Build the PACK_EXPANSION_* node. */
4169 result = for_types
4170 ? cxx_make_type (TYPE_PACK_EXPANSION)
4171 : make_node (EXPR_PACK_EXPANSION);
4172 PACK_EXPANSION_PATTERN (result) = arg;
4173 if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
4175 /* Propagate type and const-expression information. */
4176 TREE_TYPE (result) = TREE_TYPE (arg);
4177 TREE_CONSTANT (result) = TREE_CONSTANT (arg);
4178 /* Mark this read now, since the expansion might be length 0. */
4179 mark_exp_read (arg);
4181 else
4182 /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
4183 they will rarely be compared to anything. */
4184 SET_TYPE_STRUCTURAL_EQUALITY (result);
4186 /* Determine which parameter packs will be expanded. */
4187 ppd.parameter_packs = &parameter_packs;
4188 ppd.visited = new hash_set<tree>;
4189 ppd.type_pack_expansion_p = TYPE_P (arg);
4190 cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
4191 delete ppd.visited;
4193 /* Make sure we found some parameter packs. */
4194 if (parameter_packs == NULL_TREE)
4196 if (complain & tf_error)
4198 if (TYPE_P (arg))
4199 error ("expansion pattern %qT contains no parameter packs", arg);
4200 else
4201 error ("expansion pattern %qE contains no parameter packs", arg);
4203 return error_mark_node;
4205 PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
4207 PACK_EXPANSION_LOCAL_P (result) = at_function_scope_p ();
4208 if (ppd.found_extra_args_tree_p)
4209 /* If the pattern of this pack expansion contains a subtree that has
4210 the extra args mechanism for avoiding partial instantiation, then
4211 force this pack expansion to also use extra args. Otherwise
4212 partial instantiation of this pack expansion may not lower the
4213 level of some parameter packs within the pattern, which would
4214 confuse tsubst_pack_expansion later (PR101764). */
4215 PACK_EXPANSION_FORCE_EXTRA_ARGS_P (result) = true;
4217 return result;
4220 /* Checks T for any "bare" parameter packs, which have not yet been
4221 expanded, and issues an error if any are found. This operation can
4222 only be done on full expressions or types (e.g., an expression
4223 statement, "if" condition, etc.), because we could have expressions like:
4225 foo(f(g(h(args)))...)
4227 where "args" is a parameter pack. check_for_bare_parameter_packs
4228 should not be called for the subexpressions args, h(args),
4229 g(h(args)), or f(g(h(args))), because we would produce erroneous
4230 error messages.
4232 Returns TRUE and emits an error if there were bare parameter packs,
4233 returns FALSE otherwise. */
4234 bool
4235 check_for_bare_parameter_packs (tree t, location_t loc /* = UNKNOWN_LOCATION */)
4237 tree parameter_packs = NULL_TREE;
4238 struct find_parameter_pack_data ppd;
4240 if (!processing_template_decl || !t || t == error_mark_node)
4241 return false;
4243 if (TREE_CODE (t) == TYPE_DECL)
4244 t = TREE_TYPE (t);
4246 ppd.parameter_packs = &parameter_packs;
4247 ppd.visited = new hash_set<tree>;
4248 ppd.type_pack_expansion_p = false;
4249 cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4250 delete ppd.visited;
4252 if (!parameter_packs)
4253 return false;
4255 if (loc == UNKNOWN_LOCATION)
4256 loc = cp_expr_loc_or_input_loc (t);
4258 /* It's OK for a lambda to have an unexpanded parameter pack from the
4259 containing context, but do complain about unexpanded capture packs. */
4260 tree lam = current_lambda_expr ();
4261 if (lam)
4262 lam = TREE_TYPE (lam);
4264 if (lam && lam != current_class_type)
4266 /* We're in a lambda, but it isn't the innermost class.
4267 This should work, but currently doesn't. */
4268 sorry_at (loc, "unexpanded parameter pack in local class in lambda");
4269 return true;
4272 if (lam && CLASSTYPE_TEMPLATE_INFO (lam))
4273 for (; parameter_packs;
4274 parameter_packs = TREE_CHAIN (parameter_packs))
4276 tree pack = TREE_VALUE (parameter_packs);
4277 if (is_capture_proxy (pack)
4278 || (TREE_CODE (pack) == PARM_DECL
4279 && DECL_CONTEXT (DECL_CONTEXT (pack)) == lam))
4280 break;
4283 if (parameter_packs)
4285 error_at (loc, "parameter packs not expanded with %<...%>:");
4286 while (parameter_packs)
4288 tree pack = TREE_VALUE (parameter_packs);
4289 tree name = NULL_TREE;
4291 if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
4292 || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
4293 name = TYPE_NAME (pack);
4294 else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
4295 name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
4296 else if (TREE_CODE (pack) == CALL_EXPR)
4297 name = DECL_NAME (CALL_EXPR_FN (pack));
4298 else
4299 name = DECL_NAME (pack);
4301 if (name)
4302 inform (loc, " %qD", name);
4303 else
4304 inform (loc, " %s", "<anonymous>");
4306 parameter_packs = TREE_CHAIN (parameter_packs);
4309 return true;
4312 return false;
4315 /* Expand any parameter packs that occur in the template arguments in
4316 ARGS. */
4317 tree
4318 expand_template_argument_pack (tree args)
4320 if (args == error_mark_node)
4321 return error_mark_node;
4323 tree result_args = NULL_TREE;
4324 int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
4325 int num_result_args = -1;
4326 int non_default_args_count = -1;
4328 /* First, determine if we need to expand anything, and the number of
4329 slots we'll need. */
4330 for (in_arg = 0; in_arg < nargs; ++in_arg)
4332 tree arg = TREE_VEC_ELT (args, in_arg);
4333 if (arg == NULL_TREE)
4334 return args;
4335 if (ARGUMENT_PACK_P (arg))
4337 int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
4338 if (num_result_args < 0)
4339 num_result_args = in_arg + num_packed;
4340 else
4341 num_result_args += num_packed;
4343 else
4345 if (num_result_args >= 0)
4346 num_result_args++;
4350 /* If no expansion is necessary, we're done. */
4351 if (num_result_args < 0)
4352 return args;
4354 /* Expand arguments. */
4355 result_args = make_tree_vec (num_result_args);
4356 if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
4357 non_default_args_count =
4358 GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
4359 for (in_arg = 0; in_arg < nargs; ++in_arg)
4361 tree arg = TREE_VEC_ELT (args, in_arg);
4362 if (ARGUMENT_PACK_P (arg))
4364 tree packed = ARGUMENT_PACK_ARGS (arg);
4365 int i, num_packed = TREE_VEC_LENGTH (packed);
4366 for (i = 0; i < num_packed; ++i, ++out_arg)
4367 TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
4368 if (non_default_args_count > 0)
4369 non_default_args_count += num_packed - 1;
4371 else
4373 TREE_VEC_ELT (result_args, out_arg) = arg;
4374 ++out_arg;
4377 if (non_default_args_count >= 0)
4378 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
4379 return result_args;
4382 /* Checks if DECL shadows a template parameter.
4384 [temp.local]: A template-parameter shall not be redeclared within its
4385 scope (including nested scopes).
4387 Emits an error and returns TRUE if the DECL shadows a parameter,
4388 returns FALSE otherwise. */
4390 bool
4391 check_template_shadow (tree decl)
4393 tree olddecl;
4395 /* If we're not in a template, we can't possibly shadow a template
4396 parameter. */
4397 if (!current_template_parms)
4398 return true;
4400 /* Figure out what we're shadowing. */
4401 decl = OVL_FIRST (decl);
4402 olddecl = innermost_non_namespace_value (DECL_NAME (decl));
4404 /* If there's no previous binding for this name, we're not shadowing
4405 anything, let alone a template parameter. */
4406 if (!olddecl)
4407 return true;
4409 /* If we're not shadowing a template parameter, we're done. Note
4410 that OLDDECL might be an OVERLOAD (or perhaps even an
4411 ERROR_MARK), so we can't just blithely assume it to be a _DECL
4412 node. */
4413 if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
4414 return true;
4416 /* We check for decl != olddecl to avoid bogus errors for using a
4417 name inside a class. We check TPFI to avoid duplicate errors for
4418 inline member templates. */
4419 if (decl == olddecl
4420 || (DECL_TEMPLATE_PARM_P (decl)
4421 && TEMPLATE_PARMS_FOR_INLINE (current_template_parms)))
4422 return true;
4424 /* Don't complain about the injected class name, as we've already
4425 complained about the class itself. */
4426 if (DECL_SELF_REFERENCE_P (decl))
4427 return false;
4429 if (DECL_TEMPLATE_PARM_P (decl))
4430 error ("declaration of template parameter %q+D shadows "
4431 "template parameter", decl);
4432 else
4433 error ("declaration of %q+#D shadows template parameter", decl);
4434 inform (DECL_SOURCE_LOCATION (olddecl),
4435 "template parameter %qD declared here", olddecl);
4436 return false;
4439 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
4440 ORIG_LEVEL, DECL, and TYPE. */
4442 static tree
4443 build_template_parm_index (int index,
4444 int level,
4445 int orig_level,
4446 tree decl,
4447 tree type)
4449 tree t = make_node (TEMPLATE_PARM_INDEX);
4450 TEMPLATE_PARM_IDX (t) = index;
4451 TEMPLATE_PARM_LEVEL (t) = level;
4452 TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
4453 TEMPLATE_PARM_DECL (t) = decl;
4454 TREE_TYPE (t) = type;
4455 TREE_CONSTANT (t) = TREE_CONSTANT (decl);
4456 TREE_READONLY (t) = TREE_READONLY (decl);
4458 return t;
4461 struct ctp_hasher : ggc_ptr_hash<tree_node>
4463 static hashval_t hash (tree t)
4465 ++comparing_specializations;
4466 tree_code code = TREE_CODE (t);
4467 hashval_t val = iterative_hash_object (code, 0);
4468 val = iterative_hash_object (TEMPLATE_TYPE_LEVEL (t), val);
4469 val = iterative_hash_object (TEMPLATE_TYPE_IDX (t), val);
4470 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
4471 val = iterative_hash_template_arg (TYPE_TI_ARGS (t), val);
4472 --comparing_specializations;
4473 return val;
4476 static bool equal (tree t, tree u)
4478 ++comparing_specializations;
4479 bool eq = comptypes (t, u, COMPARE_STRUCTURAL);
4480 --comparing_specializations;
4481 return eq;
4485 static GTY (()) hash_table<ctp_hasher> *ctp_table;
4487 /* Find the canonical type parameter for the given template type
4488 parameter. Returns the canonical type parameter, which may be TYPE
4489 if no such parameter existed. */
4491 tree
4492 canonical_type_parameter (tree type)
4494 if (ctp_table == NULL)
4495 ctp_table = hash_table<ctp_hasher>::create_ggc (61);
4497 tree& slot = *ctp_table->find_slot (type, INSERT);
4498 if (slot == NULL_TREE)
4499 slot = type;
4500 return slot;
4503 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
4504 TEMPLATE_PARM_LEVEL has been decreased by LEVELS. If such a
4505 TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
4506 new one is created. */
4508 static tree
4509 reduce_template_parm_level (tree index, tree type, int levels, tree args,
4510 tsubst_flags_t complain)
4512 if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
4513 || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
4514 != TEMPLATE_PARM_LEVEL (index) - levels)
4515 || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
4517 tree orig_decl = TEMPLATE_PARM_DECL (index);
4519 tree decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
4520 TREE_CODE (orig_decl), DECL_NAME (orig_decl),
4521 type);
4522 TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
4523 TREE_READONLY (decl) = TREE_READONLY (orig_decl);
4524 DECL_VIRTUAL_P (decl) = DECL_VIRTUAL_P (orig_decl);
4525 DECL_ARTIFICIAL (decl) = 1;
4526 SET_DECL_TEMPLATE_PARM_P (decl);
4528 tree tpi = build_template_parm_index (TEMPLATE_PARM_IDX (index),
4529 TEMPLATE_PARM_LEVEL (index) - levels,
4530 TEMPLATE_PARM_ORIG_LEVEL (index),
4531 decl, type);
4532 TEMPLATE_PARM_DESCENDANTS (index) = tpi;
4533 TEMPLATE_PARM_PARAMETER_PACK (tpi)
4534 = TEMPLATE_PARM_PARAMETER_PACK (index);
4536 /* Template template parameters need this. */
4537 tree inner = decl;
4538 if (TREE_CODE (decl) == TEMPLATE_DECL)
4540 inner = build_lang_decl_loc (DECL_SOURCE_LOCATION (decl),
4541 TYPE_DECL, DECL_NAME (decl), type);
4542 DECL_TEMPLATE_RESULT (decl) = inner;
4543 DECL_ARTIFICIAL (inner) = true;
4544 tree parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (orig_decl),
4545 args, complain);
4546 DECL_TEMPLATE_PARMS (decl) = parms;
4547 tree orig_inner = DECL_TEMPLATE_RESULT (orig_decl);
4548 DECL_TEMPLATE_INFO (inner)
4549 = build_template_info (DECL_TI_TEMPLATE (orig_inner),
4550 template_parms_to_args (parms));
4553 /* Attach the TPI to the decl. */
4554 if (TREE_CODE (inner) == TYPE_DECL)
4555 TEMPLATE_TYPE_PARM_INDEX (type) = tpi;
4556 else
4557 DECL_INITIAL (decl) = tpi;
4560 return TEMPLATE_PARM_DESCENDANTS (index);
4563 /* Process information from new template parameter PARM and append it
4564 to the LIST being built. This new parameter is a non-type
4565 parameter iff IS_NON_TYPE is true. This new parameter is a
4566 parameter pack iff IS_PARAMETER_PACK is true. The location of PARM
4567 is in PARM_LOC. */
4569 tree
4570 process_template_parm (tree list, location_t parm_loc, tree parm,
4571 bool is_non_type, bool is_parameter_pack)
4573 gcc_assert (TREE_CODE (parm) == TREE_LIST);
4574 tree prev = NULL_TREE;
4575 int idx = 0;
4577 if (list)
4579 prev = tree_last (list);
4581 tree p = TREE_VALUE (prev);
4582 if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
4583 idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
4584 else if (TREE_CODE (p) == PARM_DECL)
4585 idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
4587 ++idx;
4590 tree decl = NULL_TREE;
4591 tree defval = TREE_PURPOSE (parm);
4592 tree constr = TREE_TYPE (parm);
4594 if (is_non_type)
4596 parm = TREE_VALUE (parm);
4598 SET_DECL_TEMPLATE_PARM_P (parm);
4600 if (TREE_TYPE (parm) != error_mark_node)
4602 /* [temp.param]
4604 The top-level cv-qualifiers on the template-parameter are
4605 ignored when determining its type. */
4606 TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
4607 if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
4608 TREE_TYPE (parm) = error_mark_node;
4609 else if (uses_parameter_packs (TREE_TYPE (parm))
4610 && !is_parameter_pack
4611 /* If we're in a nested template parameter list, the template
4612 template parameter could be a parameter pack. */
4613 && processing_template_parmlist == 1)
4615 /* This template parameter is not a parameter pack, but it
4616 should be. Complain about "bare" parameter packs. */
4617 check_for_bare_parameter_packs (TREE_TYPE (parm));
4619 /* Recover by calling this a parameter pack. */
4620 is_parameter_pack = true;
4624 /* A template parameter is not modifiable. */
4625 TREE_CONSTANT (parm) = 1;
4626 TREE_READONLY (parm) = 1;
4627 decl = build_decl (parm_loc,
4628 CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
4629 TREE_CONSTANT (decl) = 1;
4630 TREE_READONLY (decl) = 1;
4631 DECL_INITIAL (parm) = DECL_INITIAL (decl)
4632 = build_template_parm_index (idx, current_template_depth,
4633 current_template_depth,
4634 decl, TREE_TYPE (parm));
4636 TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))
4637 = is_parameter_pack;
4639 else
4641 tree t;
4642 parm = TREE_VALUE (TREE_VALUE (parm));
4644 if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
4646 t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
4647 /* This is for distinguishing between real templates and template
4648 template parameters */
4649 TREE_TYPE (parm) = t;
4651 /* any_template_parm_r expects to be able to get the targs of a
4652 DECL_TEMPLATE_RESULT. */
4653 tree result = DECL_TEMPLATE_RESULT (parm);
4654 TREE_TYPE (result) = t;
4655 tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (parm));
4656 tree tinfo = build_template_info (parm, args);
4657 retrofit_lang_decl (result);
4658 DECL_TEMPLATE_INFO (result) = tinfo;
4660 decl = parm;
4662 else
4664 t = cxx_make_type (TEMPLATE_TYPE_PARM);
4665 /* parm is either IDENTIFIER_NODE or NULL_TREE. */
4666 decl = build_decl (parm_loc,
4667 TYPE_DECL, parm, t);
4670 TYPE_NAME (t) = decl;
4671 TYPE_STUB_DECL (t) = decl;
4672 parm = decl;
4673 TEMPLATE_TYPE_PARM_INDEX (t)
4674 = build_template_parm_index (idx, current_template_depth,
4675 current_template_depth,
4676 decl, TREE_TYPE (parm));
4677 TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
4678 TYPE_CANONICAL (t) = canonical_type_parameter (t);
4680 DECL_ARTIFICIAL (decl) = 1;
4681 SET_DECL_TEMPLATE_PARM_P (decl);
4683 if (TREE_CODE (parm) == TEMPLATE_DECL
4684 && !uses_outer_template_parms (parm))
4685 TEMPLATE_TEMPLATE_PARM_SIMPLE_P (TREE_TYPE (parm)) = true;
4687 /* Build requirements for the type/template parameter.
4688 This must be done after SET_DECL_TEMPLATE_PARM_P or
4689 process_template_parm could fail. */
4690 tree reqs = finish_shorthand_constraint (parm, constr);
4692 decl = pushdecl (decl);
4693 if (!is_non_type)
4694 parm = decl;
4696 /* Build the parameter node linking the parameter declaration,
4697 its default argument (if any), and its constraints (if any). */
4698 parm = build_tree_list (defval, parm);
4699 TEMPLATE_PARM_CONSTRAINTS (parm) = reqs;
4701 if (prev)
4702 TREE_CHAIN (prev) = parm;
4703 else
4704 list = parm;
4706 return list;
4709 /* The end of a template parameter list has been reached. Process the
4710 tree list into a parameter vector, converting each parameter into a more
4711 useful form. Type parameters are saved as IDENTIFIER_NODEs, and others
4712 as PARM_DECLs. */
4714 tree
4715 end_template_parm_list (tree parms)
4717 tree saved_parmlist = make_tree_vec (list_length (parms));
4719 /* Pop the dummy parameter level and add the real one. We do not
4720 morph the dummy parameter in place, as it might have been
4721 captured by a (nested) template-template-parm. */
4722 current_template_parms = TREE_CHAIN (current_template_parms);
4724 current_template_parms
4725 = tree_cons (size_int (current_template_depth + 1),
4726 saved_parmlist, current_template_parms);
4728 for (unsigned ix = 0; parms; ix++)
4730 tree parm = parms;
4731 parms = TREE_CHAIN (parms);
4732 TREE_CHAIN (parm) = NULL_TREE;
4734 TREE_VEC_ELT (saved_parmlist, ix) = parm;
4737 --processing_template_parmlist;
4739 return saved_parmlist;
4742 // Explicitly indicate the end of the template parameter list. We assume
4743 // that the current template parameters have been constructed and/or
4744 // managed explicitly, as when creating new template template parameters
4745 // from a shorthand constraint.
4746 void
4747 end_template_parm_list ()
4749 --processing_template_parmlist;
4752 /* end_template_decl is called after a template declaration is seen. */
4754 void
4755 end_template_decl (void)
4757 reset_specialization ();
4759 if (! processing_template_decl)
4760 return;
4762 /* This matches the pushlevel in begin_template_parm_list. */
4763 finish_scope ();
4765 --processing_template_decl;
4766 current_template_parms = TREE_CHAIN (current_template_parms);
4769 /* Takes a TEMPLATE_PARM_P or DECL_TEMPLATE_PARM_P node or a TREE_LIST
4770 thereof, and converts it into an argument suitable to be passed to
4771 the type substitution functions. Note that if the TREE_LIST contains
4772 an error_mark node, the returned argument is error_mark_node. */
4774 tree
4775 template_parm_to_arg (tree t)
4777 if (!t)
4778 return NULL_TREE;
4780 if (TREE_CODE (t) == TREE_LIST)
4781 t = TREE_VALUE (t);
4783 if (error_operand_p (t))
4784 return error_mark_node;
4786 if (DECL_P (t) && DECL_TEMPLATE_PARM_P (t))
4788 if (TREE_CODE (t) == TYPE_DECL
4789 || TREE_CODE (t) == TEMPLATE_DECL)
4790 t = TREE_TYPE (t);
4791 else
4792 t = DECL_INITIAL (t);
4795 gcc_assert (TEMPLATE_PARM_P (t));
4797 if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
4798 || TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
4800 if (TEMPLATE_TYPE_PARAMETER_PACK (t))
4802 /* Turn this argument into a TYPE_ARGUMENT_PACK
4803 with a single element, which expands T. */
4804 tree vec = make_tree_vec (1);
4805 if (CHECKING_P)
4806 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4808 TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4810 t = cxx_make_type (TYPE_ARGUMENT_PACK);
4811 ARGUMENT_PACK_ARGS (t) = vec;
4814 else
4816 if (TEMPLATE_PARM_PARAMETER_PACK (t))
4818 /* Turn this argument into a NONTYPE_ARGUMENT_PACK
4819 with a single element, which expands T. */
4820 tree vec = make_tree_vec (1);
4821 if (CHECKING_P)
4822 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4824 t = convert_from_reference (t);
4825 TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4827 t = make_node (NONTYPE_ARGUMENT_PACK);
4828 ARGUMENT_PACK_ARGS (t) = vec;
4830 else
4831 t = convert_from_reference (t);
4833 return t;
4836 /* If T looks like a generic template argument produced by template_parm_to_arg,
4837 return the corresponding template parameter, otherwise return NULL_TREE. */
4839 static tree
4840 template_arg_to_parm (tree t)
4842 if (t == NULL_TREE)
4843 return NULL_TREE;
4845 if (ARGUMENT_PACK_P (t))
4847 tree args = ARGUMENT_PACK_ARGS (t);
4848 if (TREE_VEC_LENGTH (args) == 1
4849 && PACK_EXPANSION_P (TREE_VEC_ELT (args, 0)))
4850 t = PACK_EXPANSION_PATTERN (TREE_VEC_ELT (args, 0));
4853 if (REFERENCE_REF_P (t))
4854 t = TREE_OPERAND (t, 0);
4856 if (TEMPLATE_PARM_P (t))
4857 return t;
4858 else
4859 return NULL_TREE;
4862 /* Given a single level of template parameters (a TREE_VEC), return it
4863 as a set of template arguments. */
4865 tree
4866 template_parms_level_to_args (tree parms)
4868 parms = copy_node (parms);
4869 TREE_TYPE (parms) = NULL_TREE;
4870 for (tree& parm : tree_vec_range (parms))
4871 parm = template_parm_to_arg (parm);
4873 if (CHECKING_P)
4874 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (parms, TREE_VEC_LENGTH (parms));
4876 return parms;
4879 /* Given a set of template parameters, return them as a set of template
4880 arguments. The template parameters are represented as a TREE_VEC, in
4881 the form documented in cp-tree.h for template arguments. */
4883 tree
4884 template_parms_to_args (tree parms)
4886 tree header;
4887 tree args = NULL_TREE;
4888 int length = TMPL_PARMS_DEPTH (parms);
4889 int l = length;
4891 /* If there is only one level of template parameters, we do not
4892 create a TREE_VEC of TREE_VECs. Instead, we return a single
4893 TREE_VEC containing the arguments. */
4894 if (length > 1)
4895 args = make_tree_vec (length);
4897 for (header = parms; header; header = TREE_CHAIN (header))
4899 tree a = template_parms_level_to_args (TREE_VALUE (header));
4901 if (length > 1)
4902 TREE_VEC_ELT (args, --l) = a;
4903 else
4904 args = a;
4907 return args;
4910 /* Within the declaration of a template, return the currently active
4911 template parameters as an argument TREE_VEC. */
4913 static tree
4914 current_template_args (void)
4916 return template_parms_to_args (current_template_parms);
4919 /* Return the fully generic arguments for of TMPL, i.e. what
4920 current_template_args would be while parsing it. */
4922 tree
4923 generic_targs_for (tree tmpl)
4925 if (tmpl == NULL_TREE)
4926 return NULL_TREE;
4927 if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
4928 || DECL_TEMPLATE_SPECIALIZATION (tmpl))
4929 /* DECL_TEMPLATE_RESULT doesn't have the arguments we want. For a template
4930 template parameter, it has no TEMPLATE_INFO; for a partial
4931 specialization, it has the arguments for the primary template, and we
4932 want the arguments for the partial specialization. */;
4933 else if (tree result = DECL_TEMPLATE_RESULT (tmpl))
4934 if (tree ti = get_template_info (result))
4935 return TI_ARGS (ti);
4936 return template_parms_to_args (DECL_TEMPLATE_PARMS (tmpl));
4939 /* Return the template arguments corresponding to the template parameters of
4940 DECL's enclosing scope. When DECL is a member of a partial specialization,
4941 this returns the arguments for the partial specialization as opposed to those
4942 for the primary template, which is the main difference between this function
4943 and simply using e.g. the TYPE_TI_ARGS of DECL's DECL_CONTEXT. */
4945 tree
4946 outer_template_args (const_tree decl)
4948 if (TREE_CODE (decl) == TEMPLATE_DECL)
4949 decl = DECL_TEMPLATE_RESULT (decl);
4950 tree ti = get_template_info (decl);
4951 if (!ti)
4952 return NULL_TREE;
4953 tree args = TI_ARGS (ti);
4954 if (!PRIMARY_TEMPLATE_P (TI_TEMPLATE (ti)))
4955 return args;
4956 if (TMPL_ARGS_DEPTH (args) == 1)
4957 return NULL_TREE;
4958 return strip_innermost_template_args (args, 1);
4961 /* Update the declared TYPE by doing any lookups which were thought to be
4962 dependent, but are not now that we know the SCOPE of the declarator. */
4964 tree
4965 maybe_update_decl_type (tree orig_type, tree scope)
4967 tree type = orig_type;
4969 if (type == NULL_TREE)
4970 return type;
4972 if (TREE_CODE (orig_type) == TYPE_DECL)
4973 type = TREE_TYPE (type);
4975 if (scope && TYPE_P (scope) && dependent_type_p (scope)
4976 && dependent_type_p (type)
4977 /* Don't bother building up the args in this case. */
4978 && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
4980 /* tsubst in the args corresponding to the template parameters,
4981 including auto if present. Most things will be unchanged, but
4982 make_typename_type and tsubst_qualified_id will resolve
4983 TYPENAME_TYPEs and SCOPE_REFs that were previously dependent. */
4984 tree args = current_template_args ();
4985 tree auto_node = type_uses_auto (type);
4986 tree pushed;
4987 if (auto_node)
4989 tree auto_vec = make_tree_vec (1);
4990 TREE_VEC_ELT (auto_vec, 0) = auto_node;
4991 args = add_to_template_args (args, auto_vec);
4993 pushed = push_scope (scope);
4994 type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
4995 if (pushed)
4996 pop_scope (scope);
4999 if (type == error_mark_node)
5000 return orig_type;
5002 if (TREE_CODE (orig_type) == TYPE_DECL)
5004 if (same_type_p (type, TREE_TYPE (orig_type)))
5005 type = orig_type;
5006 else
5007 type = TYPE_NAME (type);
5009 return type;
5012 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
5013 template PARMS and constraints, CONSTR. If MEMBER_TEMPLATE_P is true,
5014 the new template is a member template. */
5016 static tree
5017 build_template_decl (tree decl, tree parms, bool member_template_p)
5019 gcc_checking_assert (TREE_CODE (decl) != TEMPLATE_DECL);
5021 tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
5022 SET_DECL_LANGUAGE (tmpl, DECL_LANGUAGE (decl));
5023 DECL_TEMPLATE_PARMS (tmpl) = parms;
5024 DECL_TEMPLATE_RESULT (tmpl) = decl;
5025 DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
5026 TREE_TYPE (tmpl) = TREE_TYPE (decl);
5027 DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
5028 DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
5030 /* Propagate module information from the decl. */
5031 DECL_MODULE_EXPORT_P (tmpl) = DECL_MODULE_EXPORT_P (decl);
5033 return tmpl;
5036 struct template_parm_data
5038 /* The level of the template parameters we are currently
5039 processing. */
5040 int level;
5042 /* The index of the specialization argument we are currently
5043 processing. */
5044 int current_arg;
5046 /* An array whose size is the number of template parameters. The
5047 elements are nonzero if the parameter has been used in any one
5048 of the arguments processed so far. */
5049 int* parms;
5051 /* An array whose size is the number of template arguments. The
5052 elements are nonzero if the argument makes use of template
5053 parameters of this level. */
5054 int* arg_uses_template_parms;
5057 /* Subroutine of push_template_decl used to see if each template
5058 parameter in a partial specialization is used in the explicit
5059 argument list. If T is of the LEVEL given in DATA (which is
5060 treated as a template_parm_data*), then DATA->PARMS is marked
5061 appropriately. */
5063 static int
5064 mark_template_parm (tree t, void* data)
5066 int level;
5067 int idx;
5068 struct template_parm_data* tpd = (struct template_parm_data*) data;
5070 template_parm_level_and_index (t, &level, &idx);
5072 if (level == tpd->level)
5074 tpd->parms[idx] = 1;
5075 tpd->arg_uses_template_parms[tpd->current_arg] = 1;
5078 /* In C++17 the type of a non-type argument is a deduced context. */
5079 if (cxx_dialect >= cxx17
5080 && TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5081 for_each_template_parm (TREE_TYPE (t),
5082 &mark_template_parm,
5083 data,
5084 NULL,
5085 /*include_nondeduced_p=*/false);
5087 /* Return zero so that for_each_template_parm will continue the
5088 traversal of the tree; we want to mark *every* template parm. */
5089 return 0;
5092 /* Process the partial specialization DECL. */
5094 static tree
5095 process_partial_specialization (tree decl)
5097 tree type = TREE_TYPE (decl);
5098 tree tinfo = get_template_info (decl);
5099 tree maintmpl = TI_TEMPLATE (tinfo);
5100 tree specargs = TI_ARGS (tinfo);
5101 tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
5102 tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
5103 tree inner_parms;
5104 tree inst;
5105 int nargs = TREE_VEC_LENGTH (inner_args);
5106 int ntparms;
5107 int i;
5108 bool did_error_intro = false;
5109 struct template_parm_data tpd;
5110 struct template_parm_data tpd2;
5112 gcc_assert (current_template_parms);
5114 /* A concept cannot be specialized. */
5115 if (flag_concepts && variable_concept_p (maintmpl))
5117 error ("specialization of variable concept %q#D", maintmpl);
5118 return error_mark_node;
5121 inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
5122 ntparms = TREE_VEC_LENGTH (inner_parms);
5124 /* We check that each of the template parameters given in the
5125 partial specialization is used in the argument list to the
5126 specialization. For example:
5128 template <class T> struct S;
5129 template <class T> struct S<T*>;
5131 The second declaration is OK because `T*' uses the template
5132 parameter T, whereas
5134 template <class T> struct S<int>;
5136 is no good. Even trickier is:
5138 template <class T>
5139 struct S1
5141 template <class U>
5142 struct S2;
5143 template <class U>
5144 struct S2<T>;
5147 The S2<T> declaration is actually invalid; it is a
5148 full-specialization. Of course,
5150 template <class U>
5151 struct S2<T (*)(U)>;
5153 or some such would have been OK. */
5154 tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
5155 tpd.parms = XALLOCAVEC (int, ntparms);
5156 memset (tpd.parms, 0, sizeof (int) * ntparms);
5158 tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
5159 memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
5160 for (i = 0; i < nargs; ++i)
5162 tpd.current_arg = i;
5163 for_each_template_parm (TREE_VEC_ELT (inner_args, i),
5164 &mark_template_parm,
5165 &tpd,
5166 NULL,
5167 /*include_nondeduced_p=*/false);
5169 for (i = 0; i < ntparms; ++i)
5170 if (tpd.parms[i] == 0)
5172 /* One of the template parms was not used in a deduced context in the
5173 specialization. */
5174 if (!did_error_intro)
5176 error ("template parameters not deducible in "
5177 "partial specialization:");
5178 did_error_intro = true;
5181 inform (input_location, " %qD",
5182 TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
5185 if (did_error_intro)
5186 return error_mark_node;
5188 /* [temp.class.spec]
5190 The argument list of the specialization shall not be identical to
5191 the implicit argument list of the primary template. */
5192 tree main_args
5193 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (maintmpl)));
5194 if (comp_template_args (inner_args, INNERMOST_TEMPLATE_ARGS (main_args))
5195 && (!flag_concepts
5196 || !strictly_subsumes (current_template_constraints (), maintmpl)))
5198 if (!flag_concepts)
5199 error ("partial specialization %q+D does not specialize "
5200 "any template arguments; to define the primary template, "
5201 "remove the template argument list", decl);
5202 else
5203 error ("partial specialization %q+D does not specialize any "
5204 "template arguments and is not more constrained than "
5205 "the primary template; to define the primary template, "
5206 "remove the template argument list", decl);
5207 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5210 /* A partial specialization that replaces multiple parameters of the
5211 primary template with a pack expansion is less specialized for those
5212 parameters. */
5213 if (nargs < DECL_NTPARMS (maintmpl))
5215 error ("partial specialization is not more specialized than the "
5216 "primary template because it replaces multiple parameters "
5217 "with a pack expansion");
5218 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5219 /* Avoid crash in process_partial_specialization. */
5220 return decl;
5223 else if (nargs > DECL_NTPARMS (maintmpl))
5225 error ("too many arguments for partial specialization %qT", type);
5226 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5227 /* Avoid crash below. */
5228 return decl;
5231 /* If we aren't in a dependent class, we can actually try deduction. */
5232 else if (tpd.level == 1
5233 /* FIXME we should be able to handle a partial specialization of a
5234 partial instantiation, but currently we can't (c++/41727). */
5235 && TMPL_ARGS_DEPTH (specargs) == 1
5236 && !get_partial_spec_bindings (maintmpl, maintmpl, specargs))
5238 auto_diagnostic_group d;
5239 if (pedwarn (input_location, 0,
5240 "partial specialization %qD is not more specialized than",
5241 decl))
5242 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template %qD",
5243 maintmpl);
5246 /* [temp.spec.partial]
5248 The type of a template parameter corresponding to a specialized
5249 non-type argument shall not be dependent on a parameter of the
5250 specialization.
5252 Also, we verify that pack expansions only occur at the
5253 end of the argument list. */
5254 tpd2.parms = 0;
5255 for (i = 0; i < nargs; ++i)
5257 tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
5258 tree arg = TREE_VEC_ELT (inner_args, i);
5259 tree packed_args = NULL_TREE;
5260 int j, len = 1;
5262 if (ARGUMENT_PACK_P (arg))
5264 /* Extract the arguments from the argument pack. We'll be
5265 iterating over these in the following loop. */
5266 packed_args = ARGUMENT_PACK_ARGS (arg);
5267 len = TREE_VEC_LENGTH (packed_args);
5270 for (j = 0; j < len; j++)
5272 if (packed_args)
5273 /* Get the Jth argument in the parameter pack. */
5274 arg = TREE_VEC_ELT (packed_args, j);
5276 if (PACK_EXPANSION_P (arg))
5278 /* Pack expansions must come at the end of the
5279 argument list. */
5280 if ((packed_args && j < len - 1)
5281 || (!packed_args && i < nargs - 1))
5283 if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5284 error ("parameter pack argument %qE must be at the "
5285 "end of the template argument list", arg);
5286 else
5287 error ("parameter pack argument %qT must be at the "
5288 "end of the template argument list", arg);
5292 if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5293 /* We only care about the pattern. */
5294 arg = PACK_EXPANSION_PATTERN (arg);
5296 if (/* These first two lines are the `non-type' bit. */
5297 !TYPE_P (arg)
5298 && TREE_CODE (arg) != TEMPLATE_DECL
5299 /* This next two lines are the `argument expression is not just a
5300 simple identifier' condition and also the `specialized
5301 non-type argument' bit. */
5302 && TREE_CODE (arg) != TEMPLATE_PARM_INDEX
5303 && !((REFERENCE_REF_P (arg)
5304 || TREE_CODE (arg) == VIEW_CONVERT_EXPR)
5305 && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_PARM_INDEX))
5307 /* Look at the corresponding template parameter,
5308 marking which template parameters its type depends
5309 upon. */
5310 tree type = TREE_TYPE (parm);
5312 if (!tpd2.parms)
5314 /* We haven't yet initialized TPD2. Do so now. */
5315 tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
5316 /* The number of parameters here is the number in the
5317 main template, which, as checked in the assertion
5318 above, is NARGS. */
5319 tpd2.parms = XALLOCAVEC (int, nargs);
5320 tpd2.level =
5321 TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
5324 /* Mark the template parameters. But this time, we're
5325 looking for the template parameters of the main
5326 template, not in the specialization. */
5327 tpd2.current_arg = i;
5328 tpd2.arg_uses_template_parms[i] = 0;
5329 memset (tpd2.parms, 0, sizeof (int) * nargs);
5330 for_each_template_parm (type,
5331 &mark_template_parm,
5332 &tpd2,
5333 NULL,
5334 /*include_nondeduced_p=*/false);
5336 if (tpd2.arg_uses_template_parms [i])
5338 /* The type depended on some template parameters.
5339 If they are fully specialized in the
5340 specialization, that's OK. */
5341 int j;
5342 int count = 0;
5343 for (j = 0; j < nargs; ++j)
5344 if (tpd2.parms[j] != 0
5345 && tpd.arg_uses_template_parms [j])
5346 ++count;
5347 if (count != 0)
5348 error_n (input_location, count,
5349 "type %qT of template argument %qE depends "
5350 "on a template parameter",
5351 "type %qT of template argument %qE depends "
5352 "on template parameters",
5353 type,
5354 arg);
5360 /* We should only get here once. */
5361 if (TREE_CODE (decl) == TYPE_DECL)
5362 gcc_assert (!COMPLETE_TYPE_P (type));
5364 // Build the template decl.
5365 tree tmpl = build_template_decl (decl, current_template_parms,
5366 DECL_MEMBER_TEMPLATE_P (maintmpl));
5367 SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5368 DECL_TEMPLATE_INFO (tmpl) = build_template_info (maintmpl, specargs);
5369 DECL_PRIMARY_TEMPLATE (tmpl) = maintmpl;
5371 /* Give template template parms a DECL_CONTEXT of the template
5372 for which they are a parameter. */
5373 for (i = 0; i < ntparms; ++i)
5375 tree parm = TREE_VALUE (TREE_VEC_ELT (inner_parms, i));
5376 if (TREE_CODE (parm) == TEMPLATE_DECL)
5377 DECL_CONTEXT (parm) = tmpl;
5380 if (VAR_P (decl))
5381 /* We didn't register this in check_explicit_specialization so we could
5382 wait until the constraints were set. */
5383 decl = register_specialization (decl, maintmpl, specargs, false, 0);
5384 else
5385 associate_classtype_constraints (type);
5387 DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
5388 = tree_cons (specargs, tmpl,
5389 DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
5390 TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
5391 /* Link the DECL_TEMPLATE_RESULT back to the partial TEMPLATE_DECL. */
5392 gcc_checking_assert (!TI_PARTIAL_INFO (tinfo));
5393 TI_PARTIAL_INFO (tinfo) = build_template_info (tmpl, NULL_TREE);
5395 for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
5396 inst = TREE_CHAIN (inst))
5398 tree instance = TREE_VALUE (inst);
5399 if (TYPE_P (instance)
5400 ? (COMPLETE_TYPE_P (instance)
5401 && CLASSTYPE_IMPLICIT_INSTANTIATION (instance))
5402 : DECL_TEMPLATE_INSTANTIATION (instance))
5404 tree partial_ti = most_specialized_partial_spec (instance, tf_none,
5405 /*rechecking=*/true);
5406 tree inst_decl = (DECL_P (instance)
5407 ? instance : TYPE_NAME (instance));
5408 if (!partial_ti)
5409 /* OK */;
5410 else if (partial_ti == error_mark_node)
5411 permerror (input_location,
5412 "declaration of %qD ambiguates earlier template "
5413 "instantiation for %qD", decl, inst_decl);
5414 else if (TI_TEMPLATE (partial_ti) == tmpl)
5415 permerror (input_location,
5416 "partial specialization of %qD after instantiation "
5417 "of %qD", decl, inst_decl);
5421 return decl;
5424 /* PARM is a template parameter of some form; return the corresponding
5425 TEMPLATE_PARM_INDEX. */
5427 static tree
5428 get_template_parm_index (tree parm)
5430 if (TREE_CODE (parm) == PARM_DECL
5431 || TREE_CODE (parm) == CONST_DECL)
5432 parm = DECL_INITIAL (parm);
5433 else if (TREE_CODE (parm) == TYPE_DECL
5434 || TREE_CODE (parm) == TEMPLATE_DECL)
5435 parm = TREE_TYPE (parm);
5436 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
5437 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM
5438 || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
5439 parm = TEMPLATE_TYPE_PARM_INDEX (parm);
5440 gcc_assert (TREE_CODE (parm) == TEMPLATE_PARM_INDEX);
5441 return parm;
5444 /* Subroutine of fixed_parameter_pack_p below. Look for any template
5445 parameter packs used by the template parameter PARM. */
5447 static void
5448 fixed_parameter_pack_p_1 (tree parm, struct find_parameter_pack_data *ppd)
5450 /* A type parm can't refer to another parm. */
5451 if (TREE_CODE (parm) == TYPE_DECL || parm == error_mark_node)
5452 return;
5453 else if (TREE_CODE (parm) == PARM_DECL)
5455 cp_walk_tree (&TREE_TYPE (parm), &find_parameter_packs_r,
5456 ppd, ppd->visited);
5457 return;
5460 gcc_assert (TREE_CODE (parm) == TEMPLATE_DECL);
5462 tree vec = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
5463 for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
5465 tree p = TREE_VALUE (TREE_VEC_ELT (vec, i));
5466 if (template_parameter_pack_p (p))
5467 /* Any packs in the type are expanded by this parameter. */;
5468 else
5469 fixed_parameter_pack_p_1 (p, ppd);
5473 /* PARM is a template parameter pack. Return any parameter packs used in
5474 its type or the type of any of its template parameters. If there are
5475 any such packs, it will be instantiated into a fixed template parameter
5476 list by partial instantiation rather than be fully deduced. */
5478 tree
5479 fixed_parameter_pack_p (tree parm)
5481 /* This can only be true in a member template. */
5482 if (TEMPLATE_PARM_ORIG_LEVEL (get_template_parm_index (parm)) < 2)
5483 return NULL_TREE;
5484 /* This can only be true for a parameter pack. */
5485 if (!template_parameter_pack_p (parm))
5486 return NULL_TREE;
5487 /* A type parm can't refer to another parm. */
5488 if (TREE_CODE (parm) == TYPE_DECL)
5489 return NULL_TREE;
5491 tree parameter_packs = NULL_TREE;
5492 struct find_parameter_pack_data ppd;
5493 ppd.parameter_packs = &parameter_packs;
5494 ppd.visited = new hash_set<tree>;
5495 ppd.type_pack_expansion_p = false;
5497 fixed_parameter_pack_p_1 (parm, &ppd);
5499 delete ppd.visited;
5500 return parameter_packs;
5503 /* Check that a template declaration's use of default arguments and
5504 parameter packs is not invalid. Here, PARMS are the template
5505 parameters. IS_PRIMARY is true if DECL is the thing declared by
5506 a primary template. IS_PARTIAL is true if DECL is a partial
5507 specialization.
5509 IS_FRIEND_DECL is nonzero if DECL is either a non-defining friend
5510 function template declaration or a friend class template
5511 declaration. In the function case, 1 indicates a declaration, 2
5512 indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
5513 emitted for extraneous default arguments.
5515 Returns TRUE if there were no errors found, FALSE otherwise. */
5517 bool
5518 check_default_tmpl_args (tree decl, tree parms, bool is_primary,
5519 bool is_partial, int is_friend_decl)
5521 const char *msg;
5522 int last_level_to_check;
5523 tree parm_level;
5524 bool no_errors = true;
5526 /* [temp.param]
5528 A default template-argument shall not be specified in a
5529 function template declaration or a function template definition, nor
5530 in the template-parameter-list of the definition of a member of a
5531 class template. */
5533 if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL
5534 || (TREE_CODE (decl) == FUNCTION_DECL && DECL_LOCAL_DECL_P (decl)))
5535 /* You can't have a function template declaration in a local
5536 scope, nor you can you define a member of a class template in a
5537 local scope. */
5538 return true;
5540 if ((TREE_CODE (decl) == TYPE_DECL
5541 && TREE_TYPE (decl)
5542 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5543 || (TREE_CODE (decl) == FUNCTION_DECL
5544 && LAMBDA_FUNCTION_P (decl)))
5545 /* A lambda doesn't have an explicit declaration; don't complain
5546 about the parms of the enclosing class. */
5547 return true;
5549 if (current_class_type
5550 && !TYPE_BEING_DEFINED (current_class_type)
5551 && DECL_LANG_SPECIFIC (decl)
5552 && DECL_DECLARES_FUNCTION_P (decl)
5553 /* If this is either a friend defined in the scope of the class
5554 or a member function. */
5555 && (DECL_FUNCTION_MEMBER_P (decl)
5556 ? same_type_p (DECL_CONTEXT (decl), current_class_type)
5557 : DECL_FRIEND_CONTEXT (decl)
5558 ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
5559 : false)
5560 /* And, if it was a member function, it really was defined in
5561 the scope of the class. */
5562 && (!DECL_FUNCTION_MEMBER_P (decl)
5563 || DECL_INITIALIZED_IN_CLASS_P (decl)))
5564 /* We already checked these parameters when the template was
5565 declared, so there's no need to do it again now. This function
5566 was defined in class scope, but we're processing its body now
5567 that the class is complete. */
5568 return true;
5570 /* Core issue 226 (C++0x only): the following only applies to class
5571 templates. */
5572 if (is_primary
5573 && ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL))
5575 /* [temp.param]
5577 If a template-parameter has a default template-argument, all
5578 subsequent template-parameters shall have a default
5579 template-argument supplied. */
5580 for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
5582 tree inner_parms = TREE_VALUE (parm_level);
5583 int ntparms = TREE_VEC_LENGTH (inner_parms);
5584 int seen_def_arg_p = 0;
5585 int i;
5587 for (i = 0; i < ntparms; ++i)
5589 tree parm = TREE_VEC_ELT (inner_parms, i);
5591 if (parm == error_mark_node)
5592 continue;
5594 if (TREE_PURPOSE (parm))
5595 seen_def_arg_p = 1;
5596 else if (seen_def_arg_p
5597 && !template_parameter_pack_p (TREE_VALUE (parm)))
5599 error ("no default argument for %qD", TREE_VALUE (parm));
5600 /* For better subsequent error-recovery, we indicate that
5601 there should have been a default argument. */
5602 TREE_PURPOSE (parm) = error_mark_node;
5603 no_errors = false;
5605 else if (!is_partial
5606 && !is_friend_decl
5607 /* Don't complain about an enclosing partial
5608 specialization. */
5609 && parm_level == parms
5610 && (TREE_CODE (decl) == TYPE_DECL || VAR_P (decl))
5611 && i < ntparms - 1
5612 && template_parameter_pack_p (TREE_VALUE (parm))
5613 /* A fixed parameter pack will be partially
5614 instantiated into a fixed length list. */
5615 && !fixed_parameter_pack_p (TREE_VALUE (parm)))
5617 /* A primary class template, primary variable template
5618 (DR 2032), or alias template can only have one
5619 parameter pack, at the end of the template
5620 parameter list. */
5622 error ("parameter pack %q+D must be at the end of the"
5623 " template parameter list", TREE_VALUE (parm));
5625 TREE_VALUE (TREE_VEC_ELT (inner_parms, i))
5626 = error_mark_node;
5627 no_errors = false;
5633 if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
5634 || is_partial
5635 || !is_primary
5636 || is_friend_decl)
5637 /* For an ordinary class template, default template arguments are
5638 allowed at the innermost level, e.g.:
5639 template <class T = int>
5640 struct S {};
5641 but, in a partial specialization, they're not allowed even
5642 there, as we have in [temp.class.spec]:
5644 The template parameter list of a specialization shall not
5645 contain default template argument values.
5647 So, for a partial specialization, or for a function template
5648 (in C++98/C++03), we look at all of them. */
5650 else
5651 /* But, for a primary class template that is not a partial
5652 specialization we look at all template parameters except the
5653 innermost ones. */
5654 parms = TREE_CHAIN (parms);
5656 /* Figure out what error message to issue. */
5657 if (is_friend_decl == 2)
5658 msg = G_("default template arguments may not be used in function template "
5659 "friend re-declaration");
5660 else if (is_friend_decl)
5661 msg = G_("default template arguments may not be used in template "
5662 "friend declarations");
5663 else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
5664 msg = G_("default template arguments may not be used in function templates "
5665 "without %<-std=c++11%> or %<-std=gnu++11%>");
5666 else if (is_partial)
5667 msg = G_("default template arguments may not be used in "
5668 "partial specializations");
5669 else if (current_class_type && CLASSTYPE_IS_TEMPLATE (current_class_type))
5670 msg = G_("default argument for template parameter for class enclosing %qD");
5671 else
5672 /* Per [temp.param]/9, "A default template-argument shall not be
5673 specified in the template-parameter-lists of the definition of
5674 a member of a class template that appears outside of the member's
5675 class.", thus if we aren't handling a member of a class template
5676 there is no need to examine the parameters. */
5677 return true;
5679 if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
5680 /* If we're inside a class definition, there's no need to
5681 examine the parameters to the class itself. On the one
5682 hand, they will be checked when the class is defined, and,
5683 on the other, default arguments are valid in things like:
5684 template <class T = double>
5685 struct S { template <class U> void f(U); };
5686 Here the default argument for `S' has no bearing on the
5687 declaration of `f'. */
5688 last_level_to_check = template_class_depth (current_class_type) + 1;
5689 else
5690 /* Check everything. */
5691 last_level_to_check = 0;
5693 for (parm_level = parms;
5694 parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
5695 parm_level = TREE_CHAIN (parm_level))
5697 tree inner_parms = TREE_VALUE (parm_level);
5698 int i;
5699 int ntparms;
5701 ntparms = TREE_VEC_LENGTH (inner_parms);
5702 for (i = 0; i < ntparms; ++i)
5704 if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
5705 continue;
5707 if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
5709 if (msg)
5711 no_errors = false;
5712 if (is_friend_decl == 2)
5713 return no_errors;
5715 error (msg, decl);
5716 msg = 0;
5719 /* Clear out the default argument so that we are not
5720 confused later. */
5721 TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
5725 /* At this point, if we're still interested in issuing messages,
5726 they must apply to classes surrounding the object declared. */
5727 if (msg)
5728 msg = G_("default argument for template parameter for class "
5729 "enclosing %qD");
5732 return no_errors;
5735 /* Worker for push_template_decl_real, called via
5736 for_each_template_parm. DATA is really an int, indicating the
5737 level of the parameters we are interested in. If T is a template
5738 parameter of that level, return nonzero. */
5740 static int
5741 template_parm_this_level_p (tree t, void* data)
5743 int this_level = *(int *)data;
5744 int level;
5746 if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5747 level = TEMPLATE_PARM_LEVEL (t);
5748 else
5749 level = TEMPLATE_TYPE_LEVEL (t);
5750 return level == this_level;
5753 /* Worker for uses_outer_template_parms, called via for_each_template_parm.
5754 DATA is really an int, indicating the innermost outer level of parameters.
5755 If T is a template parameter of that level or further out, return
5756 nonzero. */
5758 static int
5759 template_parm_outer_level (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 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
5772 parameters given by current_template_args, or reuses a
5773 previously existing one, if appropriate. Returns the DECL, or an
5774 equivalent one, if it is replaced via a call to duplicate_decls.
5776 If IS_FRIEND is true, DECL is a friend declaration. */
5778 tree
5779 push_template_decl (tree decl, bool is_friend)
5781 if (decl == error_mark_node || !current_template_parms)
5782 return error_mark_node;
5784 /* See if this is a partial specialization. */
5785 bool is_partial = ((DECL_IMPLICIT_TYPEDEF_P (decl)
5786 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
5787 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
5788 || (VAR_P (decl)
5789 && DECL_LANG_SPECIFIC (decl)
5790 && DECL_TEMPLATE_SPECIALIZATION (decl)
5791 && TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl))));
5793 /* No surprising friend functions. */
5794 gcc_checking_assert (is_friend
5795 || !(TREE_CODE (decl) == FUNCTION_DECL
5796 && DECL_UNIQUE_FRIEND_P (decl)));
5798 tree ctx;
5799 if (is_friend)
5800 /* For a friend, we want the context of the friend, not
5801 the type of which it is a friend. */
5802 ctx = CP_DECL_CONTEXT (decl);
5803 else if (CP_DECL_CONTEXT (decl)
5804 && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
5805 /* In the case of a virtual function, we want the class in which
5806 it is defined. */
5807 ctx = CP_DECL_CONTEXT (decl);
5808 else
5809 /* Otherwise, if we're currently defining some class, the DECL
5810 is assumed to be a member of the class. */
5811 ctx = current_scope ();
5813 if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
5814 ctx = NULL_TREE;
5816 if (!DECL_CONTEXT (decl))
5817 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5819 /* See if this is a primary template. */
5820 bool is_primary = false;
5821 if (is_friend && ctx
5822 && uses_template_parms_level (ctx, current_template_depth))
5823 /* A friend template that specifies a class context, i.e.
5824 template <typename T> friend void A<T>::f();
5825 is not primary. */
5827 else if (TREE_CODE (decl) == TYPE_DECL && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5828 /* Lambdas are not primary. */
5830 else
5831 is_primary = template_parm_scope_p ();
5833 /* True if the template is a member template, in the sense of
5834 [temp.mem]. */
5835 bool member_template_p = false;
5837 if (is_primary)
5839 warning (OPT_Wtemplates, "template %qD declared", decl);
5841 if (DECL_CLASS_SCOPE_P (decl))
5842 member_template_p = true;
5844 if (TREE_CODE (decl) == TYPE_DECL
5845 && IDENTIFIER_ANON_P (DECL_NAME (decl)))
5847 error ("template class without a name");
5848 return error_mark_node;
5850 else if (TREE_CODE (decl) == FUNCTION_DECL)
5852 if (member_template_p)
5854 if (DECL_OVERRIDE_P (decl) || DECL_FINAL_P (decl))
5855 error ("member template %qD may not have virt-specifiers", decl);
5857 if (DECL_DESTRUCTOR_P (decl))
5859 /* [temp.mem]
5861 A destructor shall not be a member template. */
5862 error_at (DECL_SOURCE_LOCATION (decl),
5863 "destructor %qD declared as member template", decl);
5864 return error_mark_node;
5866 if (IDENTIFIER_NEWDEL_OP_P (DECL_NAME (decl))
5867 && (!prototype_p (TREE_TYPE (decl))
5868 || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
5869 || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5870 || (TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5871 == void_list_node)))
5873 /* [basic.stc.dynamic.allocation]
5875 An allocation function can be a function
5876 template. ... Template allocation functions shall
5877 have two or more parameters. */
5878 error ("invalid template declaration of %qD", decl);
5879 return error_mark_node;
5882 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5883 && CLASS_TYPE_P (TREE_TYPE (decl)))
5884 /* Class template. */;
5885 else if (TREE_CODE (decl) == TYPE_DECL
5886 && TYPE_DECL_ALIAS_P (decl))
5887 /* alias-declaration */
5888 gcc_assert (!DECL_ARTIFICIAL (decl));
5889 else if (VAR_P (decl))
5890 /* C++14 variable template. */;
5891 else if (TREE_CODE (decl) == CONCEPT_DECL)
5892 /* C++20 concept definitions. */;
5893 else
5895 error ("template declaration of %q#D", decl);
5896 return error_mark_node;
5900 bool local_p = (!DECL_IMPLICIT_TYPEDEF_P (decl)
5901 && ((ctx && TREE_CODE (ctx) == FUNCTION_DECL)
5902 || (VAR_OR_FUNCTION_DECL_P (decl)
5903 && DECL_LOCAL_DECL_P (decl))));
5905 /* Check to see that the rules regarding the use of default
5906 arguments are not being violated. We check args for a friend
5907 functions when we know whether it's a definition, introducing
5908 declaration or re-declaration. */
5909 if (!local_p && (!is_friend || TREE_CODE (decl) != FUNCTION_DECL))
5910 check_default_tmpl_args (decl, current_template_parms,
5911 is_primary, is_partial, is_friend);
5913 /* Ensure that there are no parameter packs in the type of this
5914 declaration that have not been expanded. */
5915 if (TREE_CODE (decl) == FUNCTION_DECL)
5917 /* Check each of the arguments individually to see if there are
5918 any bare parameter packs. */
5919 tree type = TREE_TYPE (decl);
5920 tree arg = DECL_ARGUMENTS (decl);
5921 tree argtype = TYPE_ARG_TYPES (type);
5923 while (arg && argtype)
5925 if (!DECL_PACK_P (arg)
5926 && check_for_bare_parameter_packs (TREE_TYPE (arg)))
5928 /* This is a PARM_DECL that contains unexpanded parameter
5929 packs. We have already complained about this in the
5930 check_for_bare_parameter_packs call, so just replace
5931 these types with ERROR_MARK_NODE. */
5932 TREE_TYPE (arg) = error_mark_node;
5933 TREE_VALUE (argtype) = error_mark_node;
5936 arg = DECL_CHAIN (arg);
5937 argtype = TREE_CHAIN (argtype);
5940 /* Check for bare parameter packs in the return type and the
5941 exception specifiers. */
5942 if (check_for_bare_parameter_packs (TREE_TYPE (type)))
5943 /* Errors were already issued, set return type to int
5944 as the frontend doesn't expect error_mark_node as
5945 the return type. */
5946 TREE_TYPE (type) = integer_type_node;
5947 if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
5948 TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
5950 else
5952 if (check_for_bare_parameter_packs (is_typedef_decl (decl)
5953 ? DECL_ORIGINAL_TYPE (decl)
5954 : TREE_TYPE (decl)))
5956 TREE_TYPE (decl) = error_mark_node;
5957 return error_mark_node;
5960 if (is_partial && VAR_P (decl)
5961 && check_for_bare_parameter_packs (DECL_TI_ARGS (decl)))
5962 return error_mark_node;
5965 if (is_partial)
5966 return process_partial_specialization (decl);
5968 tree args = current_template_args ();
5969 tree tmpl = NULL_TREE;
5970 bool new_template_p = false;
5971 if (local_p)
5973 /* Does not get a template head. */
5974 tmpl = NULL_TREE;
5975 gcc_checking_assert (!is_primary);
5977 else if (!ctx
5978 || TREE_CODE (ctx) == FUNCTION_DECL
5979 || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
5980 || (TREE_CODE (decl) == TYPE_DECL && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5981 || (is_friend && !(DECL_LANG_SPECIFIC (decl)
5982 && DECL_TEMPLATE_INFO (decl))))
5984 if (DECL_LANG_SPECIFIC (decl)
5985 && DECL_TEMPLATE_INFO (decl)
5986 && DECL_TI_TEMPLATE (decl))
5987 tmpl = DECL_TI_TEMPLATE (decl);
5988 /* If DECL is a TYPE_DECL for a class-template, then there won't
5989 be DECL_LANG_SPECIFIC. The information equivalent to
5990 DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead. */
5991 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5992 && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
5993 && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
5995 /* Since a template declaration already existed for this
5996 class-type, we must be redeclaring it here. Make sure
5997 that the redeclaration is valid. */
5998 redeclare_class_template (TREE_TYPE (decl),
5999 current_template_parms,
6000 current_template_constraints ());
6001 /* We don't need to create a new TEMPLATE_DECL; just use the
6002 one we already had. */
6003 tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
6005 else
6007 tmpl = build_template_decl (decl, current_template_parms,
6008 member_template_p);
6009 new_template_p = true;
6011 if (DECL_LANG_SPECIFIC (decl)
6012 && DECL_TEMPLATE_SPECIALIZATION (decl))
6014 /* A specialization of a member template of a template
6015 class. */
6016 SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
6017 DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
6018 DECL_TEMPLATE_INFO (decl) = NULL_TREE;
6022 else
6024 tree a, t, current, parms;
6025 int i;
6026 tree tinfo = get_template_info (decl);
6028 if (!tinfo)
6030 error ("template definition of non-template %q#D", decl);
6031 return error_mark_node;
6034 tmpl = TI_TEMPLATE (tinfo);
6036 if (DECL_FUNCTION_TEMPLATE_P (tmpl)
6037 && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
6038 && DECL_TEMPLATE_SPECIALIZATION (decl)
6039 && DECL_MEMBER_TEMPLATE_P (tmpl))
6041 /* The declaration is a specialization of a member
6042 template, declared outside the class. Therefore, the
6043 innermost template arguments will be NULL, so we
6044 replace them with the arguments determined by the
6045 earlier call to check_explicit_specialization. */
6046 args = DECL_TI_ARGS (decl);
6048 tree new_tmpl
6049 = build_template_decl (decl, current_template_parms,
6050 member_template_p);
6051 DECL_TI_TEMPLATE (decl) = new_tmpl;
6052 SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
6053 DECL_TEMPLATE_INFO (new_tmpl)
6054 = build_template_info (tmpl, args);
6056 register_specialization (new_tmpl,
6057 most_general_template (tmpl),
6058 args,
6059 is_friend, 0);
6060 return decl;
6063 /* Make sure the template headers we got make sense. */
6065 parms = DECL_TEMPLATE_PARMS (tmpl);
6066 i = TMPL_PARMS_DEPTH (parms);
6067 if (TMPL_ARGS_DEPTH (args) != i)
6069 error ("expected %d levels of template parms for %q#D, got %d",
6070 i, decl, TMPL_ARGS_DEPTH (args));
6071 DECL_INTERFACE_KNOWN (decl) = 1;
6072 return error_mark_node;
6074 else
6075 for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
6077 a = TMPL_ARGS_LEVEL (args, i);
6078 t = INNERMOST_TEMPLATE_PARMS (parms);
6080 if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
6082 if (current == decl)
6083 error ("got %d template parameters for %q#D",
6084 TREE_VEC_LENGTH (a), decl);
6085 else
6086 error ("got %d template parameters for %q#T",
6087 TREE_VEC_LENGTH (a), current);
6088 error (" but %d required", TREE_VEC_LENGTH (t));
6089 /* Avoid crash in import_export_decl. */
6090 DECL_INTERFACE_KNOWN (decl) = 1;
6091 return error_mark_node;
6094 if (current == decl)
6095 current = ctx;
6096 else if (current == NULL_TREE)
6097 /* Can happen in erroneous input. */
6098 break;
6099 else
6100 current = get_containing_scope (current);
6103 /* Check that the parms are used in the appropriate qualifying scopes
6104 in the declarator. */
6105 if (!comp_template_args
6106 (TI_ARGS (tinfo),
6107 TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
6109 error ("template arguments to %qD do not match original "
6110 "template %qD", decl, DECL_TEMPLATE_RESULT (tmpl));
6111 if (!uses_template_parms (TI_ARGS (tinfo)))
6112 inform (input_location, "use %<template<>%> for"
6113 " an explicit specialization");
6114 /* Avoid crash in import_export_decl. */
6115 DECL_INTERFACE_KNOWN (decl) = 1;
6116 return error_mark_node;
6119 /* Check that the constraints for each enclosing template scope are
6120 consistent with the original declarations. */
6121 if (flag_concepts)
6123 tree decl_parms = DECL_TEMPLATE_PARMS (tmpl);
6124 tree scope_parms = current_template_parms;
6125 if (PRIMARY_TEMPLATE_P (tmpl))
6127 decl_parms = TREE_CHAIN (decl_parms);
6128 scope_parms = TREE_CHAIN (scope_parms);
6130 while (decl_parms)
6132 if (!template_requirements_equivalent_p (decl_parms, scope_parms))
6134 error ("redeclaration of %qD with different constraints",
6135 TPARMS_PRIMARY_TEMPLATE (TREE_VALUE (decl_parms)));
6136 break;
6138 decl_parms = TREE_CHAIN (decl_parms);
6139 scope_parms = TREE_CHAIN (scope_parms);
6144 gcc_checking_assert (!tmpl || DECL_TEMPLATE_RESULT (tmpl) == decl);
6146 if (new_template_p)
6148 /* Push template declarations for global functions and types.
6149 Note that we do not try to push a global template friend
6150 declared in a template class; such a thing may well depend on
6151 the template parameters of the class and we'll push it when
6152 instantiating the befriending class. */
6153 if (!ctx
6154 && !(is_friend && template_class_depth (current_class_type) > 0))
6156 tree pushed = pushdecl_namespace_level (tmpl, /*hiding=*/is_friend);
6157 if (pushed == error_mark_node)
6158 return error_mark_node;
6160 /* pushdecl may have found an existing template. */
6161 if (pushed != tmpl)
6163 decl = DECL_TEMPLATE_RESULT (pushed);
6164 tmpl = NULL_TREE;
6167 else if (is_friend)
6169 /* Record this decl as belonging to the current class. It's
6170 not chained onto anything else. */
6171 DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (tmpl) = true;
6172 gcc_checking_assert (!DECL_CHAIN (tmpl));
6173 DECL_CHAIN (tmpl) = current_scope ();
6176 else if (tmpl)
6177 /* The type may have been completed, or (erroneously) changed. */
6178 TREE_TYPE (tmpl) = TREE_TYPE (decl);
6180 if (tmpl)
6182 if (is_primary)
6184 tree parms = DECL_TEMPLATE_PARMS (tmpl);
6186 DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
6188 /* Give template template parms a DECL_CONTEXT of the template
6189 for which they are a parameter. */
6190 parms = INNERMOST_TEMPLATE_PARMS (parms);
6191 for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
6193 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
6194 if (TREE_CODE (parm) == TEMPLATE_DECL)
6195 DECL_CONTEXT (parm) = tmpl;
6198 if (TREE_CODE (decl) == TYPE_DECL
6199 && TYPE_DECL_ALIAS_P (decl))
6201 if (tree constr
6202 = TEMPLATE_PARMS_CONSTRAINTS (DECL_TEMPLATE_PARMS (tmpl)))
6204 /* ??? Why don't we do this here for all templates? */
6205 constr = build_constraints (constr, NULL_TREE);
6206 set_constraints (decl, constr);
6208 if (complex_alias_template_p (tmpl))
6209 TEMPLATE_DECL_COMPLEX_ALIAS_P (tmpl) = true;
6213 /* The DECL_TI_ARGS of DECL contains full set of arguments
6214 referring wback to its most general template. If TMPL is a
6215 specialization, ARGS may only have the innermost set of
6216 arguments. Add the missing argument levels if necessary. */
6217 if (DECL_TEMPLATE_INFO (tmpl))
6218 args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
6220 tree info = build_template_info (tmpl, args);
6222 if (DECL_IMPLICIT_TYPEDEF_P (decl))
6223 SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
6224 else
6226 retrofit_lang_decl (decl);
6227 DECL_TEMPLATE_INFO (decl) = info;
6231 if (flag_implicit_templates
6232 && !is_friend
6233 && TREE_PUBLIC (decl)
6234 && VAR_OR_FUNCTION_DECL_P (decl))
6235 /* Set DECL_COMDAT on template instantiations; if we force
6236 them to be emitted by explicit instantiation,
6237 mark_needed will tell cgraph to do the right thing. */
6238 DECL_COMDAT (decl) = true;
6240 gcc_checking_assert (!tmpl || DECL_TEMPLATE_RESULT (tmpl) == decl);
6242 return decl;
6245 /* FN is an inheriting constructor that inherits from the constructor
6246 template INHERITED; turn FN into a constructor template with a matching
6247 template header. */
6249 tree
6250 add_inherited_template_parms (tree fn, tree inherited)
6252 tree inner_parms
6253 = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (inherited));
6254 inner_parms = copy_node (inner_parms);
6255 tree parms
6256 = tree_cons (size_int (current_template_depth + 1),
6257 inner_parms, current_template_parms);
6258 tree tmpl = build_template_decl (fn, parms, /*member*/true);
6259 tree args = template_parms_to_args (parms);
6260 DECL_TEMPLATE_INFO (fn) = build_template_info (tmpl, args);
6261 DECL_ARTIFICIAL (tmpl) = true;
6262 DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
6263 return tmpl;
6266 /* Called when a class template TYPE is redeclared with the indicated
6267 template PARMS, e.g.:
6269 template <class T> struct S;
6270 template <class T> struct S {}; */
6272 bool
6273 redeclare_class_template (tree type, tree parms, tree cons)
6275 tree tmpl;
6276 tree tmpl_parms;
6277 int i;
6279 if (!TYPE_TEMPLATE_INFO (type))
6281 error ("%qT is not a template type", type);
6282 return false;
6285 tmpl = TYPE_TI_TEMPLATE (type);
6286 if (!PRIMARY_TEMPLATE_P (tmpl))
6287 /* The type is nested in some template class. Nothing to worry
6288 about here; there are no new template parameters for the nested
6289 type. */
6290 return true;
6292 if (!parms)
6294 error ("template specifiers not specified in declaration of %qD",
6295 tmpl);
6296 return false;
6299 parms = INNERMOST_TEMPLATE_PARMS (parms);
6300 tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
6302 if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
6304 error_n (input_location, TREE_VEC_LENGTH (parms),
6305 "redeclared with %d template parameter",
6306 "redeclared with %d template parameters",
6307 TREE_VEC_LENGTH (parms));
6308 inform_n (DECL_SOURCE_LOCATION (tmpl), TREE_VEC_LENGTH (tmpl_parms),
6309 "previous declaration %qD used %d template parameter",
6310 "previous declaration %qD used %d template parameters",
6311 tmpl, TREE_VEC_LENGTH (tmpl_parms));
6312 return false;
6315 for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
6317 tree tmpl_parm;
6318 tree parm;
6320 if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
6321 || TREE_VEC_ELT (parms, i) == error_mark_node)
6322 continue;
6324 tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
6325 if (error_operand_p (tmpl_parm))
6326 return false;
6328 parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
6330 /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
6331 TEMPLATE_DECL. */
6332 if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
6333 || (TREE_CODE (tmpl_parm) != TYPE_DECL
6334 && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
6335 || (TREE_CODE (tmpl_parm) != PARM_DECL
6336 && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
6337 != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
6338 || (TREE_CODE (tmpl_parm) == PARM_DECL
6339 && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
6340 != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
6342 auto_diagnostic_group d;
6343 error ("template parameter %q+#D", tmpl_parm);
6344 if (DECL_P (parm))
6345 inform (DECL_SOURCE_LOCATION (parm), "redeclared here as %q#D", parm);
6346 else
6347 inform (input_location, "redeclared here");
6348 return false;
6351 /* The parameters can be declared to introduce different
6352 constraints. */
6353 tree p1 = TREE_VEC_ELT (tmpl_parms, i);
6354 tree p2 = TREE_VEC_ELT (parms, i);
6355 if (!template_parameter_constraints_equivalent_p (p1, p2))
6357 auto_diagnostic_group d;
6358 error ("declaration of template parameter %q+#D with different "
6359 "constraints", parm);
6360 inform (DECL_SOURCE_LOCATION (tmpl_parm),
6361 "original declaration appeared here");
6362 return false;
6365 /* Give each template template parm in this redeclaration a
6366 DECL_CONTEXT of the template for which they are a parameter. */
6367 if (TREE_CODE (parm) == TEMPLATE_DECL)
6369 gcc_checking_assert (DECL_CONTEXT (parm) == NULL_TREE
6370 || DECL_CONTEXT (parm) == tmpl);
6371 DECL_CONTEXT (parm) = tmpl;
6375 if (!merge_default_template_args (parms, tmpl_parms, /*class_p=*/true))
6376 return false;
6378 tree ci = get_constraints (tmpl);
6379 tree req1 = ci ? CI_TEMPLATE_REQS (ci) : NULL_TREE;
6380 tree req2 = cons ? CI_TEMPLATE_REQS (cons) : NULL_TREE;
6382 /* Two classes with different constraints declare different entities. */
6383 if (!cp_tree_equal (req1, req2))
6385 auto_diagnostic_group d;
6386 error_at (input_location, "redeclaration of %q#D with different "
6387 "constraints", tmpl);
6388 inform (DECL_SOURCE_LOCATION (tmpl),
6389 "original declaration appeared here");
6390 return false;
6393 return true;
6396 /* The actual substitution part of instantiate_non_dependent_expr,
6397 to be used when the caller has already checked
6398 !instantiation_dependent_uneval_expression_p (expr)
6399 and cleared processing_template_decl. */
6401 tree
6402 instantiate_non_dependent_expr_internal (tree expr, tsubst_flags_t complain)
6404 return tsubst_expr (expr, /*args=*/NULL_TREE, complain, /*in_decl=*/NULL_TREE);
6407 /* Instantiate the non-dependent expression EXPR. */
6409 tree
6410 instantiate_non_dependent_expr (tree expr,
6411 tsubst_flags_t complain /* = tf_error */)
6413 if (expr == NULL_TREE)
6414 return NULL_TREE;
6416 if (processing_template_decl)
6418 /* The caller should have checked this already. */
6419 gcc_checking_assert (!instantiation_dependent_uneval_expression_p (expr));
6420 processing_template_decl_sentinel s;
6421 expr = instantiate_non_dependent_expr_internal (expr, complain);
6423 return expr;
6426 /* Like instantiate_non_dependent_expr, but return NULL_TREE if the
6427 expression is dependent or non-constant. */
6429 tree
6430 instantiate_non_dependent_or_null (tree expr)
6432 if (expr == NULL_TREE)
6433 return NULL_TREE;
6434 if (processing_template_decl)
6436 if (!is_nondependent_constant_expression (expr))
6437 expr = NULL_TREE;
6438 else
6440 processing_template_decl_sentinel s;
6441 expr = instantiate_non_dependent_expr_internal (expr, tf_error);
6444 return expr;
6447 /* True iff T is a specialization of a variable template. */
6449 bool
6450 variable_template_specialization_p (tree t)
6452 if (!VAR_P (t) || !DECL_LANG_SPECIFIC (t) || !DECL_TEMPLATE_INFO (t))
6453 return false;
6454 tree tmpl = DECL_TI_TEMPLATE (t);
6455 return variable_template_p (tmpl);
6458 /* Return TRUE iff T is a type alias, a TEMPLATE_DECL for an alias
6459 template declaration, or a TYPE_DECL for an alias declaration. */
6461 bool
6462 alias_type_or_template_p (tree t)
6464 if (t == NULL_TREE)
6465 return false;
6466 return ((TREE_CODE (t) == TYPE_DECL && TYPE_DECL_ALIAS_P (t))
6467 || (TYPE_P (t)
6468 && TYPE_NAME (t)
6469 && TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
6470 || DECL_ALIAS_TEMPLATE_P (t));
6473 /* If T is a specialization of an alias template, return it; otherwise return
6474 NULL_TREE. If TRANSPARENT_TYPEDEFS is true, look through other aliases. */
6476 tree
6477 alias_template_specialization_p (const_tree t,
6478 bool transparent_typedefs)
6480 if (!TYPE_P (t))
6481 return NULL_TREE;
6483 /* It's an alias template specialization if it's an alias and its
6484 TYPE_NAME is a specialization of a primary template. */
6485 if (typedef_variant_p (t))
6487 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
6488 if (PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo)))
6489 return CONST_CAST_TREE (t);
6490 if (transparent_typedefs)
6491 return alias_template_specialization_p (DECL_ORIGINAL_TYPE
6492 (TYPE_NAME (t)),
6493 transparent_typedefs);
6496 return NULL_TREE;
6499 /* Data structure for complex_alias_template_*. */
6501 struct uses_all_template_parms_data
6503 int level;
6504 bool *seen;
6507 /* walk_tree callback for complex_alias_template_p. */
6509 static tree
6510 complex_alias_template_r (tree *tp, int *walk_subtrees, void *data_)
6512 tree t = *tp;
6513 auto &data = *(struct uses_all_template_parms_data*)data_;
6515 switch (TREE_CODE (t))
6517 case TEMPLATE_TYPE_PARM:
6518 case TEMPLATE_PARM_INDEX:
6519 case TEMPLATE_TEMPLATE_PARM:
6520 case BOUND_TEMPLATE_TEMPLATE_PARM:
6522 tree idx = get_template_parm_index (t);
6523 if (TEMPLATE_PARM_LEVEL (idx) == data.level)
6524 data.seen[TEMPLATE_PARM_IDX (idx)] = true;
6527 default:;
6530 if (!PACK_EXPANSION_P (t))
6531 return 0;
6533 /* An alias template with a pack expansion that expands a pack from the
6534 enclosing class needs to be considered complex, to avoid confusion with
6535 the same pack being used as an argument to the alias's own template
6536 parameter (91966). */
6537 for (tree pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
6538 pack = TREE_CHAIN (pack))
6540 tree parm_pack = TREE_VALUE (pack);
6541 if (!TEMPLATE_PARM_P (parm_pack))
6542 continue;
6543 int idx, level;
6544 template_parm_level_and_index (parm_pack, &level, &idx);
6545 if (level < data.level)
6546 return t;
6548 /* Consider the expanded packs to be used outside the expansion... */
6549 data.seen[idx] = true;
6552 /* ...but don't walk into the pattern. Consider PR104008:
6554 template <typename T, typename... Ts>
6555 using IsOneOf = disjunction<is_same<T, Ts>...>;
6557 where IsOneOf seemingly uses all of its template parameters in its
6558 expansion (and does not expand a pack from the enclosing class), so the
6559 alias was not marked as complex. However, if it is used like
6560 "IsOneOf<T>", the empty pack for Ts means that T no longer appears in the
6561 expansion. So only Ts is considered used by the pack expansion. */
6562 *walk_subtrees = false;
6564 return 0;
6567 /* An alias template is complex from a SFINAE perspective if a template-id
6568 using that alias can be ill-formed when the expansion is not, as with
6569 the void_t template.
6571 Returns 1 if always complex, 0 if not complex, -1 if complex iff any of the
6572 template arguments are empty packs. */
6574 static bool
6575 complex_alias_template_p (const_tree tmpl)
6577 /* A renaming alias isn't complex. */
6578 if (get_underlying_template (CONST_CAST_TREE (tmpl)) != tmpl)
6579 return false;
6581 /* Any other constrained alias is complex. */
6582 if (get_constraints (tmpl))
6583 return true;
6585 struct uses_all_template_parms_data data;
6586 tree pat = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6587 tree parms = DECL_TEMPLATE_PARMS (tmpl);
6588 data.level = TMPL_PARMS_DEPTH (parms);
6589 int len = TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS (parms));
6590 data.seen = XALLOCAVEC (bool, len);
6591 for (int i = 0; i < len; ++i)
6592 data.seen[i] = false;
6594 if (cp_walk_tree_without_duplicates (&pat, complex_alias_template_r, &data))
6595 return true;
6596 for (int i = 0; i < len; ++i)
6597 if (!data.seen[i])
6598 return true;
6599 return false;
6602 /* If T is a specialization of a complex alias template with dependent
6603 template-arguments, return it; otherwise return NULL_TREE. If T is a
6604 typedef to such a specialization, return the specialization. */
6606 tree
6607 dependent_alias_template_spec_p (const_tree t, bool transparent_typedefs)
6609 if (t == error_mark_node)
6610 return NULL_TREE;
6611 gcc_assert (TYPE_P (t));
6613 if (!typedef_variant_p (t))
6614 return NULL_TREE;
6616 tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t);
6617 if (tinfo
6618 && TEMPLATE_DECL_COMPLEX_ALIAS_P (TI_TEMPLATE (tinfo))
6619 && (any_dependent_template_arguments_p
6620 (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)))))
6621 return CONST_CAST_TREE (t);
6623 if (transparent_typedefs)
6625 tree utype = DECL_ORIGINAL_TYPE (TYPE_NAME (t));
6626 return dependent_alias_template_spec_p (utype, transparent_typedefs);
6629 return NULL_TREE;
6632 /* Return the number of innermost template parameters in TMPL. */
6634 static int
6635 num_innermost_template_parms (const_tree tmpl)
6637 tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
6638 return TREE_VEC_LENGTH (parms);
6641 /* Return either TMPL or another template that it is equivalent to under DR
6642 1286: An alias that just changes the name of a template is equivalent to
6643 the other template. */
6645 static tree
6646 get_underlying_template (tree tmpl)
6648 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
6649 while (DECL_ALIAS_TEMPLATE_P (tmpl))
6651 /* Determine if the alias is equivalent to an underlying template. */
6652 tree orig_type = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6653 /* The underlying type may have been ill-formed. Don't proceed. */
6654 if (!orig_type)
6655 break;
6656 tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (orig_type);
6657 if (!tinfo)
6658 break;
6660 tree underlying = TI_TEMPLATE (tinfo);
6661 if (!PRIMARY_TEMPLATE_P (underlying)
6662 || (num_innermost_template_parms (tmpl)
6663 != num_innermost_template_parms (underlying)))
6664 break;
6666 /* Does the alias add cv-quals? */
6667 if (TYPE_QUALS (TREE_TYPE (underlying)) != TYPE_QUALS (TREE_TYPE (tmpl)))
6668 break;
6670 tree alias_args = INNERMOST_TEMPLATE_ARGS (generic_targs_for (tmpl));
6671 if (!comp_template_args (TI_ARGS (tinfo), alias_args))
6672 break;
6674 /* Are any default template arguments equivalent? */
6675 tree aparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
6676 tree uparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (underlying));
6677 const int nparms = TREE_VEC_LENGTH (aparms);
6678 for (int i = 0; i < nparms; ++i)
6680 tree adefarg = TREE_PURPOSE (TREE_VEC_ELT (aparms, i));
6681 tree udefarg = TREE_PURPOSE (TREE_VEC_ELT (uparms, i));
6682 if (!template_args_equal (adefarg, udefarg))
6683 goto top_break;
6686 /* If TMPL adds or changes any constraints, it isn't equivalent. I think
6687 it's appropriate to treat a less-constrained alias as equivalent. */
6688 if (!at_least_as_constrained (underlying, tmpl))
6689 break;
6691 /* Alias is equivalent. Strip it and repeat. */
6692 tmpl = underlying;
6694 top_break:;
6696 return tmpl;
6699 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
6700 must be a reference-to-function or a pointer-to-function type, as specified
6701 in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
6702 and check that the resulting function has external linkage. */
6704 static tree
6705 convert_nontype_argument_function (tree type, tree expr,
6706 tsubst_flags_t complain)
6708 tree fns = expr;
6709 tree fn, fn_no_ptr;
6710 linkage_kind linkage;
6712 fn = instantiate_type (type, fns, tf_none);
6713 if (fn == error_mark_node)
6714 return error_mark_node;
6716 if (value_dependent_expression_p (fn))
6717 goto accept;
6719 fn_no_ptr = fn;
6720 if (REFERENCE_REF_P (fn_no_ptr))
6721 fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
6722 fn_no_ptr = strip_fnptr_conv (fn_no_ptr);
6723 if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
6724 fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
6725 if (BASELINK_P (fn_no_ptr))
6726 fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
6728 /* [temp.arg.nontype]/1
6730 A template-argument for a non-type, non-template template-parameter
6731 shall be one of:
6732 [...]
6733 -- the address of an object or function with external [C++11: or
6734 internal] linkage. */
6736 STRIP_ANY_LOCATION_WRAPPER (fn_no_ptr);
6737 if (TREE_CODE (fn_no_ptr) != FUNCTION_DECL)
6739 if (complain & tf_error)
6741 location_t loc = cp_expr_loc_or_input_loc (expr);
6742 error_at (loc, "%qE is not a valid template argument for type %qT",
6743 expr, type);
6744 if (TYPE_PTR_P (type))
6745 inform (loc, "it must be the address of a function "
6746 "with external linkage");
6747 else
6748 inform (loc, "it must be the name of a function with "
6749 "external linkage");
6751 return NULL_TREE;
6754 linkage = decl_linkage (fn_no_ptr);
6755 if ((cxx_dialect < cxx11 && linkage != lk_external)
6756 || (cxx_dialect < cxx17 && linkage == lk_none))
6758 if (complain & tf_error)
6760 location_t loc = cp_expr_loc_or_input_loc (expr);
6761 if (cxx_dialect >= cxx11)
6762 error_at (loc, "%qE is not a valid template argument for type "
6763 "%qT because %qD has no linkage",
6764 expr, type, fn_no_ptr);
6765 else
6766 error_at (loc, "%qE is not a valid template argument for type "
6767 "%qT because %qD does not have external linkage",
6768 expr, type, fn_no_ptr);
6770 return NULL_TREE;
6773 accept:
6774 if (TYPE_REF_P (type))
6776 if (REFERENCE_REF_P (fn))
6777 fn = TREE_OPERAND (fn, 0);
6778 else
6779 fn = build_address (fn);
6781 if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (fn)))
6782 fn = build_nop (type, fn);
6784 return fn;
6787 /* Subroutine of convert_nontype_argument.
6788 Check if EXPR of type TYPE is a valid pointer-to-member constant.
6789 Emit an error otherwise. */
6791 static bool
6792 check_valid_ptrmem_cst_expr (tree type, tree expr,
6793 tsubst_flags_t complain)
6795 tree orig_expr = expr;
6796 STRIP_NOPS (expr);
6797 if (null_ptr_cst_p (expr))
6798 return true;
6799 if (TREE_CODE (expr) == PTRMEM_CST
6800 && same_type_p (TYPE_PTRMEM_CLASS_TYPE (type),
6801 PTRMEM_CST_CLASS (expr)))
6802 return true;
6803 if (cxx_dialect >= cxx11 && null_member_pointer_value_p (expr))
6804 return true;
6805 if (processing_template_decl
6806 && TREE_CODE (expr) == ADDR_EXPR
6807 && TREE_CODE (TREE_OPERAND (expr, 0)) == OFFSET_REF)
6808 return true;
6809 if (complain & tf_error)
6811 location_t loc = cp_expr_loc_or_input_loc (orig_expr);
6812 error_at (loc, "%qE is not a valid template argument for type %qT",
6813 orig_expr, type);
6814 if (TREE_CODE (expr) != PTRMEM_CST)
6815 inform (loc, "it must be a pointer-to-member of the form %<&X::Y%>");
6816 else
6817 inform (loc, "because it is a member of %qT", PTRMEM_CST_CLASS (expr));
6819 return false;
6822 /* Returns TRUE iff the address of OP is value-dependent.
6824 14.6.2.4 [temp.dep.temp]:
6825 A non-integral non-type template-argument is dependent if its type is
6826 dependent or it has either of the following forms
6827 qualified-id
6828 & qualified-id
6829 and contains a nested-name-specifier which specifies a class-name that
6830 names a dependent type.
6832 We generalize this to just say that the address of a member of a
6833 dependent class is value-dependent; the above doesn't cover the
6834 address of a static data member named with an unqualified-id. */
6836 static bool
6837 has_value_dependent_address (tree op)
6839 STRIP_ANY_LOCATION_WRAPPER (op);
6841 /* We could use get_inner_reference here, but there's no need;
6842 this is only relevant for template non-type arguments, which
6843 can only be expressed as &id-expression. */
6844 if (DECL_P (op))
6846 tree ctx = CP_DECL_CONTEXT (op);
6848 if (TYPE_P (ctx) && dependent_type_p (ctx))
6849 return true;
6851 if (VAR_P (op)
6852 && TREE_STATIC (op)
6853 && TREE_CODE (ctx) == FUNCTION_DECL
6854 && type_dependent_expression_p (ctx))
6855 return true;
6858 return false;
6861 /* The next set of functions are used for providing helpful explanatory
6862 diagnostics for failed overload resolution. Their messages should be
6863 indented by two spaces for consistency with the messages in
6864 call.cc */
6866 static int
6867 unify_success (bool /*explain_p*/)
6869 return 0;
6872 /* Other failure functions should call this one, to provide a single function
6873 for setting a breakpoint on. */
6875 static int
6876 unify_invalid (bool /*explain_p*/)
6878 return 1;
6881 static int
6882 unify_parameter_deduction_failure (bool explain_p, tree parm)
6884 if (explain_p)
6885 inform (input_location,
6886 " couldn%'t deduce template parameter %qD", parm);
6887 return unify_invalid (explain_p);
6890 static int
6891 unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
6893 if (explain_p)
6894 inform (input_location,
6895 " types %qT and %qT have incompatible cv-qualifiers",
6896 parm, arg);
6897 return unify_invalid (explain_p);
6900 static int
6901 unify_type_mismatch (bool explain_p, tree parm, tree arg)
6903 if (explain_p)
6904 inform (input_location, " mismatched types %qT and %qT", parm, arg);
6905 return unify_invalid (explain_p);
6908 static int
6909 unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
6911 if (explain_p)
6912 inform (input_location,
6913 " template parameter %qD is not a parameter pack, but "
6914 "argument %qD is",
6915 parm, arg);
6916 return unify_invalid (explain_p);
6919 static int
6920 unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
6922 if (explain_p)
6923 inform (input_location,
6924 " template argument %qE does not match "
6925 "pointer-to-member constant %qE",
6926 arg, parm);
6927 return unify_invalid (explain_p);
6930 static int
6931 unify_expression_unequal (bool explain_p, tree parm, tree arg)
6933 if (explain_p)
6934 inform (input_location, " %qE is not equivalent to %qE", parm, arg);
6935 return unify_invalid (explain_p);
6938 static int
6939 unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
6941 if (explain_p)
6942 inform (input_location,
6943 " inconsistent parameter pack deduction with %qT and %qT",
6944 old_arg, new_arg);
6945 return unify_invalid (explain_p);
6948 static int
6949 unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
6951 if (explain_p)
6953 if (TYPE_P (parm))
6954 inform (input_location,
6955 " deduced conflicting types for parameter %qT (%qT and %qT)",
6956 parm, first, second);
6957 else
6958 inform (input_location,
6959 " deduced conflicting values for non-type parameter "
6960 "%qE (%qE and %qE)", parm, first, second);
6962 return unify_invalid (explain_p);
6965 static int
6966 unify_vla_arg (bool explain_p, tree arg)
6968 if (explain_p)
6969 inform (input_location,
6970 " variable-sized array type %qT is not "
6971 "a valid template argument",
6972 arg);
6973 return unify_invalid (explain_p);
6976 static int
6977 unify_method_type_error (bool explain_p, tree arg)
6979 if (explain_p)
6980 inform (input_location,
6981 " member function type %qT is not a valid template argument",
6982 arg);
6983 return unify_invalid (explain_p);
6986 static int
6987 unify_arity (bool explain_p, int have, int wanted, bool least_p = false)
6989 if (explain_p)
6991 if (least_p)
6992 inform_n (input_location, wanted,
6993 " candidate expects at least %d argument, %d provided",
6994 " candidate expects at least %d arguments, %d provided",
6995 wanted, have);
6996 else
6997 inform_n (input_location, wanted,
6998 " candidate expects %d argument, %d provided",
6999 " candidate expects %d arguments, %d provided",
7000 wanted, have);
7002 return unify_invalid (explain_p);
7005 static int
7006 unify_too_many_arguments (bool explain_p, int have, int wanted)
7008 return unify_arity (explain_p, have, wanted);
7011 static int
7012 unify_too_few_arguments (bool explain_p, int have, int wanted,
7013 bool least_p = false)
7015 return unify_arity (explain_p, have, wanted, least_p);
7018 static int
7019 unify_arg_conversion (bool explain_p, tree to_type,
7020 tree from_type, tree arg)
7022 if (explain_p)
7023 inform (cp_expr_loc_or_input_loc (arg),
7024 " cannot convert %qE (type %qT) to type %qT",
7025 arg, from_type, to_type);
7026 return unify_invalid (explain_p);
7029 static int
7030 unify_no_common_base (bool explain_p, enum template_base_result r,
7031 tree parm, tree arg)
7033 if (explain_p)
7034 switch (r)
7036 case tbr_ambiguous_baseclass:
7037 inform (input_location, " %qT is an ambiguous base class of %qT",
7038 parm, arg);
7039 break;
7040 default:
7041 inform (input_location, " %qT is not derived from %qT", arg, parm);
7042 break;
7044 return unify_invalid (explain_p);
7047 static int
7048 unify_inconsistent_template_template_parameters (bool explain_p)
7050 if (explain_p)
7051 inform (input_location,
7052 " template parameters of a template template argument are "
7053 "inconsistent with other deduced template arguments");
7054 return unify_invalid (explain_p);
7057 static int
7058 unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
7060 if (explain_p)
7061 inform (input_location,
7062 " cannot deduce a template for %qT from non-template type %qT",
7063 parm, arg);
7064 return unify_invalid (explain_p);
7067 static int
7068 unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
7070 if (explain_p)
7071 inform (input_location,
7072 " template argument %qE does not match %qE", arg, parm);
7073 return unify_invalid (explain_p);
7076 /* Subroutine of convert_nontype_argument, to check whether EXPR, as an
7077 argument for TYPE, points to an unsuitable object.
7079 Also adjust the type of the index in C++20 array subobject references. */
7081 static bool
7082 invalid_tparm_referent_p (tree type, tree expr, tsubst_flags_t complain)
7084 switch (TREE_CODE (expr))
7086 CASE_CONVERT:
7087 return invalid_tparm_referent_p (type, TREE_OPERAND (expr, 0),
7088 complain);
7090 case TARGET_EXPR:
7091 return invalid_tparm_referent_p (type, TARGET_EXPR_INITIAL (expr),
7092 complain);
7094 case CONSTRUCTOR:
7096 for (auto &e: CONSTRUCTOR_ELTS (expr))
7097 if (invalid_tparm_referent_p (TREE_TYPE (e.value), e.value, complain))
7098 return true;
7100 break;
7102 case ADDR_EXPR:
7104 tree decl = TREE_OPERAND (expr, 0);
7106 if (cxx_dialect >= cxx20)
7107 while (TREE_CODE (decl) == COMPONENT_REF
7108 || TREE_CODE (decl) == ARRAY_REF)
7110 tree &op = TREE_OPERAND (decl, 1);
7111 if (TREE_CODE (decl) == ARRAY_REF
7112 && TREE_CODE (op) == INTEGER_CST)
7113 /* Canonicalize array offsets to ptrdiff_t; how they were
7114 written doesn't matter for subobject identity. */
7115 op = fold_convert (ptrdiff_type_node, op);
7116 decl = TREE_OPERAND (decl, 0);
7119 if (!VAR_OR_FUNCTION_DECL_P (decl))
7121 if (complain & tf_error)
7122 error_at (cp_expr_loc_or_input_loc (expr),
7123 "%qE is not a valid template argument of type %qT "
7124 "because %qE is not a variable or function",
7125 expr, type, decl);
7126 return true;
7128 else if (cxx_dialect < cxx11 && !DECL_EXTERNAL_LINKAGE_P (decl))
7130 if (complain & tf_error)
7131 error_at (cp_expr_loc_or_input_loc (expr),
7132 "%qE is not a valid template argument of type %qT "
7133 "in C++98 because %qD does not have external linkage",
7134 expr, type, decl);
7135 return true;
7137 else if ((cxx_dialect >= cxx11 && cxx_dialect < cxx17)
7138 && decl_linkage (decl) == lk_none)
7140 if (complain & tf_error)
7141 error_at (cp_expr_loc_or_input_loc (expr),
7142 "%qE is not a valid template argument of type %qT "
7143 "because %qD has no linkage", expr, type, decl);
7144 return true;
7146 /* C++17: For a non-type template-parameter of reference or pointer
7147 type, the value of the constant expression shall not refer to (or
7148 for a pointer type, shall not be the address of):
7149 * a subobject (4.5),
7150 * a temporary object (15.2),
7151 * a string literal (5.13.5),
7152 * the result of a typeid expression (8.2.8), or
7153 * a predefined __func__ variable (11.4.1). */
7154 else if (VAR_P (decl) && DECL_ARTIFICIAL (decl))
7156 if (complain & tf_error)
7157 error ("the address of %qD is not a valid template argument",
7158 decl);
7159 return true;
7161 else if (cxx_dialect < cxx20
7162 && !(same_type_ignoring_top_level_qualifiers_p
7163 (strip_array_types (TREE_TYPE (type)),
7164 strip_array_types (TREE_TYPE (decl)))))
7166 if (complain & tf_error)
7167 error ("the address of the %qT subobject of %qD is not a "
7168 "valid template argument", TREE_TYPE (type), decl);
7169 return true;
7171 else if (!TREE_STATIC (decl) && !DECL_EXTERNAL (decl))
7173 if (complain & tf_error)
7174 error ("the address of %qD is not a valid template argument "
7175 "because it does not have static storage duration",
7176 decl);
7177 return true;
7180 break;
7182 default:
7183 if (!INDIRECT_TYPE_P (type))
7184 /* We're only concerned about pointers and references here. */;
7185 else if (cxx_dialect >= cxx11 && integer_zerop (expr))
7186 /* Null pointer values are OK in C++11. */;
7187 else
7189 if (VAR_P (expr))
7191 if (complain & tf_error)
7192 error ("%qD is not a valid template argument "
7193 "because %qD is a variable, not the address of "
7194 "a variable", expr, expr);
7195 return true;
7197 else
7199 if (complain & tf_error)
7200 error ("%qE is not a valid template argument for %qT "
7201 "because it is not the address of a variable",
7202 expr, type);
7203 return true;
7207 return false;
7211 /* Return a VAR_DECL for the C++20 template parameter object corresponding to
7212 template argument EXPR. */
7214 static tree
7215 create_template_parm_object (tree expr, tsubst_flags_t complain)
7217 if (TREE_CODE (expr) == TARGET_EXPR)
7218 expr = TARGET_EXPR_INITIAL (expr);
7220 if (!TREE_CONSTANT (expr))
7222 if ((complain & tf_error)
7223 && require_rvalue_constant_expression (expr))
7224 cxx_constant_value (expr);
7225 return error_mark_node;
7227 if (invalid_tparm_referent_p (TREE_TYPE (expr), expr, complain))
7228 return error_mark_node;
7230 /* This is no longer a compound literal. */
7231 gcc_assert (!TREE_HAS_CONSTRUCTOR (expr));
7233 return get_template_parm_object (expr, mangle_template_parm_object (expr));
7236 /* The template arguments corresponding to template parameter objects of types
7237 that contain pointers to members. */
7239 static GTY(()) hash_map<tree, tree> *tparm_obj_values;
7241 /* Find or build an nttp object for (already-validated) EXPR with name
7242 NAME. */
7244 tree
7245 get_template_parm_object (tree expr, tree name)
7247 tree decl = get_global_binding (name);
7248 if (decl)
7249 return decl;
7251 tree type = cp_build_qualified_type (TREE_TYPE (expr), TYPE_QUAL_CONST);
7252 decl = create_temporary_var (type);
7253 DECL_NTTP_OBJECT_P (decl) = true;
7254 DECL_CONTEXT (decl) = NULL_TREE;
7255 TREE_STATIC (decl) = true;
7256 DECL_DECLARED_CONSTEXPR_P (decl) = true;
7257 TREE_READONLY (decl) = true;
7258 DECL_NAME (decl) = name;
7259 SET_DECL_ASSEMBLER_NAME (decl, name);
7260 comdat_linkage (decl);
7262 if (!zero_init_p (type))
7264 /* If EXPR contains any PTRMEM_CST, they will get clobbered by
7265 lower_var_init before we're done mangling. So store the original
7266 value elsewhere. */
7267 tree copy = unshare_constructor (expr);
7268 hash_map_safe_put<hm_ggc> (tparm_obj_values, decl, copy);
7271 pushdecl_top_level_and_finish (decl, expr);
7273 return decl;
7276 /* Return the actual template argument corresponding to template parameter
7277 object VAR. */
7279 tree
7280 tparm_object_argument (tree var)
7282 if (zero_init_p (TREE_TYPE (var)))
7283 return DECL_INITIAL (var);
7284 return *(tparm_obj_values->get (var));
7287 /* Attempt to convert the non-type template parameter EXPR to the
7288 indicated TYPE. If the conversion is successful, return the
7289 converted value. If the conversion is unsuccessful, return
7290 NULL_TREE if we issued an error message, or error_mark_node if we
7291 did not. We issue error messages for out-and-out bad template
7292 parameters, but not simply because the conversion failed, since we
7293 might be just trying to do argument deduction. Both TYPE and EXPR
7294 must be non-dependent.
7296 The conversion follows the special rules described in
7297 [temp.arg.nontype], and it is much more strict than an implicit
7298 conversion.
7300 This function is called twice for each template argument (see
7301 lookup_template_class for a more accurate description of this
7302 problem). This means that we need to handle expressions which
7303 are not valid in a C++ source, but can be created from the
7304 first call (for instance, casts to perform conversions). These
7305 hacks can go away after we fix the double coercion problem. */
7307 static tree
7308 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
7310 tree expr_type;
7311 location_t loc = cp_expr_loc_or_input_loc (expr);
7313 /* Detect immediately string literals as invalid non-type argument.
7314 This special-case is not needed for correctness (we would easily
7315 catch this later), but only to provide better diagnostic for this
7316 common user mistake. As suggested by DR 100, we do not mention
7317 linkage issues in the diagnostic as this is not the point. */
7318 if (TREE_CODE (expr) == STRING_CST && !CLASS_TYPE_P (type))
7320 if (complain & tf_error)
7321 error ("%qE is not a valid template argument for type %qT "
7322 "because string literals can never be used in this context",
7323 expr, type);
7324 return NULL_TREE;
7327 /* Add the ADDR_EXPR now for the benefit of
7328 value_dependent_expression_p. */
7329 if (TYPE_PTROBV_P (type)
7330 && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
7332 expr = decay_conversion (expr, complain);
7333 if (expr == error_mark_node)
7334 return error_mark_node;
7337 /* If we are in a template, EXPR may be non-dependent, but still
7338 have a syntactic, rather than semantic, form. For example, EXPR
7339 might be a SCOPE_REF, rather than the VAR_DECL to which the
7340 SCOPE_REF refers. Preserving the qualifying scope is necessary
7341 so that access checking can be performed when the template is
7342 instantiated -- but here we need the resolved form so that we can
7343 convert the argument. */
7344 bool non_dep = false;
7345 if (TYPE_REF_OBJ_P (type)
7346 && has_value_dependent_address (expr))
7347 /* If we want the address and it's value-dependent, don't fold. */;
7348 else if (processing_template_decl
7349 && !instantiation_dependent_expression_p (expr))
7350 non_dep = true;
7351 if (error_operand_p (expr))
7352 return error_mark_node;
7353 expr_type = TREE_TYPE (expr);
7355 /* If the argument is non-dependent, perform any conversions in
7356 non-dependent context as well. */
7357 processing_template_decl_sentinel s (non_dep);
7358 if (non_dep)
7359 expr = instantiate_non_dependent_expr_internal (expr, complain);
7361 bool val_dep_p = value_dependent_expression_p (expr);
7362 if (val_dep_p)
7363 expr = canonicalize_expr_argument (expr, complain);
7364 else
7365 STRIP_ANY_LOCATION_WRAPPER (expr);
7367 /* 14.3.2/5: The null pointer{,-to-member} conversion is applied
7368 to a non-type argument of "nullptr". */
7369 if (NULLPTR_TYPE_P (expr_type) && TYPE_PTR_OR_PTRMEM_P (type))
7370 expr = fold_simple (convert (type, expr));
7372 /* In C++11, integral or enumeration non-type template arguments can be
7373 arbitrary constant expressions. Pointer and pointer to
7374 member arguments can be general constant expressions that evaluate
7375 to a null value, but otherwise still need to be of a specific form. */
7376 if (cxx_dialect >= cxx11)
7378 if (TREE_CODE (expr) == PTRMEM_CST && TYPE_PTRMEM_P (type))
7379 /* A PTRMEM_CST is already constant, and a valid template
7380 argument for a parameter of pointer to member type, we just want
7381 to leave it in that form rather than lower it to a
7382 CONSTRUCTOR. */;
7383 else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
7384 || cxx_dialect >= cxx17)
7386 /* C++17: A template-argument for a non-type template-parameter shall
7387 be a converted constant expression (8.20) of the type of the
7388 template-parameter. */
7389 expr = build_converted_constant_expr (type, expr, complain);
7390 if (expr == error_mark_node)
7391 /* Make sure we return NULL_TREE only if we have really issued
7392 an error, as described above. */
7393 return (complain & tf_error) ? NULL_TREE : error_mark_node;
7394 else if (TREE_CODE (expr) == IMPLICIT_CONV_EXPR)
7396 IMPLICIT_CONV_EXPR_NONTYPE_ARG (expr) = true;
7397 return expr;
7399 expr = maybe_constant_value (expr, NULL_TREE, mce_true);
7400 expr = convert_from_reference (expr);
7401 /* EXPR may have become value-dependent. */
7402 val_dep_p = value_dependent_expression_p (expr);
7404 else if (TYPE_PTR_OR_PTRMEM_P (type))
7406 tree folded = maybe_constant_value (expr, NULL_TREE, mce_true);
7407 if (TYPE_PTR_P (type) ? integer_zerop (folded)
7408 : null_member_pointer_value_p (folded))
7409 expr = folded;
7413 if (TYPE_REF_P (type))
7414 expr = mark_lvalue_use (expr);
7415 else
7416 expr = mark_rvalue_use (expr);
7418 /* HACK: Due to double coercion, we can get a
7419 NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
7420 which is the tree that we built on the first call (see
7421 below when coercing to reference to object or to reference to
7422 function). We just strip everything and get to the arg.
7423 See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
7424 for examples. */
7425 if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
7427 /* Check this before we strip *& to avoid redundancy. */
7428 if (!mark_single_function (expr, complain))
7429 return error_mark_node;
7431 tree probe_type, probe = expr;
7432 if (REFERENCE_REF_P (probe))
7433 probe = TREE_OPERAND (probe, 0);
7434 probe_type = TREE_TYPE (probe);
7435 if (TREE_CODE (probe) == NOP_EXPR)
7437 /* ??? Maybe we could use convert_from_reference here, but we
7438 would need to relax its constraints because the NOP_EXPR
7439 could actually change the type to something more cv-qualified,
7440 and this is not folded by convert_from_reference. */
7441 tree addr = TREE_OPERAND (probe, 0);
7442 if (TYPE_REF_P (probe_type)
7443 && TREE_CODE (addr) == ADDR_EXPR
7444 && TYPE_PTR_P (TREE_TYPE (addr))
7445 && (same_type_ignoring_top_level_qualifiers_p
7446 (TREE_TYPE (probe_type),
7447 TREE_TYPE (TREE_TYPE (addr)))))
7449 expr = TREE_OPERAND (addr, 0);
7450 expr_type = TREE_TYPE (probe_type);
7455 /* [temp.arg.nontype]/5, bullet 1
7457 For a non-type template-parameter of integral or enumeration type,
7458 integral promotions (_conv.prom_) and integral conversions
7459 (_conv.integral_) are applied. */
7460 if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
7461 || SCALAR_FLOAT_TYPE_P (type))
7463 if (cxx_dialect < cxx11)
7465 tree t = build_converted_constant_expr (type, expr, complain);
7466 t = maybe_constant_value (t);
7467 if (t != error_mark_node)
7468 expr = t;
7471 if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
7472 return error_mark_node;
7474 /* Notice that there are constant expressions like '4 % 0' which
7475 do not fold into integer constants. */
7476 if (!CONSTANT_CLASS_P (expr) && !val_dep_p)
7478 if (complain & tf_error)
7480 int errs = errorcount, warns = warningcount + werrorcount;
7481 if (!require_potential_constant_expression (expr))
7482 expr = error_mark_node;
7483 else
7484 expr = cxx_constant_value (expr);
7485 if (errorcount > errs || warningcount + werrorcount > warns)
7486 inform (loc, "in template argument for type %qT", type);
7487 if (expr == error_mark_node)
7488 return NULL_TREE;
7489 /* else cxx_constant_value complained but gave us
7490 a real constant, so go ahead. */
7491 if (!CONSTANT_CLASS_P (expr))
7493 /* Some assemble time constant expressions like
7494 (intptr_t)&&lab1 - (intptr_t)&&lab2 or
7495 4 + (intptr_t)&&var satisfy reduced_constant_expression_p
7496 as we can emit them into .rodata initializers of
7497 variables, yet they can't fold into an INTEGER_CST at
7498 compile time. Refuse them here. */
7499 gcc_checking_assert (reduced_constant_expression_p (expr));
7500 error_at (loc, "template argument %qE for type %qT not "
7501 "a compile-time constant", expr, type);
7502 return NULL_TREE;
7505 else
7506 return NULL_TREE;
7509 /* Avoid typedef problems. */
7510 if (TREE_TYPE (expr) != type)
7511 expr = fold_convert (type, expr);
7513 /* [temp.arg.nontype]/5, bullet 2
7515 For a non-type template-parameter of type pointer to object,
7516 qualification conversions (_conv.qual_) and the array-to-pointer
7517 conversion (_conv.array_) are applied. */
7518 else if (TYPE_PTROBV_P (type))
7520 tree decayed = expr;
7522 /* Look through any NOP_EXPRs around an ADDR_EXPR, whether they come from
7523 decay_conversion or an explicit cast. If it's a problematic cast,
7524 we'll complain about it below. */
7525 if (TREE_CODE (expr) == NOP_EXPR)
7527 tree probe = expr;
7528 STRIP_NOPS (probe);
7529 if (TREE_CODE (probe) == ADDR_EXPR
7530 && TYPE_PTR_P (TREE_TYPE (probe)))
7532 expr = probe;
7533 expr_type = TREE_TYPE (expr);
7537 /* [temp.arg.nontype]/1 (TC1 version, DR 49):
7539 A template-argument for a non-type, non-template template-parameter
7540 shall be one of: [...]
7542 -- the name of a non-type template-parameter;
7543 -- the address of an object or function with external linkage, [...]
7544 expressed as "& id-expression" where the & is optional if the name
7545 refers to a function or array, or if the corresponding
7546 template-parameter is a reference.
7548 Here, we do not care about functions, as they are invalid anyway
7549 for a parameter of type pointer-to-object. */
7551 if (val_dep_p)
7552 /* Non-type template parameters are OK. */
7554 else if (cxx_dialect >= cxx11 && integer_zerop (expr))
7555 /* Null pointer values are OK in C++11. */;
7556 else if (TREE_CODE (expr) != ADDR_EXPR
7557 && !INDIRECT_TYPE_P (expr_type))
7558 /* Other values, like integer constants, might be valid
7559 non-type arguments of some other type. */
7560 return error_mark_node;
7561 else if (invalid_tparm_referent_p (type, expr, complain))
7562 return NULL_TREE;
7564 expr = decayed;
7566 expr = perform_qualification_conversions (type, expr);
7567 if (expr == error_mark_node)
7568 return error_mark_node;
7570 /* [temp.arg.nontype]/5, bullet 3
7572 For a non-type template-parameter of type reference to object, no
7573 conversions apply. The type referred to by the reference may be more
7574 cv-qualified than the (otherwise identical) type of the
7575 template-argument. The template-parameter is bound directly to the
7576 template-argument, which must be an lvalue. */
7577 else if (TYPE_REF_OBJ_P (type))
7579 if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
7580 expr_type))
7581 return error_mark_node;
7583 if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
7585 if (complain & tf_error)
7586 error ("%qE is not a valid template argument for type %qT "
7587 "because of conflicts in cv-qualification", expr, type);
7588 return NULL_TREE;
7591 if (!lvalue_p (expr))
7593 if (complain & tf_error)
7594 error ("%qE is not a valid template argument for type %qT "
7595 "because it is not an lvalue", expr, type);
7596 return NULL_TREE;
7599 /* [temp.arg.nontype]/1
7601 A template-argument for a non-type, non-template template-parameter
7602 shall be one of: [...]
7604 -- the address of an object or function with external linkage. */
7605 if (INDIRECT_REF_P (expr)
7606 && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
7608 expr = TREE_OPERAND (expr, 0);
7609 if (DECL_P (expr))
7611 if (complain & tf_error)
7612 error ("%q#D is not a valid template argument for type %qT "
7613 "because a reference variable does not have a constant "
7614 "address", expr, type);
7615 return NULL_TREE;
7619 if (TYPE_REF_OBJ_P (TREE_TYPE (expr)) && val_dep_p)
7620 /* OK, dependent reference. We don't want to ask whether a DECL is
7621 itself value-dependent, since what we want here is its address. */;
7622 else
7624 expr = build_address (expr);
7626 if (invalid_tparm_referent_p (type, expr, complain))
7627 return NULL_TREE;
7630 if (!same_type_p (type, TREE_TYPE (expr)))
7631 expr = build_nop (type, expr);
7633 /* [temp.arg.nontype]/5, bullet 4
7635 For a non-type template-parameter of type pointer to function, only
7636 the function-to-pointer conversion (_conv.func_) is applied. If the
7637 template-argument represents a set of overloaded functions (or a
7638 pointer to such), the matching function is selected from the set
7639 (_over.over_). */
7640 else if (TYPE_PTRFN_P (type))
7642 /* If the argument is a template-id, we might not have enough
7643 context information to decay the pointer. */
7644 if (!type_unknown_p (expr_type))
7646 expr = decay_conversion (expr, complain);
7647 if (expr == error_mark_node)
7648 return error_mark_node;
7651 if (cxx_dialect >= cxx11 && integer_zerop (expr))
7652 /* Null pointer values are OK in C++11. */
7653 return perform_qualification_conversions (type, expr);
7655 expr = convert_nontype_argument_function (type, expr, complain);
7656 if (!expr || expr == error_mark_node)
7657 return expr;
7659 /* [temp.arg.nontype]/5, bullet 5
7661 For a non-type template-parameter of type reference to function, no
7662 conversions apply. If the template-argument represents a set of
7663 overloaded functions, the matching function is selected from the set
7664 (_over.over_). */
7665 else if (TYPE_REFFN_P (type))
7667 if (TREE_CODE (expr) == ADDR_EXPR)
7669 if (complain & tf_error)
7671 error ("%qE is not a valid template argument for type %qT "
7672 "because it is a pointer", expr, type);
7673 inform (input_location, "try using %qE instead",
7674 TREE_OPERAND (expr, 0));
7676 return NULL_TREE;
7679 expr = convert_nontype_argument_function (type, expr, complain);
7680 if (!expr || expr == error_mark_node)
7681 return expr;
7683 /* [temp.arg.nontype]/5, bullet 6
7685 For a non-type template-parameter of type pointer to member function,
7686 no conversions apply. If the template-argument represents a set of
7687 overloaded member functions, the matching member function is selected
7688 from the set (_over.over_). */
7689 else if (TYPE_PTRMEMFUNC_P (type))
7691 expr = instantiate_type (type, expr, tf_none);
7692 if (expr == error_mark_node)
7693 return error_mark_node;
7695 /* [temp.arg.nontype] bullet 1 says the pointer to member
7696 expression must be a pointer-to-member constant. */
7697 if (!val_dep_p
7698 && !check_valid_ptrmem_cst_expr (type, expr, complain))
7699 return NULL_TREE;
7701 /* Repeated conversion can't deal with a conversion that turns PTRMEM_CST
7702 into a CONSTRUCTOR, so build up a new PTRMEM_CST instead. */
7703 if (fnptr_conv_p (type, TREE_TYPE (expr)))
7704 expr = make_ptrmem_cst (type, PTRMEM_CST_MEMBER (expr));
7706 /* [temp.arg.nontype]/5, bullet 7
7708 For a non-type template-parameter of type pointer to data member,
7709 qualification conversions (_conv.qual_) are applied. */
7710 else if (TYPE_PTRDATAMEM_P (type))
7712 /* [temp.arg.nontype] bullet 1 says the pointer to member
7713 expression must be a pointer-to-member constant. */
7714 if (!val_dep_p
7715 && !check_valid_ptrmem_cst_expr (type, expr, complain))
7716 return NULL_TREE;
7718 expr = perform_qualification_conversions (type, expr);
7719 if (expr == error_mark_node)
7720 return expr;
7722 else if (NULLPTR_TYPE_P (type))
7724 if (!NULLPTR_TYPE_P (TREE_TYPE (expr)))
7726 if (complain & tf_error)
7727 error ("%qE is not a valid template argument for type %qT "
7728 "because it is of type %qT", expr, type, TREE_TYPE (expr));
7729 return NULL_TREE;
7731 return expr;
7733 else if (CLASS_TYPE_P (type))
7735 /* Replace the argument with a reference to the corresponding template
7736 parameter object. */
7737 if (!val_dep_p)
7738 expr = create_template_parm_object (expr, complain);
7739 if (expr == error_mark_node)
7740 return NULL_TREE;
7742 /* A template non-type parameter must be one of the above. */
7743 else
7744 gcc_unreachable ();
7746 /* Sanity check: did we actually convert the argument to the
7747 right type? */
7748 gcc_assert (same_type_ignoring_top_level_qualifiers_p
7749 (type, TREE_TYPE (expr)));
7750 return convert_from_reference (expr);
7753 /* Subroutine of coerce_template_template_parms, which returns 1 if
7754 PARM_PARM and ARG_PARM match using the rule for the template
7755 parameters of template template parameters. Both PARM and ARG are
7756 template parameters; the rest of the arguments are the same as for
7757 coerce_template_template_parms.
7759 static int
7760 coerce_template_template_parm (tree parm,
7761 tree arg,
7762 tsubst_flags_t complain,
7763 tree in_decl,
7764 tree outer_args)
7766 if (arg == NULL_TREE || error_operand_p (arg)
7767 || parm == NULL_TREE || error_operand_p (parm))
7768 return 0;
7770 if (TREE_CODE (arg) != TREE_CODE (parm))
7771 return 0;
7773 switch (TREE_CODE (parm))
7775 case TEMPLATE_DECL:
7776 /* We encounter instantiations of templates like
7777 template <template <template <class> class> class TT>
7778 class C; */
7780 if (!coerce_template_template_parms
7781 (parm, arg, complain, in_decl, outer_args))
7782 return 0;
7784 /* Fall through. */
7786 case TYPE_DECL:
7787 if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
7788 && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
7789 /* Argument is a parameter pack but parameter is not. */
7790 return 0;
7791 break;
7793 case PARM_DECL:
7794 /* The tsubst call is used to handle cases such as
7796 template <int> class C {};
7797 template <class T, template <T> class TT> class D {};
7798 D<int, C> d;
7800 i.e. the parameter list of TT depends on earlier parameters. */
7801 if (!uses_template_parms (TREE_TYPE (arg)))
7803 tree t = tsubst (TREE_TYPE (parm), outer_args, complain, in_decl);
7804 if (!uses_template_parms (t)
7805 && !same_type_p (t, TREE_TYPE (arg)))
7806 return 0;
7809 if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
7810 && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
7811 /* Argument is a parameter pack but parameter is not. */
7812 return 0;
7814 break;
7816 default:
7817 gcc_unreachable ();
7820 return 1;
7823 /* Coerce template argument list ARGLIST for use with template
7824 template-parameter TEMPL. */
7826 static tree
7827 coerce_template_args_for_ttp (tree templ, tree arglist,
7828 tsubst_flags_t complain)
7830 /* Consider an example where a template template parameter declared as
7832 template <class T, class U = std::allocator<T> > class TT
7834 The template parameter level of T and U are one level larger than
7835 of TT. To proper process the default argument of U, say when an
7836 instantiation `TT<int>' is seen, we need to build the full
7837 arguments containing {int} as the innermost level. Outer levels,
7838 available when not appearing as default template argument, can be
7839 obtained from the arguments of the enclosing template.
7841 Suppose that TT is later substituted with std::vector. The above
7842 instantiation is `TT<int, std::allocator<T> >' with TT at
7843 level 1, and T at level 2, while the template arguments at level 1
7844 becomes {std::vector} and the inner level 2 is {int}. */
7846 tree outer = DECL_CONTEXT (templ);
7847 if (outer)
7848 outer = generic_targs_for (outer);
7849 else if (current_template_parms)
7851 /* This is an argument of the current template, so we haven't set
7852 DECL_CONTEXT yet. We can also get here when level-lowering a
7853 bound ttp. */
7854 tree relevant_template_parms;
7856 /* Parameter levels that are greater than the level of the given
7857 template template parm are irrelevant. */
7858 relevant_template_parms = current_template_parms;
7859 while (TMPL_PARMS_DEPTH (relevant_template_parms)
7860 != TEMPLATE_TYPE_LEVEL (TREE_TYPE (templ)))
7861 relevant_template_parms = TREE_CHAIN (relevant_template_parms);
7863 outer = template_parms_to_args (relevant_template_parms);
7866 if (outer)
7867 arglist = add_to_template_args (outer, arglist);
7869 tree parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
7870 return coerce_template_parms (parmlist, arglist, templ, complain);
7873 /* A cache of template template parameters with match-all default
7874 arguments. */
7875 static GTY((deletable)) hash_map<tree,tree> *defaulted_ttp_cache;
7877 /* T is a bound template template-parameter. Copy its arguments into default
7878 arguments of the template template-parameter's template parameters. */
7880 static tree
7881 add_defaults_to_ttp (tree otmpl)
7883 if (tree *c = hash_map_safe_get (defaulted_ttp_cache, otmpl))
7884 return *c;
7886 tree ntmpl = copy_node (otmpl);
7888 tree ntype = copy_node (TREE_TYPE (otmpl));
7889 TYPE_STUB_DECL (ntype) = TYPE_NAME (ntype) = ntmpl;
7890 TYPE_MAIN_VARIANT (ntype) = ntype;
7891 TYPE_POINTER_TO (ntype) = TYPE_REFERENCE_TO (ntype) = NULL_TREE;
7892 TYPE_NAME (ntype) = ntmpl;
7893 SET_TYPE_STRUCTURAL_EQUALITY (ntype);
7895 tree idx = TEMPLATE_TYPE_PARM_INDEX (ntype)
7896 = copy_node (TEMPLATE_TYPE_PARM_INDEX (ntype));
7897 TEMPLATE_PARM_DECL (idx) = ntmpl;
7898 TREE_TYPE (ntmpl) = TREE_TYPE (idx) = ntype;
7900 tree oparms = DECL_TEMPLATE_PARMS (otmpl);
7901 tree parms = DECL_TEMPLATE_PARMS (ntmpl) = copy_node (oparms);
7902 TREE_CHAIN (parms) = TREE_CHAIN (oparms);
7903 tree vec = TREE_VALUE (parms) = copy_node (TREE_VALUE (parms));
7904 for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
7906 tree o = TREE_VEC_ELT (vec, i);
7907 if (!template_parameter_pack_p (TREE_VALUE (o)))
7909 tree n = TREE_VEC_ELT (vec, i) = copy_node (o);
7910 TREE_PURPOSE (n) = any_targ_node;
7914 tree oresult = DECL_TEMPLATE_RESULT (otmpl);
7915 tree gen_otmpl = DECL_TI_TEMPLATE (oresult);
7916 tree gen_ntmpl;
7917 if (gen_otmpl == otmpl)
7918 gen_ntmpl = ntmpl;
7919 else
7920 gen_ntmpl = add_defaults_to_ttp (gen_otmpl);
7922 tree nresult = copy_decl (oresult);
7923 DECL_TEMPLATE_INFO (nresult)
7924 = build_template_info (gen_ntmpl, TI_ARGS (DECL_TEMPLATE_INFO (oresult)));
7925 DECL_TEMPLATE_RESULT (ntmpl) = nresult;
7927 hash_map_safe_put<hm_ggc> (defaulted_ttp_cache, otmpl, ntmpl);
7928 return ntmpl;
7931 /* ARG is a bound potential template template-argument, and PARGS is a list
7932 of arguments for the corresponding template template-parameter. Adjust
7933 PARGS as appropriate for application to ARG's template, and if ARG is a
7934 BOUND_TEMPLATE_TEMPLATE_PARM, possibly adjust it to add default template
7935 arguments to the template template parameter. */
7937 static tree
7938 coerce_ttp_args_for_tta (tree& arg, tree pargs, tsubst_flags_t complain)
7940 ++processing_template_decl;
7941 tree arg_tmpl = TYPE_TI_TEMPLATE (arg);
7942 if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
7944 /* When comparing two template template-parameters in partial ordering,
7945 rewrite the one currently being used as an argument to have default
7946 arguments for all parameters. */
7947 arg_tmpl = add_defaults_to_ttp (arg_tmpl);
7948 pargs = coerce_template_args_for_ttp (arg_tmpl, pargs, complain);
7949 if (pargs != error_mark_node)
7950 arg = bind_template_template_parm (TREE_TYPE (arg_tmpl),
7951 TYPE_TI_ARGS (arg));
7953 else
7955 tree aparms
7956 = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (arg_tmpl));
7957 pargs = coerce_template_parms (aparms, pargs, arg_tmpl, complain);
7959 --processing_template_decl;
7960 return pargs;
7963 /* Subroutine of unify for the case when PARM is a
7964 BOUND_TEMPLATE_TEMPLATE_PARM. */
7966 static int
7967 unify_bound_ttp_args (tree tparms, tree targs, tree parm, tree& arg,
7968 bool explain_p)
7970 tree parmvec = TYPE_TI_ARGS (parm);
7971 tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
7973 /* The template template parm might be variadic and the argument
7974 not, so flatten both argument lists. */
7975 parmvec = expand_template_argument_pack (parmvec);
7976 argvec = expand_template_argument_pack (argvec);
7978 if (flag_new_ttp)
7980 /* In keeping with P0522R0, adjust P's template arguments
7981 to apply to A's template; then flatten it again. */
7982 tree nparmvec = coerce_ttp_args_for_tta (arg, parmvec, tf_none);
7983 nparmvec = expand_template_argument_pack (nparmvec);
7985 if (unify (tparms, targs, nparmvec, argvec,
7986 UNIFY_ALLOW_NONE, explain_p))
7987 return 1;
7989 /* If the P0522 adjustment eliminated a pack expansion, deduce
7990 empty packs. */
7991 if (flag_new_ttp
7992 && TREE_VEC_LENGTH (nparmvec) < TREE_VEC_LENGTH (parmvec)
7993 && unify_pack_expansion (tparms, targs, parmvec, argvec,
7994 DEDUCE_EXACT, /*sub*/true, explain_p))
7995 return 1;
7997 else
7999 /* Deduce arguments T, i from TT<T> or TT<i>.
8000 We check each element of PARMVEC and ARGVEC individually
8001 rather than the whole TREE_VEC since they can have
8002 different number of elements, which is allowed under N2555. */
8004 int len = TREE_VEC_LENGTH (parmvec);
8006 /* Check if the parameters end in a pack, making them
8007 variadic. */
8008 int parm_variadic_p = 0;
8009 if (len > 0
8010 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
8011 parm_variadic_p = 1;
8013 for (int i = 0; i < len - parm_variadic_p; ++i)
8014 /* If the template argument list of P contains a pack
8015 expansion that is not the last template argument, the
8016 entire template argument list is a non-deduced
8017 context. */
8018 if (PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, i)))
8019 return unify_success (explain_p);
8021 if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
8022 return unify_too_few_arguments (explain_p,
8023 TREE_VEC_LENGTH (argvec), len);
8025 for (int i = 0; i < len - parm_variadic_p; ++i)
8026 if (unify (tparms, targs,
8027 TREE_VEC_ELT (parmvec, i),
8028 TREE_VEC_ELT (argvec, i),
8029 UNIFY_ALLOW_NONE, explain_p))
8030 return 1;
8032 if (parm_variadic_p
8033 && unify_pack_expansion (tparms, targs,
8034 parmvec, argvec,
8035 DEDUCE_EXACT,
8036 /*subr=*/true, explain_p))
8037 return 1;
8040 return 0;
8043 /* Return 1 if PARM_TMPL and ARG_TMPL match using rule for
8044 template template parameters.
8046 Consider the example:
8047 template <class T> class A;
8048 template<template <class U> class TT> class B;
8050 For B<A>, PARM_TMPL is TT, while ARG_TMPL is A,
8051 and OUTER_ARGS contains A. */
8053 static int
8054 coerce_template_template_parms (tree parm_tmpl,
8055 tree arg_tmpl,
8056 tsubst_flags_t complain,
8057 tree in_decl,
8058 tree outer_args)
8060 int nparms, nargs, i;
8061 tree parm, arg;
8062 int variadic_p = 0;
8064 tree parm_parms = DECL_INNERMOST_TEMPLATE_PARMS (parm_tmpl);
8065 tree arg_parms = DECL_INNERMOST_TEMPLATE_PARMS (arg_tmpl);
8066 tree gen_arg_tmpl = most_general_template (arg_tmpl);
8067 tree gen_arg_parms = DECL_INNERMOST_TEMPLATE_PARMS (gen_arg_tmpl);
8069 nparms = TREE_VEC_LENGTH (parm_parms);
8070 nargs = TREE_VEC_LENGTH (arg_parms);
8072 if (flag_new_ttp)
8074 /* P0522R0: A template template-parameter P is at least as specialized as
8075 a template template-argument A if, given the following rewrite to two
8076 function templates, the function template corresponding to P is at
8077 least as specialized as the function template corresponding to A
8078 according to the partial ordering rules for function templates
8079 ([temp.func.order]). Given an invented class template X with the
8080 template parameter list of A (including default arguments):
8082 * Each of the two function templates has the same template parameters,
8083 respectively, as P or A.
8085 * Each function template has a single function parameter whose type is
8086 a specialization of X with template arguments corresponding to the
8087 template parameters from the respective function template where, for
8088 each template parameter PP in the template parameter list of the
8089 function template, a corresponding template argument AA is formed. If
8090 PP declares a parameter pack, then AA is the pack expansion
8091 PP... ([temp.variadic]); otherwise, AA is the id-expression PP.
8093 If the rewrite produces an invalid type, then P is not at least as
8094 specialized as A. */
8096 /* So coerce P's args to apply to A's parms, and then deduce between A's
8097 args and the converted args. If that succeeds, A is at least as
8098 specialized as P, so they match.*/
8099 processing_template_decl_sentinel ptds (/*reset*/false);
8100 ++processing_template_decl;
8102 tree pargs = template_parms_level_to_args (parm_parms);
8104 /* PARM and ARG might be at different template depths, and we want to
8105 pass the right additional levels of args when coercing PARGS to
8106 ARG_PARMS in case we need to do any substitution into non-type
8107 template parameter types.
8109 OUTER_ARGS are not the right outer levels in this case, as they are
8110 the args we're building up for PARM, and for the coercion we want the
8111 args for ARG. If DECL_CONTEXT isn't set for a template template
8112 parameter, we can assume that it's in the current scope. */
8113 tree ctx = DECL_CONTEXT (arg_tmpl);
8114 if (!ctx && DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
8115 ctx = current_scope ();
8116 tree scope_args = NULL_TREE;
8117 if (tree tinfo = get_template_info (ctx))
8118 scope_args = TI_ARGS (tinfo);
8119 if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
8121 int level = TEMPLATE_TYPE_LEVEL (TREE_TYPE (gen_arg_tmpl));
8122 int scope_depth = TMPL_ARGS_DEPTH (scope_args);
8123 tree full_pargs = make_tree_vec (level + 1);
8125 /* Only use as many levels from the scope as needed
8126 (excluding the level of ARG). */
8127 for (int i = 0; i < level - 1; ++i)
8128 if (i < scope_depth)
8129 TREE_VEC_ELT (full_pargs, i) = TMPL_ARGS_LEVEL (scope_args, i + 1);
8130 else
8131 TREE_VEC_ELT (full_pargs, i) = make_tree_vec (0);
8133 /* Add the arguments that appear at the levels of ARG. */
8134 tree adjacent = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (arg_tmpl));
8135 adjacent = TMPL_ARGS_LEVEL (adjacent, TMPL_ARGS_DEPTH (adjacent) - 1);
8136 TREE_VEC_ELT (full_pargs, level - 1) = adjacent;
8138 TREE_VEC_ELT (full_pargs, level) = pargs;
8139 pargs = full_pargs;
8141 else
8142 pargs = add_to_template_args (scope_args, pargs);
8144 pargs = coerce_template_parms (gen_arg_parms, pargs,
8145 NULL_TREE, tf_none);
8146 if (pargs != error_mark_node)
8148 tree targs = make_tree_vec (nargs);
8149 tree aargs = template_parms_level_to_args (arg_parms);
8150 if (!unify (arg_parms, targs, aargs, pargs, UNIFY_ALLOW_NONE,
8151 /*explain*/false))
8152 return 1;
8156 /* Determine whether we have a parameter pack at the end of the
8157 template template parameter's template parameter list. */
8158 if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
8160 parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
8162 if (error_operand_p (parm))
8163 return 0;
8165 switch (TREE_CODE (parm))
8167 case TEMPLATE_DECL:
8168 case TYPE_DECL:
8169 if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
8170 variadic_p = 1;
8171 break;
8173 case PARM_DECL:
8174 if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
8175 variadic_p = 1;
8176 break;
8178 default:
8179 gcc_unreachable ();
8183 if (nargs != nparms
8184 && !(variadic_p && nargs >= nparms - 1))
8185 return 0;
8187 /* Check all of the template parameters except the parameter pack at
8188 the end (if any). */
8189 for (i = 0; i < nparms - variadic_p; ++i)
8191 if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
8192 || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
8193 continue;
8195 parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
8196 arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
8198 if (!coerce_template_template_parm (parm, arg, complain, in_decl,
8199 outer_args))
8200 return 0;
8204 if (variadic_p)
8206 /* Check each of the template parameters in the template
8207 argument against the template parameter pack at the end of
8208 the template template parameter. */
8209 if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
8210 return 0;
8212 parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
8214 for (; i < nargs; ++i)
8216 if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
8217 continue;
8219 arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
8221 if (!coerce_template_template_parm (parm, arg, complain, in_decl,
8222 outer_args))
8223 return 0;
8227 return 1;
8230 /* Verifies that the deduced template arguments (in TARGS) for the
8231 template template parameters (in TPARMS) represent valid bindings,
8232 by comparing the template parameter list of each template argument
8233 to the template parameter list of its corresponding template
8234 template parameter, in accordance with DR150. This
8235 routine can only be called after all template arguments have been
8236 deduced. It will return TRUE if all of the template template
8237 parameter bindings are okay, FALSE otherwise. */
8238 bool
8239 template_template_parm_bindings_ok_p (tree tparms, tree targs)
8241 int i, ntparms = TREE_VEC_LENGTH (tparms);
8242 bool ret = true;
8244 /* We're dealing with template parms in this process. */
8245 ++processing_template_decl;
8247 targs = INNERMOST_TEMPLATE_ARGS (targs);
8249 for (i = 0; i < ntparms; ++i)
8251 tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
8252 tree targ = TREE_VEC_ELT (targs, i);
8254 if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
8256 tree packed_args = NULL_TREE;
8257 int idx, len = 1;
8259 if (ARGUMENT_PACK_P (targ))
8261 /* Look inside the argument pack. */
8262 packed_args = ARGUMENT_PACK_ARGS (targ);
8263 len = TREE_VEC_LENGTH (packed_args);
8266 for (idx = 0; idx < len; ++idx)
8268 if (packed_args)
8269 /* Extract the next argument from the argument
8270 pack. */
8271 targ = TREE_VEC_ELT (packed_args, idx);
8273 if (PACK_EXPANSION_P (targ))
8274 /* Look at the pattern of the pack expansion. */
8275 targ = PACK_EXPANSION_PATTERN (targ);
8277 /* Extract the template parameters from the template
8278 argument. */
8279 if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
8280 targ = TYPE_NAME (targ);
8282 /* Verify that we can coerce the template template
8283 parameters from the template argument to the template
8284 parameter. This requires an exact match. */
8285 if (TREE_CODE (targ) == TEMPLATE_DECL
8286 && !coerce_template_template_parms
8287 (tparm,
8288 targ,
8289 tf_none,
8290 tparm,
8291 targs))
8293 ret = false;
8294 goto out;
8300 out:
8302 --processing_template_decl;
8303 return ret;
8306 /* Since type attributes aren't mangled, we need to strip them from
8307 template type arguments. */
8309 tree
8310 canonicalize_type_argument (tree arg, tsubst_flags_t complain)
8312 if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
8313 return arg;
8314 bool removed_attributes = false;
8315 tree canon = strip_typedefs (arg, &removed_attributes);
8316 if (removed_attributes
8317 && (complain & tf_warning))
8318 warning (OPT_Wignored_attributes,
8319 "ignoring attributes on template argument %qT", arg);
8320 return canon;
8323 /* And from inside dependent non-type arguments like sizeof(Type). */
8325 static tree
8326 canonicalize_expr_argument (tree arg, tsubst_flags_t complain)
8328 if (!arg || arg == error_mark_node)
8329 return arg;
8330 bool removed_attributes = false;
8331 tree canon = strip_typedefs_expr (arg, &removed_attributes);
8332 if (removed_attributes
8333 && (complain & tf_warning))
8334 warning (OPT_Wignored_attributes,
8335 "ignoring attributes in template argument %qE", arg);
8336 return canon;
8339 /* A template declaration can be substituted for a constrained
8340 template template parameter only when the argument is no more
8341 constrained than the parameter. */
8343 static bool
8344 is_compatible_template_arg (tree parm, tree arg, tree args)
8346 tree parm_cons = get_constraints (parm);
8348 /* For now, allow constrained template template arguments
8349 and unconstrained template template parameters. */
8350 if (parm_cons == NULL_TREE)
8351 return true;
8353 /* If the template parameter is constrained, we need to rewrite its
8354 constraints in terms of the ARG's template parameters. This ensures
8355 that all of the template parameter types will have the same depth.
8357 Note that this is only valid when coerce_template_template_parm is
8358 true for the innermost template parameters of PARM and ARG. In other
8359 words, because coercion is successful, this conversion will be valid. */
8360 tree new_args = NULL_TREE;
8361 if (parm_cons)
8363 tree aparms = DECL_INNERMOST_TEMPLATE_PARMS (arg);
8364 new_args = template_parms_level_to_args (aparms);
8365 new_args = add_to_template_args (args, new_args);
8366 ++processing_template_decl;
8367 parm_cons = tsubst_constraint_info (parm_cons, new_args,
8368 tf_none, NULL_TREE);
8369 --processing_template_decl;
8370 if (parm_cons == error_mark_node)
8371 return false;
8374 return weakly_subsumes (parm_cons, arg);
8377 // Convert a placeholder argument into a binding to the original
8378 // parameter. The original parameter is saved as the TREE_TYPE of
8379 // ARG.
8380 static inline tree
8381 convert_wildcard_argument (tree parm, tree arg)
8383 TREE_TYPE (arg) = parm;
8384 return arg;
8387 /* We can't fully resolve ARG given as a non-type template argument to TYPE,
8388 because one of them is dependent. But we need to represent the
8389 conversion for the benefit of cp_tree_equal. */
8391 static tree
8392 maybe_convert_nontype_argument (tree type, tree arg)
8394 /* Auto parms get no conversion. */
8395 if (type_uses_auto (type))
8396 return arg;
8397 /* We don't need or want to add this conversion now if we're going to use the
8398 argument for deduction. */
8399 if (value_dependent_expression_p (arg))
8400 return arg;
8402 type = cv_unqualified (type);
8403 tree argtype = TREE_TYPE (arg);
8404 if (same_type_p (type, argtype))
8405 return arg;
8407 arg = build1 (IMPLICIT_CONV_EXPR, type, arg);
8408 IMPLICIT_CONV_EXPR_NONTYPE_ARG (arg) = true;
8409 return arg;
8412 /* Convert the indicated template ARG as necessary to match the
8413 indicated template PARM. Returns the converted ARG, or
8414 error_mark_node if the conversion was unsuccessful. Error and
8415 warning messages are issued under control of COMPLAIN. This
8416 conversion is for the Ith parameter in the parameter list. ARGS is
8417 the full set of template arguments deduced so far. */
8419 static tree
8420 convert_template_argument (tree parm,
8421 tree arg,
8422 tree args,
8423 tsubst_flags_t complain,
8424 int i,
8425 tree in_decl)
8427 tree orig_arg;
8428 tree val;
8429 int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
8431 if (parm == error_mark_node || error_operand_p (arg))
8432 return error_mark_node;
8434 /* Trivially convert placeholders. */
8435 if (TREE_CODE (arg) == WILDCARD_DECL)
8436 return convert_wildcard_argument (parm, arg);
8438 if (arg == any_targ_node)
8439 return arg;
8441 if (TREE_CODE (arg) == TREE_LIST
8442 && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
8444 /* The template argument was the name of some
8445 member function. That's usually
8446 invalid, but static members are OK. In any
8447 case, grab the underlying fields/functions
8448 and issue an error later if required. */
8449 TREE_TYPE (arg) = unknown_type_node;
8452 orig_arg = arg;
8454 requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
8455 requires_type = (TREE_CODE (parm) == TYPE_DECL
8456 || requires_tmpl_type);
8458 /* When determining whether an argument pack expansion is a template,
8459 look at the pattern. */
8460 if (PACK_EXPANSION_P (arg))
8461 arg = PACK_EXPANSION_PATTERN (arg);
8463 /* Deal with an injected-class-name used as a template template arg. */
8464 if (requires_tmpl_type && CLASS_TYPE_P (arg))
8466 tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
8467 if (TREE_CODE (t) == TEMPLATE_DECL)
8469 if (cxx_dialect >= cxx11)
8470 /* OK under DR 1004. */;
8471 else if (complain & tf_warning_or_error)
8472 pedwarn (input_location, OPT_Wpedantic, "injected-class-name %qD"
8473 " used as template template argument", TYPE_NAME (arg));
8474 else if (flag_pedantic_errors)
8475 t = arg;
8477 arg = t;
8481 is_tmpl_type =
8482 ((TREE_CODE (arg) == TEMPLATE_DECL
8483 && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
8484 || (requires_tmpl_type && TREE_CODE (arg) == TYPE_ARGUMENT_PACK)
8485 || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
8486 || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
8488 if (is_tmpl_type
8489 && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
8490 || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
8491 arg = TYPE_STUB_DECL (arg);
8493 is_type = TYPE_P (arg) || is_tmpl_type;
8495 if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
8496 && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
8498 if (TREE_CODE (TREE_OPERAND (arg, 1)) == BIT_NOT_EXPR)
8500 if (complain & tf_error)
8501 error ("invalid use of destructor %qE as a type", orig_arg);
8502 return error_mark_node;
8505 permerror (input_location,
8506 "to refer to a type member of a template parameter, "
8507 "use %<typename %E%>", orig_arg);
8509 orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
8510 TREE_OPERAND (arg, 1),
8511 typename_type,
8512 complain);
8513 arg = orig_arg;
8514 is_type = 1;
8516 if (is_type != requires_type)
8518 if (in_decl)
8520 if (complain & tf_error)
8522 error ("type/value mismatch at argument %d in template "
8523 "parameter list for %qD",
8524 i + 1, in_decl);
8525 if (is_type)
8527 /* The template argument is a type, but we're expecting
8528 an expression. */
8529 inform (input_location,
8530 " expected a constant of type %qT, got %qT",
8531 TREE_TYPE (parm),
8532 (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
8533 /* [temp.arg]/2: "In a template-argument, an ambiguity
8534 between a type-id and an expression is resolved to a
8535 type-id, regardless of the form of the corresponding
8536 template-parameter." So give the user a clue. */
8537 if (TREE_CODE (arg) == FUNCTION_TYPE)
8538 inform (input_location, " ambiguous template argument "
8539 "for non-type template parameter is treated as "
8540 "function type");
8542 else if (requires_tmpl_type)
8543 inform (input_location,
8544 " expected a class template, got %qE", orig_arg);
8545 else
8546 inform (input_location,
8547 " expected a type, got %qE", orig_arg);
8550 return error_mark_node;
8552 if (is_tmpl_type ^ requires_tmpl_type)
8554 if (in_decl && (complain & tf_error))
8556 error ("type/value mismatch at argument %d in template "
8557 "parameter list for %qD",
8558 i + 1, in_decl);
8559 if (is_tmpl_type)
8560 inform (input_location,
8561 " expected a type, got %qT", DECL_NAME (arg));
8562 else
8563 inform (input_location,
8564 " expected a class template, got %qT", orig_arg);
8566 return error_mark_node;
8569 if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
8570 /* We already did the appropriate conversion when packing args. */
8571 val = orig_arg;
8572 else if (is_type)
8574 if (requires_tmpl_type)
8576 if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
8577 /* The number of argument required is not known yet.
8578 Just accept it for now. */
8579 val = orig_arg;
8580 else
8582 /* Strip alias templates that are equivalent to another
8583 template. */
8584 arg = get_underlying_template (arg);
8586 if (coerce_template_template_parms (parm, arg,
8587 complain, in_decl,
8588 args))
8590 val = arg;
8592 /* TEMPLATE_TEMPLATE_PARM node is preferred over
8593 TEMPLATE_DECL. */
8594 if (val != error_mark_node)
8596 if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
8597 val = TREE_TYPE (val);
8598 if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
8599 val = make_pack_expansion (val, complain);
8602 else
8604 if (in_decl && (complain & tf_error))
8606 error ("type/value mismatch at argument %d in "
8607 "template parameter list for %qD",
8608 i + 1, in_decl);
8609 inform (input_location,
8610 " expected a template of type %qD, got %qT",
8611 parm, orig_arg);
8614 val = error_mark_node;
8617 // Check that the constraints are compatible before allowing the
8618 // substitution.
8619 if (val != error_mark_node)
8620 if (!is_compatible_template_arg (parm, arg, args))
8622 if (in_decl && (complain & tf_error))
8624 error ("constraint mismatch at argument %d in "
8625 "template parameter list for %qD",
8626 i + 1, in_decl);
8627 inform (input_location, " expected %qD but got %qD",
8628 parm, arg);
8630 val = error_mark_node;
8634 else
8635 val = orig_arg;
8636 /* We only form one instance of each template specialization.
8637 Therefore, if we use a non-canonical variant (i.e., a
8638 typedef), any future messages referring to the type will use
8639 the typedef, which is confusing if those future uses do not
8640 themselves also use the typedef. */
8641 if (TYPE_P (val))
8642 val = canonicalize_type_argument (val, complain);
8644 else
8646 tree t = TREE_TYPE (parm);
8648 if (TEMPLATE_PARM_LEVEL (get_template_parm_index (parm))
8649 > TMPL_ARGS_DEPTH (args))
8650 /* We don't have enough levels of args to do any substitution. This
8651 can happen in the context of -fnew-ttp-matching. */;
8652 else if (tree a = type_uses_auto (t))
8654 t = do_auto_deduction (t, arg, a, complain, adc_unify, args,
8655 LOOKUP_IMPLICIT, /*tmpl=*/in_decl);
8656 if (t == error_mark_node)
8657 return error_mark_node;
8659 else
8660 t = tsubst (t, args, complain, in_decl);
8662 /* Perform array-to-pointer and function-to-pointer conversion
8663 as per [temp.param]/10. */
8664 t = type_decays_to (t);
8666 if (invalid_nontype_parm_type_p (t, complain))
8667 return error_mark_node;
8669 /* Drop top-level cv-qualifiers on the substituted/deduced type of
8670 this non-type template parameter, as per [temp.param]/6. */
8671 t = cv_unqualified (t);
8673 if (t != TREE_TYPE (parm))
8674 t = canonicalize_type_argument (t, complain);
8676 if (!type_dependent_expression_p (orig_arg)
8677 && !uses_template_parms (t))
8678 /* We used to call digest_init here. However, digest_init
8679 will report errors, which we don't want when complain
8680 is zero. More importantly, digest_init will try too
8681 hard to convert things: for example, `0' should not be
8682 converted to pointer type at this point according to
8683 the standard. Accepting this is not merely an
8684 extension, since deciding whether or not these
8685 conversions can occur is part of determining which
8686 function template to call, or whether a given explicit
8687 argument specification is valid. */
8688 val = convert_nontype_argument (t, orig_arg, complain);
8689 else
8691 val = canonicalize_expr_argument (orig_arg, complain);
8692 val = maybe_convert_nontype_argument (t, val);
8696 if (val == NULL_TREE)
8697 val = error_mark_node;
8698 else if (val == error_mark_node && (complain & tf_error))
8699 error_at (cp_expr_loc_or_input_loc (orig_arg),
8700 "could not convert template argument %qE from %qT to %qT",
8701 orig_arg, TREE_TYPE (orig_arg), t);
8703 if (INDIRECT_REF_P (val))
8705 /* Reject template arguments that are references to built-in
8706 functions with no library fallbacks. */
8707 const_tree inner = TREE_OPERAND (val, 0);
8708 const_tree innertype = TREE_TYPE (inner);
8709 if (innertype
8710 && TYPE_REF_P (innertype)
8711 && TREE_CODE (TREE_TYPE (innertype)) == FUNCTION_TYPE
8712 && TREE_OPERAND_LENGTH (inner) > 0
8713 && reject_gcc_builtin (TREE_OPERAND (inner, 0)))
8714 return error_mark_node;
8717 if (TREE_CODE (val) == SCOPE_REF)
8719 /* Strip typedefs from the SCOPE_REF. */
8720 tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
8721 tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
8722 complain);
8723 val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
8724 QUALIFIED_NAME_IS_TEMPLATE (val));
8728 return val;
8731 /* Coerces the remaining template arguments in INNER_ARGS (from
8732 ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
8733 Returns the coerced argument pack. PARM_IDX is the position of this
8734 parameter in the template parameter list. ARGS is the original
8735 template argument list. */
8736 static tree
8737 coerce_template_parameter_pack (tree parms,
8738 int parm_idx,
8739 tree args,
8740 tree inner_args,
8741 int arg_idx,
8742 tree new_args,
8743 int* lost,
8744 tree in_decl,
8745 tsubst_flags_t complain)
8747 tree parm = TREE_VEC_ELT (parms, parm_idx);
8748 int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8749 tree packed_args;
8750 tree argument_pack;
8751 tree packed_parms = NULL_TREE;
8753 if (arg_idx > nargs)
8754 arg_idx = nargs;
8756 if (tree packs = fixed_parameter_pack_p (TREE_VALUE (parm)))
8758 /* When the template parameter is a non-type template parameter pack
8759 or template template parameter pack whose type or template
8760 parameters use parameter packs, we know exactly how many arguments
8761 we are looking for. Build a vector of the instantiated decls for
8762 these template parameters in PACKED_PARMS. */
8763 /* We can't use make_pack_expansion here because it would interpret a
8764 _DECL as a use rather than a declaration. */
8765 tree decl = TREE_VALUE (parm);
8766 tree exp = cxx_make_type (TYPE_PACK_EXPANSION);
8767 PACK_EXPANSION_PATTERN (exp) = decl;
8768 PACK_EXPANSION_PARAMETER_PACKS (exp) = packs;
8769 SET_TYPE_STRUCTURAL_EQUALITY (exp);
8771 TREE_VEC_LENGTH (args)--;
8772 packed_parms = tsubst_pack_expansion (exp, args, complain, decl);
8773 TREE_VEC_LENGTH (args)++;
8775 if (packed_parms == error_mark_node)
8776 return error_mark_node;
8778 /* If we're doing a partial instantiation of a member template,
8779 verify that all of the types used for the non-type
8780 template parameter pack are, in fact, valid for non-type
8781 template parameters. */
8782 if (arg_idx < nargs
8783 && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
8785 int j, len = TREE_VEC_LENGTH (packed_parms);
8786 for (j = 0; j < len; ++j)
8788 tree t = TREE_VEC_ELT (packed_parms, j);
8789 if (TREE_CODE (t) == PARM_DECL
8790 && invalid_nontype_parm_type_p (TREE_TYPE (t), complain))
8791 return error_mark_node;
8793 /* We don't know how many args we have yet, just
8794 use the unconverted ones for now. */
8795 return NULL_TREE;
8798 packed_args = make_tree_vec (TREE_VEC_LENGTH (packed_parms));
8800 /* Check if we have a placeholder pack, which indicates we're
8801 in the context of a introduction list. In that case we want
8802 to match this pack to the single placeholder. */
8803 else if (arg_idx < nargs
8804 && TREE_CODE (TREE_VEC_ELT (inner_args, arg_idx)) == WILDCARD_DECL
8805 && WILDCARD_PACK_P (TREE_VEC_ELT (inner_args, arg_idx)))
8807 nargs = arg_idx + 1;
8808 packed_args = make_tree_vec (1);
8810 else
8811 packed_args = make_tree_vec (nargs - arg_idx);
8813 /* Convert the remaining arguments, which will be a part of the
8814 parameter pack "parm". */
8815 int first_pack_arg = arg_idx;
8816 for (; arg_idx < nargs; ++arg_idx)
8818 tree arg = TREE_VEC_ELT (inner_args, arg_idx);
8819 tree actual_parm = TREE_VALUE (parm);
8820 int pack_idx = arg_idx - first_pack_arg;
8822 if (packed_parms)
8824 /* Once we've packed as many args as we have types, stop. */
8825 if (pack_idx >= TREE_VEC_LENGTH (packed_parms))
8826 break;
8827 else if (PACK_EXPANSION_P (arg))
8828 /* We don't know how many args we have yet, just
8829 use the unconverted ones for now. */
8830 return NULL_TREE;
8831 else
8832 actual_parm = TREE_VEC_ELT (packed_parms, pack_idx);
8835 if (arg == error_mark_node)
8837 if (complain & tf_error)
8838 error ("template argument %d is invalid", arg_idx + 1);
8840 else
8841 arg = convert_template_argument (actual_parm,
8842 arg, new_args, complain, parm_idx,
8843 in_decl);
8844 if (arg == error_mark_node)
8845 (*lost)++;
8846 TREE_VEC_ELT (packed_args, pack_idx) = arg;
8849 if (arg_idx - first_pack_arg < TREE_VEC_LENGTH (packed_args)
8850 && TREE_VEC_LENGTH (packed_args) > 0)
8852 if (complain & tf_error)
8853 error ("wrong number of template arguments (%d, should be %d)",
8854 arg_idx - first_pack_arg, TREE_VEC_LENGTH (packed_args));
8855 return error_mark_node;
8858 if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
8859 || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
8860 argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
8861 else
8863 argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
8864 TREE_CONSTANT (argument_pack) = 1;
8867 ARGUMENT_PACK_ARGS (argument_pack) = packed_args;
8868 if (CHECKING_P)
8869 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
8870 TREE_VEC_LENGTH (packed_args));
8871 return argument_pack;
8874 /* Returns the number of pack expansions in the template argument vector
8875 ARGS. */
8877 static int
8878 pack_expansion_args_count (tree args)
8880 int i;
8881 int count = 0;
8882 if (args)
8883 for (i = 0; i < TREE_VEC_LENGTH (args); ++i)
8885 tree elt = TREE_VEC_ELT (args, i);
8886 if (elt && PACK_EXPANSION_P (elt))
8887 ++count;
8889 return count;
8892 /* Convert all template arguments to their appropriate types, and
8893 return a vector containing the innermost resulting template
8894 arguments. If any error occurs, return error_mark_node. Error and
8895 warning messages are issued under control of COMPLAIN.
8897 If PARMS represents all template parameters levels, this function
8898 returns a vector of vectors representing all the resulting argument
8899 levels. Note that in this case, only the innermost arguments are
8900 coerced because the outermost ones are supposed to have been coerced
8901 already. Otherwise, if PARMS represents only (the innermost) vector
8902 of parameters, this function returns a vector containing just the
8903 innermost resulting arguments.
8905 If REQUIRE_ALL_ARGS is false, argument deduction will be performed
8906 for arguments not specified in ARGS. If REQUIRE_ALL_ARGS is true,
8907 arguments not specified in ARGS must have default arguments which
8908 we'll use to fill in ARGS. */
8910 tree
8911 coerce_template_parms (tree parms,
8912 tree args,
8913 tree in_decl,
8914 tsubst_flags_t complain,
8915 bool require_all_args /* = true */)
8917 int nparms, nargs, parm_idx, arg_idx, lost = 0;
8918 tree orig_inner_args;
8919 tree inner_args;
8921 /* When used as a boolean value, indicates whether this is a
8922 variadic template parameter list. Since it's an int, we can also
8923 subtract it from nparms to get the number of non-variadic
8924 parameters. */
8925 int variadic_p = 0;
8926 int variadic_args_p = 0;
8927 int post_variadic_parms = 0;
8929 /* Adjustment to nparms for fixed parameter packs. */
8930 int fixed_pack_adjust = 0;
8931 int fixed_packs = 0;
8932 int missing = 0;
8934 /* Likewise for parameters with default arguments. */
8935 int default_p = 0;
8937 if (args == error_mark_node)
8938 return error_mark_node;
8940 bool return_full_args = false;
8941 if (TREE_CODE (parms) == TREE_LIST)
8943 if (TMPL_PARMS_DEPTH (parms) > 1)
8945 gcc_assert (TMPL_PARMS_DEPTH (parms) == TMPL_ARGS_DEPTH (args));
8946 return_full_args = true;
8948 parms = INNERMOST_TEMPLATE_PARMS (parms);
8951 nparms = TREE_VEC_LENGTH (parms);
8953 /* Determine if there are any parameter packs or default arguments. */
8954 for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
8956 tree parm = TREE_VEC_ELT (parms, parm_idx);
8957 if (variadic_p)
8958 ++post_variadic_parms;
8959 if (template_parameter_pack_p (TREE_VALUE (parm)))
8960 ++variadic_p;
8961 if (TREE_PURPOSE (parm))
8962 ++default_p;
8965 inner_args = orig_inner_args = INNERMOST_TEMPLATE_ARGS (args);
8966 /* If there are no parameters that follow a parameter pack, we need to
8967 expand any argument packs so that we can deduce a parameter pack from
8968 some non-packed args followed by an argument pack, as in variadic85.C.
8969 If there are such parameters, we need to leave argument packs intact
8970 so the arguments are assigned properly. This can happen when dealing
8971 with a nested class inside a partial specialization of a class
8972 template, as in variadic92.C, or when deducing a template parameter pack
8973 from a sub-declarator, as in variadic114.C. */
8974 if (!post_variadic_parms)
8975 inner_args = expand_template_argument_pack (inner_args);
8977 /* Count any pack expansion args. */
8978 variadic_args_p = pack_expansion_args_count (inner_args);
8980 nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8981 if ((nargs - variadic_args_p > nparms && !variadic_p)
8982 || (nargs < nparms - variadic_p
8983 && require_all_args
8984 && !variadic_args_p
8985 && (TREE_VEC_ELT (parms, nargs) != error_mark_node
8986 && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs)))))
8988 bad_nargs:
8989 if (complain & tf_error)
8991 if (variadic_p || default_p)
8993 nparms -= variadic_p + default_p;
8994 error ("wrong number of template arguments "
8995 "(%d, should be at least %d)", nargs, nparms);
8997 else
8998 error ("wrong number of template arguments "
8999 "(%d, should be %d)", nargs, nparms);
9001 if (in_decl)
9002 inform (DECL_SOURCE_LOCATION (in_decl),
9003 "provided for %qD", in_decl);
9006 return error_mark_node;
9008 /* We can't pass a pack expansion to a non-pack parameter of an alias
9009 template (DR 1430). */
9010 else if (in_decl
9011 && (DECL_ALIAS_TEMPLATE_P (in_decl)
9012 || concept_definition_p (in_decl))
9013 && variadic_args_p
9014 && nargs - variadic_args_p < nparms - variadic_p)
9016 if (complain & tf_error)
9018 for (int i = 0; i < TREE_VEC_LENGTH (inner_args); ++i)
9020 tree arg = TREE_VEC_ELT (inner_args, i);
9021 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
9023 if (PACK_EXPANSION_P (arg)
9024 && !template_parameter_pack_p (parm))
9026 if (DECL_ALIAS_TEMPLATE_P (in_decl))
9027 error_at (location_of (arg),
9028 "pack expansion argument for non-pack parameter "
9029 "%qD of alias template %qD", parm, in_decl);
9030 else
9031 error_at (location_of (arg),
9032 "pack expansion argument for non-pack parameter "
9033 "%qD of concept %qD", parm, in_decl);
9034 inform (DECL_SOURCE_LOCATION (parm), "declared here");
9035 goto found;
9038 gcc_unreachable ();
9039 found:;
9041 return error_mark_node;
9044 /* We need to evaluate the template arguments, even though this
9045 template-id may be nested within a "sizeof". */
9046 cp_evaluated ev;
9048 tree new_args = add_outermost_template_args (args, make_tree_vec (nparms));
9049 tree& new_inner_args = TMPL_ARGS_LEVEL (new_args, TMPL_ARGS_DEPTH (new_args));
9050 int pack_adjust = 0;
9051 for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
9053 tree arg;
9054 tree parm;
9056 /* Get the Ith template parameter. */
9057 parm = TREE_VEC_ELT (parms, parm_idx);
9059 if (parm == error_mark_node)
9061 TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
9062 continue;
9065 /* Calculate the next argument. */
9066 if (arg_idx < nargs)
9067 arg = TREE_VEC_ELT (inner_args, arg_idx);
9068 else
9069 arg = NULL_TREE;
9071 if (template_parameter_pack_p (TREE_VALUE (parm))
9072 && (arg || require_all_args || !(complain & tf_partial))
9073 && !(arg && ARGUMENT_PACK_P (arg)))
9075 /* Some arguments will be placed in the
9076 template parameter pack PARM. */
9077 arg = coerce_template_parameter_pack (parms, parm_idx, args,
9078 inner_args, arg_idx,
9079 new_args, &lost,
9080 in_decl, complain);
9082 if (arg == NULL_TREE)
9084 /* We don't know how many args we have yet, just use the
9085 unconverted (and still packed) ones for now. */
9086 new_inner_args = orig_inner_args;
9087 arg_idx = nargs;
9088 break;
9091 TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
9093 /* Store this argument. */
9094 if (arg == error_mark_node)
9096 lost++;
9097 /* We are done with all of the arguments. */
9098 arg_idx = nargs;
9099 break;
9101 else
9103 pack_adjust = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg)) - 1;
9104 arg_idx += pack_adjust;
9105 if (fixed_parameter_pack_p (TREE_VALUE (parm)))
9107 ++fixed_packs;
9108 fixed_pack_adjust += pack_adjust;
9112 continue;
9114 else if (arg)
9116 if (PACK_EXPANSION_P (arg))
9118 /* "If every valid specialization of a variadic template
9119 requires an empty template parameter pack, the template is
9120 ill-formed, no diagnostic required." So check that the
9121 pattern works with this parameter. */
9122 tree pattern = PACK_EXPANSION_PATTERN (arg);
9123 tree conv = convert_template_argument (TREE_VALUE (parm),
9124 pattern, new_args,
9125 complain, parm_idx,
9126 in_decl);
9127 if (conv == error_mark_node)
9129 if (complain & tf_error)
9130 inform (input_location, "so any instantiation with a "
9131 "non-empty parameter pack would be ill-formed");
9132 ++lost;
9134 else if (TYPE_P (conv) && !TYPE_P (pattern))
9135 /* Recover from missing typename. */
9136 TREE_VEC_ELT (inner_args, arg_idx)
9137 = make_pack_expansion (conv, complain);
9139 /* We don't know how many args we have yet, just
9140 use the unconverted ones for now. */
9141 new_inner_args = inner_args;
9142 arg_idx = nargs;
9143 break;
9146 else if (require_all_args)
9148 /* There must be a default arg in this case. */
9149 arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
9150 complain, in_decl);
9151 /* The position of the first default template argument,
9152 is also the number of non-defaulted arguments in NEW_INNER_ARGS.
9153 Record that. */
9154 if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
9155 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
9156 arg_idx - pack_adjust);
9158 else
9159 break;
9161 if (arg == error_mark_node)
9163 if (complain & tf_error)
9164 error ("template argument %d is invalid", arg_idx + 1);
9166 else if (!arg)
9168 /* This can occur if there was an error in the template
9169 parameter list itself (which we would already have
9170 reported) that we are trying to recover from, e.g., a class
9171 template with a parameter list such as
9172 template<typename..., typename> (cpp0x/variadic150.C). */
9173 ++lost;
9175 /* This can also happen with a fixed parameter pack (71834). */
9176 if (arg_idx >= nargs)
9177 ++missing;
9179 else
9180 arg = convert_template_argument (TREE_VALUE (parm),
9181 arg, new_args, complain,
9182 parm_idx, in_decl);
9184 if (arg == error_mark_node)
9185 lost++;
9187 TREE_VEC_ELT (new_inner_args, arg_idx - pack_adjust) = arg;
9190 if (missing || arg_idx < nargs - variadic_args_p)
9192 /* If we had fixed parameter packs, we didn't know how many arguments we
9193 actually needed earlier; now we do. */
9194 nparms += fixed_pack_adjust;
9195 variadic_p -= fixed_packs;
9196 goto bad_nargs;
9199 if (arg_idx < nargs)
9201 /* We had some pack expansion arguments that will only work if the packs
9202 are empty, but wait until instantiation time to complain.
9203 See variadic-ttp3.C. */
9205 /* Except that we can't provide empty packs to alias templates or
9206 concepts when there are no corresponding parameters. Basically,
9207 we can get here with this:
9209 template<typename T> concept C = true;
9211 template<typename... Args>
9212 requires C<Args...>
9213 void f();
9215 When parsing C<Args...>, we try to form a concept check of
9216 C<?, Args...>. Without the extra check for substituting an empty
9217 pack past the last parameter, we can accept the check as valid.
9219 FIXME: This may be valid for alias templates (but I doubt it).
9221 FIXME: The error could be better also. */
9222 if (in_decl && concept_definition_p (in_decl))
9224 if (complain & tf_error)
9225 error_at (location_of (TREE_VEC_ELT (args, arg_idx)),
9226 "too many arguments");
9227 return error_mark_node;
9230 int len = nparms + (nargs - arg_idx);
9231 tree args = make_tree_vec (len);
9232 int i = 0;
9233 for (; i < nparms; ++i)
9234 TREE_VEC_ELT (args, i) = TREE_VEC_ELT (new_inner_args, i);
9235 for (; i < len; ++i, ++arg_idx)
9236 TREE_VEC_ELT (args, i) = TREE_VEC_ELT (inner_args,
9237 arg_idx - pack_adjust);
9238 new_inner_args = args;
9241 if (lost)
9243 gcc_assert (!(complain & tf_error) || seen_error ());
9244 return error_mark_node;
9247 if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
9248 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
9249 TREE_VEC_LENGTH (new_inner_args));
9251 return return_full_args ? new_args : new_inner_args;
9254 /* Returns true if T is a wrapper to make a C++20 template parameter
9255 object const. */
9257 static bool
9258 class_nttp_const_wrapper_p (tree t)
9260 if (cxx_dialect < cxx20)
9261 return false;
9262 return (TREE_CODE (t) == VIEW_CONVERT_EXPR
9263 && CP_TYPE_CONST_P (TREE_TYPE (t))
9264 && TREE_CODE (TREE_OPERAND (t, 0)) == TEMPLATE_PARM_INDEX);
9267 /* Returns 1 if template args OT and NT are equivalent. */
9270 template_args_equal (tree ot, tree nt, bool partial_order /* = false */)
9272 if (nt == ot)
9273 return 1;
9274 if (nt == NULL_TREE || ot == NULL_TREE)
9275 return false;
9276 if (nt == any_targ_node || ot == any_targ_node)
9277 return true;
9279 if (class_nttp_const_wrapper_p (nt))
9280 nt = TREE_OPERAND (nt, 0);
9281 if (class_nttp_const_wrapper_p (ot))
9282 ot = TREE_OPERAND (ot, 0);
9284 /* DR 1558: Don't treat an alias template specialization with dependent
9285 arguments as equivalent to its underlying type when used as a template
9286 argument; we need them to be distinct so that we substitute into the
9287 specialization arguments at instantiation time. And aliases can't be
9288 equivalent without being ==, so we don't need to look any deeper.
9290 During partial ordering, however, we need to treat them normally so we can
9291 order uses of the same alias with different cv-qualification (79960). */
9292 auto cso = make_temp_override (comparing_dependent_aliases);
9293 if (!partial_order)
9294 ++comparing_dependent_aliases;
9296 if (TREE_CODE (nt) == TREE_VEC || TREE_CODE (ot) == TREE_VEC)
9297 /* For member templates */
9298 return TREE_CODE (ot) == TREE_CODE (nt) && comp_template_args (ot, nt);
9299 else if (PACK_EXPANSION_P (ot) || PACK_EXPANSION_P (nt))
9300 return (PACK_EXPANSION_P (ot) && PACK_EXPANSION_P (nt)
9301 && template_args_equal (PACK_EXPANSION_PATTERN (ot),
9302 PACK_EXPANSION_PATTERN (nt))
9303 && template_args_equal (PACK_EXPANSION_EXTRA_ARGS (ot),
9304 PACK_EXPANSION_EXTRA_ARGS (nt)));
9305 else if (ARGUMENT_PACK_P (ot) || ARGUMENT_PACK_P (nt))
9306 return cp_tree_equal (ot, nt);
9307 else if (TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
9308 gcc_unreachable ();
9309 else if (TYPE_P (nt) || TYPE_P (ot))
9311 if (!(TYPE_P (nt) && TYPE_P (ot)))
9312 return false;
9313 return same_type_p (ot, nt);
9315 else
9317 /* Try to treat a template non-type argument that has been converted
9318 to the parameter type as equivalent to one that hasn't yet. */
9319 for (enum tree_code code1 = TREE_CODE (ot);
9320 CONVERT_EXPR_CODE_P (code1)
9321 || code1 == NON_LVALUE_EXPR;
9322 code1 = TREE_CODE (ot))
9323 ot = TREE_OPERAND (ot, 0);
9325 for (enum tree_code code2 = TREE_CODE (nt);
9326 CONVERT_EXPR_CODE_P (code2)
9327 || code2 == NON_LVALUE_EXPR;
9328 code2 = TREE_CODE (nt))
9329 nt = TREE_OPERAND (nt, 0);
9331 return cp_tree_equal (ot, nt);
9335 /* Returns true iff the OLDARGS and NEWARGS are in fact identical sets of
9336 template arguments. Returns false otherwise, and updates OLDARG_PTR and
9337 NEWARG_PTR with the offending arguments if they are non-NULL. */
9339 bool
9340 comp_template_args (tree oldargs, tree newargs,
9341 tree *oldarg_ptr /* = NULL */, tree *newarg_ptr /* = NULL */,
9342 bool partial_order /* = false */)
9344 if (oldargs == newargs)
9345 return true;
9347 if (!oldargs || !newargs)
9348 return false;
9350 if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
9351 return false;
9353 for (int i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
9355 tree nt = TREE_VEC_ELT (newargs, i);
9356 tree ot = TREE_VEC_ELT (oldargs, i);
9358 if (! template_args_equal (ot, nt, partial_order))
9360 if (oldarg_ptr != NULL)
9361 *oldarg_ptr = ot;
9362 if (newarg_ptr != NULL)
9363 *newarg_ptr = nt;
9364 return false;
9367 return true;
9370 inline bool
9371 comp_template_args_porder (tree oargs, tree nargs)
9373 return comp_template_args (oargs, nargs, NULL, NULL, true);
9376 /* Implement a freelist interface for objects of type T.
9378 Head is a separate object, rather than a regular member, so that we
9379 can define it as a GTY deletable pointer, which is highly
9380 desirable. A data member could be declared that way, but then the
9381 containing object would implicitly get GTY((user)), which would
9382 prevent us from instantiating freelists as global objects.
9383 Although this way we can create freelist global objects, they're
9384 such thin wrappers that instantiating temporaries at every use
9385 loses nothing and saves permanent storage for the freelist object.
9387 Member functions next, anew, poison and reinit have default
9388 implementations that work for most of the types we're interested
9389 in, but if they don't work for some type, they should be explicitly
9390 specialized. See the comments before them for requirements, and
9391 the example specializations for the tree_list_freelist. */
9392 template <typename T>
9393 class freelist
9395 /* Return the next object in a chain. We could just do type
9396 punning, but if we access the object with its underlying type, we
9397 avoid strict-aliasing trouble. This needs only work between
9398 poison and reinit. */
9399 static T *&next (T *obj) { return obj->next; }
9401 /* Return a newly allocated, uninitialized or minimally-initialized
9402 object of type T. Any initialization performed by anew should
9403 either remain across the life of the object and the execution of
9404 poison, or be redone by reinit. */
9405 static T *anew () { return ggc_alloc<T> (); }
9407 /* Optionally scribble all over the bits holding the object, so that
9408 they become (mostly?) uninitialized memory. This is called while
9409 preparing to make the object part of the free list. */
9410 static void poison (T *obj) {
9411 T *p ATTRIBUTE_UNUSED = obj;
9412 T **q ATTRIBUTE_UNUSED = &next (obj);
9414 #ifdef ENABLE_GC_CHECKING
9415 /* Poison the data, to indicate the data is garbage. */
9416 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, sizeof (*p)));
9417 memset (p, 0xa5, sizeof (*p));
9418 #endif
9419 /* Let valgrind know the object is free. */
9420 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, sizeof (*p)));
9422 /* Let valgrind know the next portion of the object is available,
9423 but uninitialized. */
9424 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
9427 /* Bring an object that underwent at least one lifecycle after anew
9428 and before the most recent free and poison, back to a usable
9429 state, reinitializing whatever is needed for it to be
9430 functionally equivalent to an object just allocated and returned
9431 by anew. This may poison or clear the next field, used by
9432 freelist housekeeping after poison was called. */
9433 static void reinit (T *obj) {
9434 T **q ATTRIBUTE_UNUSED = &next (obj);
9436 #ifdef ENABLE_GC_CHECKING
9437 memset (q, 0xa5, sizeof (*q));
9438 #endif
9439 /* Let valgrind know the entire object is available, but
9440 uninitialized. */
9441 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (*obj)));
9444 /* Reference a GTY-deletable pointer that points to the first object
9445 in the free list proper. */
9446 T *&head;
9447 public:
9448 /* Construct a freelist object chaining objects off of HEAD. */
9449 freelist (T *&head) : head(head) {}
9451 /* Add OBJ to the free object list. The former head becomes OBJ's
9452 successor. */
9453 void free (T *obj)
9455 poison (obj);
9456 next (obj) = head;
9457 head = obj;
9460 /* Take an object from the free list, if one is available, or
9461 allocate a new one. Objects taken from the free list should be
9462 regarded as filled with garbage, except for bits that are
9463 configured to be preserved across free and alloc. */
9464 T *alloc ()
9466 if (head)
9468 T *obj = head;
9469 head = next (head);
9470 reinit (obj);
9471 return obj;
9473 else
9474 return anew ();
9478 /* Explicitly specialize the interfaces for freelist<tree_node>: we
9479 want to allocate a TREE_LIST using the usual interface, and ensure
9480 TREE_CHAIN remains functional. Alas, we have to duplicate a bit of
9481 build_tree_list logic in reinit, so this could go out of sync. */
9482 template <>
9483 inline tree &
9484 freelist<tree_node>::next (tree obj)
9486 return TREE_CHAIN (obj);
9488 template <>
9489 inline tree
9490 freelist<tree_node>::anew ()
9492 return build_tree_list (NULL, NULL);
9494 template <>
9495 inline void
9496 freelist<tree_node>::poison (tree obj ATTRIBUTE_UNUSED)
9498 int size ATTRIBUTE_UNUSED = sizeof (tree_list);
9499 tree p ATTRIBUTE_UNUSED = obj;
9500 tree_base *b ATTRIBUTE_UNUSED = &obj->base;
9501 tree *q ATTRIBUTE_UNUSED = &next (obj);
9503 #ifdef ENABLE_GC_CHECKING
9504 gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
9506 /* Poison the data, to indicate the data is garbage. */
9507 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, size));
9508 memset (p, 0xa5, size);
9509 #endif
9510 /* Let valgrind know the object is free. */
9511 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, size));
9512 /* But we still want to use the TREE_CODE and TREE_CHAIN parts. */
9513 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9514 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
9516 #ifdef ENABLE_GC_CHECKING
9517 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (b, sizeof (*b)));
9518 /* Keep TREE_CHAIN functional. */
9519 TREE_SET_CODE (obj, TREE_LIST);
9520 #else
9521 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9522 #endif
9524 template <>
9525 inline void
9526 freelist<tree_node>::reinit (tree obj ATTRIBUTE_UNUSED)
9528 tree_base *b ATTRIBUTE_UNUSED = &obj->base;
9530 #ifdef ENABLE_GC_CHECKING
9531 gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
9532 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
9533 memset (obj, 0, sizeof (tree_list));
9534 #endif
9536 /* Let valgrind know the entire object is available, but
9537 uninitialized. */
9538 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
9540 #ifdef ENABLE_GC_CHECKING
9541 TREE_SET_CODE (obj, TREE_LIST);
9542 #else
9543 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9544 #endif
9547 /* Point to the first object in the TREE_LIST freelist. */
9548 static GTY((deletable)) tree tree_list_freelist_head;
9549 /* Return the/an actual TREE_LIST freelist. */
9550 static inline freelist<tree_node>
9551 tree_list_freelist ()
9553 return tree_list_freelist_head;
9556 /* Point to the first object in the tinst_level freelist. */
9557 static GTY((deletable)) tinst_level *tinst_level_freelist_head;
9558 /* Return the/an actual tinst_level freelist. */
9559 static inline freelist<tinst_level>
9560 tinst_level_freelist ()
9562 return tinst_level_freelist_head;
9565 /* Point to the first object in the pending_template freelist. */
9566 static GTY((deletable)) pending_template *pending_template_freelist_head;
9567 /* Return the/an actual pending_template freelist. */
9568 static inline freelist<pending_template>
9569 pending_template_freelist ()
9571 return pending_template_freelist_head;
9574 /* Build the TREE_LIST object out of a split list, store it
9575 permanently, and return it. */
9576 tree
9577 tinst_level::to_list ()
9579 gcc_assert (split_list_p ());
9580 tree ret = tree_list_freelist ().alloc ();
9581 TREE_PURPOSE (ret) = tldcl;
9582 TREE_VALUE (ret) = targs;
9583 tldcl = ret;
9584 targs = NULL;
9585 gcc_assert (tree_list_p ());
9586 return ret;
9589 const unsigned short tinst_level::refcount_infinity;
9591 /* Increment OBJ's refcount unless it is already infinite. */
9592 static tinst_level *
9593 inc_refcount_use (tinst_level *obj)
9595 if (obj && obj->refcount != tinst_level::refcount_infinity)
9596 ++obj->refcount;
9597 return obj;
9600 /* Release storage for OBJ and node, if it's a TREE_LIST. */
9601 void
9602 tinst_level::free (tinst_level *obj)
9604 if (obj->tree_list_p ())
9605 tree_list_freelist ().free (obj->get_node ());
9606 tinst_level_freelist ().free (obj);
9609 /* Decrement OBJ's refcount if not infinite. If it reaches zero, release
9610 OBJ's DECL and OBJ, and start over with the tinst_level object that
9611 used to be referenced by OBJ's NEXT. */
9612 static void
9613 dec_refcount_use (tinst_level *obj)
9615 while (obj
9616 && obj->refcount != tinst_level::refcount_infinity
9617 && !--obj->refcount)
9619 tinst_level *next = obj->next;
9620 tinst_level::free (obj);
9621 obj = next;
9625 /* Modify PTR so that it points to OBJ, adjusting the refcounts of OBJ
9626 and of the former PTR. Omitting the second argument is equivalent
9627 to passing (T*)NULL; this is allowed because passing the
9628 zero-valued integral constant NULL confuses type deduction and/or
9629 overload resolution. */
9630 template <typename T>
9631 static void
9632 set_refcount_ptr (T *& ptr, T *obj = NULL)
9634 T *save = ptr;
9635 ptr = inc_refcount_use (obj);
9636 dec_refcount_use (save);
9639 static void
9640 add_pending_template (tree d)
9642 tree ti = (TYPE_P (d)
9643 ? CLASSTYPE_TEMPLATE_INFO (d)
9644 : DECL_TEMPLATE_INFO (d));
9645 struct pending_template *pt;
9646 int level;
9648 if (TI_PENDING_TEMPLATE_FLAG (ti))
9649 return;
9651 /* We are called both from instantiate_decl, where we've already had a
9652 tinst_level pushed, and instantiate_template, where we haven't.
9653 Compensate. */
9654 gcc_assert (TREE_CODE (d) != TREE_LIST);
9655 level = !current_tinst_level
9656 || current_tinst_level->maybe_get_node () != d;
9658 if (level)
9659 push_tinst_level (d);
9661 pt = pending_template_freelist ().alloc ();
9662 pt->next = NULL;
9663 pt->tinst = NULL;
9664 set_refcount_ptr (pt->tinst, current_tinst_level);
9665 if (last_pending_template)
9666 last_pending_template->next = pt;
9667 else
9668 pending_templates = pt;
9670 last_pending_template = pt;
9672 TI_PENDING_TEMPLATE_FLAG (ti) = 1;
9674 if (level)
9675 pop_tinst_level ();
9679 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
9680 ARGLIST. Valid choices for FNS are given in the cp-tree.def
9681 documentation for TEMPLATE_ID_EXPR. */
9683 tree
9684 lookup_template_function (tree fns, tree arglist)
9686 if (fns == error_mark_node || arglist == error_mark_node)
9687 return error_mark_node;
9689 gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
9691 if (!is_overloaded_fn (fns) && !identifier_p (fns))
9693 error ("%q#D is not a function template", fns);
9694 return error_mark_node;
9697 if (BASELINK_P (fns))
9699 fns = copy_node (fns);
9700 BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
9701 unknown_type_node,
9702 BASELINK_FUNCTIONS (fns),
9703 arglist);
9704 return fns;
9707 return build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, arglist);
9710 /* Within the scope of a template class S<T>, the name S gets bound
9711 (in build_self_reference) to a TYPE_DECL for the class, not a
9712 TEMPLATE_DECL. If DECL is a TYPE_DECL for current_class_type,
9713 or one of its enclosing classes, and that type is a template,
9714 return the associated TEMPLATE_DECL. Otherwise, the original
9715 DECL is returned.
9717 Also handle the case when DECL is a TREE_LIST of ambiguous
9718 injected-class-names from different bases. */
9720 tree
9721 maybe_get_template_decl_from_type_decl (tree decl)
9723 if (decl == NULL_TREE)
9724 return decl;
9726 /* DR 176: A lookup that finds an injected-class-name (10.2
9727 [class.member.lookup]) can result in an ambiguity in certain cases
9728 (for example, if it is found in more than one base class). If all of
9729 the injected-class-names that are found refer to specializations of
9730 the same class template, and if the name is followed by a
9731 template-argument-list, the reference refers to the class template
9732 itself and not a specialization thereof, and is not ambiguous. */
9733 if (TREE_CODE (decl) == TREE_LIST)
9735 tree t, tmpl = NULL_TREE;
9736 for (t = decl; t; t = TREE_CHAIN (t))
9738 tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
9739 if (!tmpl)
9740 tmpl = elt;
9741 else if (tmpl != elt)
9742 break;
9744 if (tmpl && t == NULL_TREE)
9745 return tmpl;
9746 else
9747 return decl;
9750 return (decl != NULL_TREE
9751 && DECL_SELF_REFERENCE_P (decl)
9752 && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
9753 ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
9756 /* Given an IDENTIFIER_NODE (or type TEMPLATE_DECL) and a chain of
9757 parameters, find the desired type.
9759 D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
9761 IN_DECL, if non-NULL, is the template declaration we are trying to
9762 instantiate.
9764 If ENTERING_SCOPE is nonzero, we are about to enter the scope of
9765 the class we are looking up.
9767 Issue error and warning messages under control of COMPLAIN.
9769 If the template class is really a local class in a template
9770 function, then the FUNCTION_CONTEXT is the function in which it is
9771 being instantiated.
9773 ??? Note that this function is currently called *twice* for each
9774 template-id: the first time from the parser, while creating the
9775 incomplete type (finish_template_type), and the second type during the
9776 real instantiation (instantiate_template_class). This is surely something
9777 that we want to avoid. It also causes some problems with argument
9778 coercion (see convert_nontype_argument for more information on this). */
9780 tree
9781 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
9782 int entering_scope, tsubst_flags_t complain)
9784 auto_timevar tv (TV_TEMPLATE_INST);
9786 tree templ = NULL_TREE, parmlist;
9787 tree t;
9788 spec_entry **slot;
9789 spec_entry *entry;
9790 spec_entry elt;
9791 hashval_t hash;
9793 if (identifier_p (d1))
9795 tree value = innermost_non_namespace_value (d1);
9796 if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
9797 templ = value;
9798 else
9800 if (context)
9801 push_decl_namespace (context);
9802 templ = lookup_name (d1);
9803 templ = maybe_get_template_decl_from_type_decl (templ);
9804 if (context)
9805 pop_decl_namespace ();
9808 else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
9810 tree type = TREE_TYPE (d1);
9812 /* If we are declaring a constructor, say A<T>::A<T>, we will get
9813 an implicit typename for the second A. Deal with it. */
9814 if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
9815 type = TREE_TYPE (type);
9817 if (CLASSTYPE_TEMPLATE_INFO (type))
9819 templ = CLASSTYPE_TI_TEMPLATE (type);
9820 d1 = DECL_NAME (templ);
9823 else if (TREE_CODE (d1) == ENUMERAL_TYPE
9824 || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
9826 templ = TYPE_TI_TEMPLATE (d1);
9827 d1 = DECL_NAME (templ);
9829 else if (DECL_TYPE_TEMPLATE_P (d1))
9831 templ = d1;
9832 d1 = DECL_NAME (templ);
9834 else if (DECL_TEMPLATE_TEMPLATE_PARM_P (d1))
9836 templ = d1;
9837 d1 = DECL_NAME (templ);
9840 /* Issue an error message if we didn't find a template. */
9841 if (! templ)
9843 if (complain & tf_error)
9844 error ("%qT is not a template", d1);
9845 return error_mark_node;
9848 if (TREE_CODE (templ) != TEMPLATE_DECL
9849 /* Make sure it's a user visible template, if it was named by
9850 the user. */
9851 || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
9852 && !PRIMARY_TEMPLATE_P (templ)))
9854 if (complain & tf_error)
9856 error ("non-template type %qT used as a template", d1);
9857 if (in_decl)
9858 error ("for template declaration %q+D", in_decl);
9860 return error_mark_node;
9863 complain &= ~tf_user;
9865 /* An alias that just changes the name of a template is equivalent to the
9866 other template, so if any of the arguments are pack expansions, strip
9867 the alias to avoid problems with a pack expansion passed to a non-pack
9868 alias template parameter (DR 1430). */
9869 if (pack_expansion_args_count (INNERMOST_TEMPLATE_ARGS (arglist)))
9870 templ = get_underlying_template (templ);
9872 if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
9874 tree parm;
9875 tree arglist2 = coerce_template_args_for_ttp (templ, arglist, complain);
9876 if (arglist2 == error_mark_node
9877 || (!uses_template_parms (arglist2)
9878 && check_instantiated_args (templ, arglist2, complain)))
9879 return error_mark_node;
9881 parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
9882 return parm;
9884 else
9886 tree template_type = TREE_TYPE (templ);
9887 tree gen_tmpl;
9888 tree type_decl;
9889 tree found = NULL_TREE;
9890 int arg_depth;
9891 int parm_depth;
9892 int is_dependent_type;
9893 int use_partial_inst_tmpl = false;
9895 if (template_type == error_mark_node)
9896 /* An error occurred while building the template TEMPL, and a
9897 diagnostic has most certainly been emitted for that
9898 already. Let's propagate that error. */
9899 return error_mark_node;
9901 gen_tmpl = most_general_template (templ);
9902 if (modules_p ())
9903 lazy_load_pendings (gen_tmpl);
9905 parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
9906 parm_depth = TMPL_PARMS_DEPTH (parmlist);
9907 arg_depth = TMPL_ARGS_DEPTH (arglist);
9909 if (arg_depth == 1 && parm_depth > 1)
9911 /* We've been given an incomplete set of template arguments.
9912 For example, given:
9914 template <class T> struct S1 {
9915 template <class U> struct S2 {};
9916 template <class U> struct S2<U*> {};
9919 we will be called with an ARGLIST of `U*', but the
9920 TEMPLATE will be `template <class T> template
9921 <class U> struct S1<T>::S2'. We must fill in the missing
9922 arguments. */
9923 tree ti = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (templ));
9924 arglist = add_outermost_template_args (TI_ARGS (ti), arglist);
9925 arg_depth = TMPL_ARGS_DEPTH (arglist);
9928 /* Now we should have enough arguments. */
9929 gcc_assert (parm_depth == arg_depth);
9931 /* From here on, we're only interested in the most general
9932 template. */
9934 /* Shortcut looking up the current class scope again. */
9935 for (tree cur = current_nonlambda_class_type ();
9936 cur != NULL_TREE;
9937 cur = get_containing_scope (cur))
9939 if (!CLASS_TYPE_P (cur))
9940 continue;
9942 tree ti = CLASSTYPE_TEMPLATE_INFO (cur);
9943 if (!ti || arg_depth > TMPL_ARGS_DEPTH (TI_ARGS (ti)))
9944 break;
9946 if (gen_tmpl == most_general_template (TI_TEMPLATE (ti))
9947 && comp_template_args (arglist, TI_ARGS (ti)))
9948 return cur;
9951 /* Calculate the BOUND_ARGS. These will be the args that are
9952 actually tsubst'd into the definition to create the
9953 instantiation. */
9954 if (PRIMARY_TEMPLATE_P (gen_tmpl))
9955 arglist = coerce_template_parms (parmlist, arglist, gen_tmpl, complain);
9957 if (arglist == error_mark_node)
9958 /* We were unable to bind the arguments. */
9959 return error_mark_node;
9961 /* In the scope of a template class, explicit references to the
9962 template class refer to the type of the template, not any
9963 instantiation of it. For example, in:
9965 template <class T> class C { void f(C<T>); }
9967 the `C<T>' is just the same as `C'. Outside of the
9968 class, however, such a reference is an instantiation. */
9969 if (entering_scope
9970 || !PRIMARY_TEMPLATE_P (gen_tmpl)
9971 || currently_open_class (template_type))
9973 tree tinfo = TYPE_TEMPLATE_INFO (template_type);
9975 if (tinfo && comp_template_args (TI_ARGS (tinfo), arglist))
9976 return template_type;
9979 /* If we already have this specialization, return it. */
9980 elt.tmpl = gen_tmpl;
9981 elt.args = arglist;
9982 elt.spec = NULL_TREE;
9983 hash = spec_hasher::hash (&elt);
9984 entry = type_specializations->find_with_hash (&elt, hash);
9986 if (entry)
9987 return entry->spec;
9989 /* If the template's constraints are not satisfied,
9990 then we cannot form a valid type.
9992 Note that the check is deferred until after the hash
9993 lookup. This prevents redundant checks on previously
9994 instantiated specializations. */
9995 if (flag_concepts
9996 && !DECL_ALIAS_TEMPLATE_P (gen_tmpl)
9997 && !constraints_satisfied_p (gen_tmpl, arglist))
9999 if (complain & tf_error)
10001 auto_diagnostic_group d;
10002 error ("template constraint failure for %qD", gen_tmpl);
10003 diagnose_constraints (input_location, gen_tmpl, arglist);
10005 return error_mark_node;
10008 is_dependent_type = uses_template_parms (arglist);
10010 /* If the deduced arguments are invalid, then the binding
10011 failed. */
10012 if (!is_dependent_type
10013 && check_instantiated_args (gen_tmpl,
10014 INNERMOST_TEMPLATE_ARGS (arglist),
10015 complain))
10016 return error_mark_node;
10018 if (!is_dependent_type
10019 && !PRIMARY_TEMPLATE_P (gen_tmpl)
10020 && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
10021 && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
10022 /* This occurs when the user has tried to define a tagged type
10023 in a scope that forbids it. We emitted an error during the
10024 parse. We didn't complete the bail out then, so here we
10025 are. */
10026 return error_mark_node;
10028 context = DECL_CONTEXT (gen_tmpl);
10029 if (context && TYPE_P (context))
10031 if (!uses_template_parms (DECL_CONTEXT (templ)))
10032 /* If the context of the partially instantiated template is
10033 already non-dependent, then we might as well use it. */
10034 context = DECL_CONTEXT (templ);
10035 else
10037 context = tsubst_aggr_type (context, arglist,
10038 complain, in_decl, true);
10039 /* Try completing the enclosing context if it's not already so. */
10040 if (context != error_mark_node
10041 && !COMPLETE_TYPE_P (context))
10043 context = complete_type (context);
10044 if (COMPLETE_TYPE_P (context))
10046 /* Completion could have caused us to register the desired
10047 specialization already, so check the table again. */
10048 entry = type_specializations->find_with_hash (&elt, hash);
10049 if (entry)
10050 return entry->spec;
10055 else
10056 context = tsubst (context, arglist, complain, in_decl);
10058 if (context == error_mark_node)
10059 return error_mark_node;
10061 if (!context)
10062 context = global_namespace;
10064 /* Create the type. */
10065 if (DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10067 /* The user referred to a specialization of an alias
10068 template represented by GEN_TMPL.
10070 [temp.alias]/2 says:
10072 When a template-id refers to the specialization of an
10073 alias template, it is equivalent to the associated
10074 type obtained by substitution of its
10075 template-arguments for the template-parameters in the
10076 type-id of the alias template. */
10078 t = tsubst (TREE_TYPE (gen_tmpl), arglist, complain, in_decl);
10079 /* Note that the call above (by indirectly calling
10080 register_specialization in tsubst_decl) registers the
10081 TYPE_DECL representing the specialization of the alias
10082 template. So next time someone substitutes ARGLIST for
10083 the template parms into the alias template (GEN_TMPL),
10084 she'll get that TYPE_DECL back. */
10086 if (t == error_mark_node)
10087 return t;
10089 else if (TREE_CODE (template_type) == ENUMERAL_TYPE)
10091 if (!is_dependent_type)
10093 set_current_access_from_decl (TYPE_NAME (template_type));
10094 t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
10095 tsubst (ENUM_UNDERLYING_TYPE (template_type),
10096 arglist, complain, in_decl),
10097 tsubst_attributes (TYPE_ATTRIBUTES (template_type),
10098 arglist, complain, in_decl),
10099 SCOPED_ENUM_P (template_type), NULL);
10101 if (t == error_mark_node)
10102 return t;
10104 else
10106 /* We don't want to call start_enum for this type, since
10107 the values for the enumeration constants may involve
10108 template parameters. And, no one should be interested
10109 in the enumeration constants for such a type. */
10110 t = cxx_make_type (ENUMERAL_TYPE);
10111 SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
10113 SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
10114 ENUM_FIXED_UNDERLYING_TYPE_P (t)
10115 = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
10117 else if (CLASS_TYPE_P (template_type))
10119 /* Lambda closures are regenerated in tsubst_lambda_expr, not
10120 instantiated here. */
10121 gcc_assert (!LAMBDA_TYPE_P (template_type));
10123 t = make_class_type (TREE_CODE (template_type));
10124 CLASSTYPE_DECLARED_CLASS (t)
10125 = CLASSTYPE_DECLARED_CLASS (template_type);
10126 SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
10128 /* A local class. Make sure the decl gets registered properly. */
10129 if (context == current_function_decl)
10130 if (pushtag (DECL_NAME (gen_tmpl), t)
10131 == error_mark_node)
10132 return error_mark_node;
10134 if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
10135 /* This instantiation is another name for the primary
10136 template type. Set the TYPE_CANONICAL field
10137 appropriately. */
10138 TYPE_CANONICAL (t) = template_type;
10139 else if (any_template_arguments_need_structural_equality_p (arglist))
10140 SET_TYPE_STRUCTURAL_EQUALITY (t);
10142 else
10143 gcc_unreachable ();
10145 /* If we called start_enum or pushtag above, this information
10146 will already be set up. */
10147 type_decl = TYPE_NAME (t);
10148 if (!type_decl)
10150 TYPE_CONTEXT (t) = FROB_CONTEXT (context);
10152 type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
10153 DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
10154 DECL_SOURCE_LOCATION (type_decl)
10155 = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
10158 set_instantiating_module (type_decl);
10159 /* Although GEN_TMPL is the TEMPLATE_DECL, it has the same value
10160 of export flag. We want to propagate this because it might
10161 be a friend declaration that pushes a new hidden binding. */
10162 DECL_MODULE_EXPORT_P (type_decl) = DECL_MODULE_EXPORT_P (gen_tmpl);
10164 if (CLASS_TYPE_P (template_type))
10166 TREE_PRIVATE (type_decl)
10167 = TREE_PRIVATE (TYPE_MAIN_DECL (template_type));
10168 TREE_PROTECTED (type_decl)
10169 = TREE_PROTECTED (TYPE_MAIN_DECL (template_type));
10170 if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
10172 DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
10173 DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
10177 if (OVERLOAD_TYPE_P (t)
10178 && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10180 static const char *tags[] = {"abi_tag", "may_alias"};
10182 for (unsigned ix = 0; ix != 2; ix++)
10184 tree attributes
10185 = lookup_attribute (tags[ix], TYPE_ATTRIBUTES (template_type));
10187 if (attributes)
10188 TYPE_ATTRIBUTES (t)
10189 = tree_cons (TREE_PURPOSE (attributes),
10190 TREE_VALUE (attributes),
10191 TYPE_ATTRIBUTES (t));
10195 /* Let's consider the explicit specialization of a member
10196 of a class template specialization that is implicitly instantiated,
10197 e.g.:
10198 template<class T>
10199 struct S
10201 template<class U> struct M {}; //#0
10204 template<>
10205 template<>
10206 struct S<int>::M<char> //#1
10208 int i;
10210 [temp.expl.spec]/4 says this is valid.
10212 In this case, when we write:
10213 S<int>::M<char> m;
10215 M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
10216 the one of #0.
10218 When we encounter #1, we want to store the partial instantiation
10219 of M (template<class T> S<int>::M<T>) in its CLASSTYPE_TI_TEMPLATE.
10221 For all cases other than this "explicit specialization of member of a
10222 class template", we just want to store the most general template into
10223 the CLASSTYPE_TI_TEMPLATE of M.
10225 This case of "explicit specialization of member of a class template"
10226 only happens when:
10227 1/ the enclosing class is an instantiation of, and therefore not
10228 the same as, the context of the most general template, and
10229 2/ we aren't looking at the partial instantiation itself, i.e.
10230 the innermost arguments are not the same as the innermost parms of
10231 the most general template.
10233 So it's only when 1/ and 2/ happens that we want to use the partial
10234 instantiation of the member template in lieu of its most general
10235 template. */
10237 if (PRIMARY_TEMPLATE_P (gen_tmpl)
10238 && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
10239 /* the enclosing class must be an instantiation... */
10240 && CLASS_TYPE_P (context)
10241 && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
10243 TREE_VEC_LENGTH (arglist)--;
10244 ++processing_template_decl;
10245 tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (gen_tmpl));
10246 tree partial_inst_args =
10247 tsubst (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)),
10248 arglist, complain, NULL_TREE);
10249 --processing_template_decl;
10250 TREE_VEC_LENGTH (arglist)++;
10251 if (partial_inst_args == error_mark_node)
10252 return error_mark_node;
10253 use_partial_inst_tmpl =
10254 /*...and we must not be looking at the partial instantiation
10255 itself. */
10256 !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
10257 partial_inst_args);
10260 if (!use_partial_inst_tmpl)
10261 /* This case is easy; there are no member templates involved. */
10262 found = gen_tmpl;
10263 else
10265 /* This is a full instantiation of a member template. Find
10266 the partial instantiation of which this is an instance. */
10268 /* Temporarily reduce by one the number of levels in the ARGLIST
10269 so as to avoid comparing the last set of arguments. */
10270 TREE_VEC_LENGTH (arglist)--;
10271 /* We don't use COMPLAIN in the following call because this isn't
10272 the immediate context of deduction. For instance, tf_partial
10273 could be set here as we might be at the beginning of template
10274 argument deduction when any explicitly specified template
10275 arguments are substituted into the function type. tf_partial
10276 could lead into trouble because we wouldn't find the partial
10277 instantiation that might have been created outside tf_partial
10278 context, because the levels of template parameters wouldn't
10279 match, because in a tf_partial context, tsubst doesn't reduce
10280 TEMPLATE_PARM_LEVEL. */
10281 found = tsubst (gen_tmpl, arglist, tf_none, NULL_TREE);
10282 TREE_VEC_LENGTH (arglist)++;
10283 /* FOUND is either a proper class type, or an alias
10284 template specialization. In the later case, it's a
10285 TYPE_DECL, resulting from the substituting of arguments
10286 for parameters in the TYPE_DECL of the alias template
10287 done earlier. So be careful while getting the template
10288 of FOUND. */
10289 found = (TREE_CODE (found) == TEMPLATE_DECL
10290 ? found
10291 : (TREE_CODE (found) == TYPE_DECL
10292 ? DECL_TI_TEMPLATE (found)
10293 : CLASSTYPE_TI_TEMPLATE (found)));
10295 if (DECL_CLASS_TEMPLATE_P (found)
10296 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (found)))
10298 /* If this partial instantiation is specialized, we want to
10299 use it for hash table lookup. */
10300 elt.tmpl = found;
10301 elt.args = arglist = INNERMOST_TEMPLATE_ARGS (arglist);
10302 hash = spec_hasher::hash (&elt);
10306 /* Build template info for the new specialization. */
10307 SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
10309 elt.spec = t;
10310 slot = type_specializations->find_slot_with_hash (&elt, hash, INSERT);
10311 gcc_checking_assert (*slot == NULL);
10312 entry = ggc_alloc<spec_entry> ();
10313 *entry = elt;
10314 *slot = entry;
10316 /* Note this use of the partial instantiation so we can check it
10317 later in maybe_process_partial_specialization. */
10318 DECL_TEMPLATE_INSTANTIATIONS (found)
10319 = tree_cons (arglist, t,
10320 DECL_TEMPLATE_INSTANTIATIONS (found));
10322 if (TREE_CODE (template_type) == ENUMERAL_TYPE
10323 && !uses_template_parms (current_nonlambda_scope ())
10324 && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10325 /* Now that the type has been registered on the instantiations
10326 list, we set up the enumerators. Because the enumeration
10327 constants may involve the enumeration type itself, we make
10328 sure to register the type first, and then create the
10329 constants. That way, doing tsubst_expr for the enumeration
10330 constants won't result in recursive calls here; we'll find
10331 the instantiation and exit above. */
10332 tsubst_enum (template_type, t, arglist);
10334 if (CLASS_TYPE_P (template_type) && is_dependent_type)
10335 /* If the type makes use of template parameters, the
10336 code that generates debugging information will crash. */
10337 DECL_IGNORED_P (TYPE_MAIN_DECL (t)) = 1;
10339 /* Possibly limit visibility based on template args. */
10340 TREE_PUBLIC (type_decl) = 1;
10341 determine_visibility (type_decl);
10343 inherit_targ_abi_tags (t);
10345 return t;
10349 /* Return a TEMPLATE_ID_EXPR for the given variable template and ARGLIST. */
10351 tree
10352 lookup_template_variable (tree templ, tree arglist, tsubst_flags_t complain)
10354 if (flag_concepts && variable_concept_p (templ))
10355 return build_concept_check (templ, arglist, tf_none);
10357 tree gen_templ = most_general_template (templ);
10358 tree parms = DECL_INNERMOST_TEMPLATE_PARMS (gen_templ);
10359 arglist = add_outermost_template_args (templ, arglist);
10360 arglist = coerce_template_parms (parms, arglist, templ, complain);
10361 if (arglist == error_mark_node)
10362 return error_mark_node;
10364 /* The type of the expression is NULL_TREE since the template-id could refer
10365 to an explicit or partial specialization. */
10366 return build2 (TEMPLATE_ID_EXPR, NULL_TREE, templ, arglist);
10369 /* Instantiate a variable declaration from a TEMPLATE_ID_EXPR if it's
10370 not dependent. */
10372 tree
10373 finish_template_variable (tree var, tsubst_flags_t complain)
10375 tree templ = TREE_OPERAND (var, 0);
10376 tree arglist = TREE_OPERAND (var, 1);
10378 /* If the template or arguments are dependent, then we
10379 can't resolve the TEMPLATE_ID_EXPR yet. */
10380 if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (templ)) != 1
10381 || any_dependent_template_arguments_p (arglist))
10382 return var;
10384 if (flag_concepts && !constraints_satisfied_p (templ, arglist))
10386 if (complain & tf_error)
10388 auto_diagnostic_group d;
10389 error ("use of invalid variable template %qE", var);
10390 diagnose_constraints (location_of (var), templ, arglist);
10392 return error_mark_node;
10395 return instantiate_template (templ, arglist, complain);
10398 /* Construct a TEMPLATE_ID_EXPR for the given variable template TEMPL having
10399 TARGS template args, and instantiate it if it's not dependent. */
10401 tree
10402 lookup_and_finish_template_variable (tree templ, tree targs,
10403 tsubst_flags_t complain)
10405 tree var = lookup_template_variable (templ, targs, complain);
10406 if (var == error_mark_node)
10407 return error_mark_node;
10408 var = finish_template_variable (var, complain);
10409 mark_used (var);
10410 return var;
10413 /* If the set of template parameters PARMS contains a template parameter
10414 at the given LEVEL and INDEX, then return this parameter. Otherwise
10415 return NULL_TREE. */
10417 static tree
10418 corresponding_template_parameter_list (tree parms, int level, int index)
10420 while (TMPL_PARMS_DEPTH (parms) > level)
10421 parms = TREE_CHAIN (parms);
10423 if (TMPL_PARMS_DEPTH (parms) != level
10424 || TREE_VEC_LENGTH (TREE_VALUE (parms)) <= index)
10425 return NULL_TREE;
10427 return TREE_VEC_ELT (TREE_VALUE (parms), index);
10430 /* Return the TREE_LIST for the template parameter from PARMS that positionally
10431 corresponds to the template parameter PARM, or else return NULL_TREE. */
10433 static tree
10434 corresponding_template_parameter_list (tree parms, tree parm)
10436 int level, index;
10437 template_parm_level_and_index (parm, &level, &index);
10438 return corresponding_template_parameter_list (parms, level, index);
10441 /* As above, but pull out the actual parameter. */
10443 static tree
10444 corresponding_template_parameter (tree parms, tree parm)
10446 tree list = corresponding_template_parameter_list (parms, parm);
10447 if (!list)
10448 return NULL_TREE;
10450 tree t = TREE_VALUE (list);
10451 /* As in template_parm_to_arg. */
10452 if (TREE_CODE (t) == TYPE_DECL || TREE_CODE (t) == TEMPLATE_DECL)
10453 t = TREE_TYPE (t);
10454 else
10455 t = DECL_INITIAL (t);
10457 gcc_assert (TEMPLATE_PARM_P (t));
10458 return t;
10461 struct pair_fn_data
10463 tree_fn_t fn;
10464 tree_fn_t any_fn;
10465 void *data;
10466 /* True when we should also visit template parameters that occur in
10467 non-deduced contexts. */
10468 bool include_nondeduced_p;
10469 hash_set<tree> *visited;
10472 /* Called from for_each_template_parm via walk_tree. */
10474 static tree
10475 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
10477 tree t = *tp;
10478 struct pair_fn_data *pfd = (struct pair_fn_data *) d;
10479 tree_fn_t fn = pfd->fn;
10480 void *data = pfd->data;
10481 tree result = NULL_TREE;
10483 #define WALK_SUBTREE(NODE) \
10484 do \
10486 result = for_each_template_parm (NODE, fn, data, pfd->visited, \
10487 pfd->include_nondeduced_p, \
10488 pfd->any_fn); \
10489 if (result) goto out; \
10491 while (0)
10493 if (pfd->any_fn && (*pfd->any_fn)(t, data))
10494 return t;
10496 if (TYPE_P (t)
10497 && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE))
10498 WALK_SUBTREE (TYPE_CONTEXT (t));
10500 switch (TREE_CODE (t))
10502 case RECORD_TYPE:
10503 if (TYPE_PTRMEMFUNC_P (t))
10504 break;
10505 /* Fall through. */
10507 case UNION_TYPE:
10508 case ENUMERAL_TYPE:
10509 if (!TYPE_TEMPLATE_INFO (t))
10510 *walk_subtrees = 0;
10511 else
10512 WALK_SUBTREE (TYPE_TI_ARGS (t));
10513 break;
10515 case INTEGER_TYPE:
10516 WALK_SUBTREE (TYPE_MIN_VALUE (t));
10517 WALK_SUBTREE (TYPE_MAX_VALUE (t));
10518 break;
10520 case METHOD_TYPE:
10521 /* Since we're not going to walk subtrees, we have to do this
10522 explicitly here. */
10523 WALK_SUBTREE (TYPE_METHOD_BASETYPE (t));
10524 /* Fall through. */
10526 case FUNCTION_TYPE:
10527 /* Check the return type. */
10528 WALK_SUBTREE (TREE_TYPE (t));
10530 /* Check the parameter types. Since default arguments are not
10531 instantiated until they are needed, the TYPE_ARG_TYPES may
10532 contain expressions that involve template parameters. But,
10533 no-one should be looking at them yet. And, once they're
10534 instantiated, they don't contain template parameters, so
10535 there's no point in looking at them then, either. */
10537 tree parm;
10539 for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
10540 WALK_SUBTREE (TREE_VALUE (parm));
10542 /* Since we've already handled the TYPE_ARG_TYPES, we don't
10543 want walk_tree walking into them itself. */
10544 *walk_subtrees = 0;
10547 if (flag_noexcept_type)
10549 tree spec = TYPE_RAISES_EXCEPTIONS (t);
10550 if (spec)
10551 WALK_SUBTREE (TREE_PURPOSE (spec));
10553 break;
10555 case TYPEOF_TYPE:
10556 case DECLTYPE_TYPE:
10557 if (pfd->include_nondeduced_p
10558 && for_each_template_parm (TYPE_VALUES_RAW (t), fn, data,
10559 pfd->visited,
10560 pfd->include_nondeduced_p,
10561 pfd->any_fn))
10562 return error_mark_node;
10563 *walk_subtrees = false;
10564 break;
10566 case TRAIT_TYPE:
10567 if (pfd->include_nondeduced_p)
10569 WALK_SUBTREE (TRAIT_TYPE_TYPE1 (t));
10570 WALK_SUBTREE (TRAIT_TYPE_TYPE2 (t));
10572 *walk_subtrees = false;
10573 break;
10575 case FUNCTION_DECL:
10576 case VAR_DECL:
10577 if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10578 WALK_SUBTREE (DECL_TI_ARGS (t));
10579 break;
10581 case PARM_DECL:
10582 WALK_SUBTREE (TREE_TYPE (t));
10583 break;
10585 case CONST_DECL:
10586 if (DECL_TEMPLATE_PARM_P (t))
10587 WALK_SUBTREE (DECL_INITIAL (t));
10588 if (DECL_CONTEXT (t)
10589 && pfd->include_nondeduced_p)
10590 WALK_SUBTREE (DECL_CONTEXT (t));
10591 break;
10593 case BOUND_TEMPLATE_TEMPLATE_PARM:
10594 /* Record template parameters such as `T' inside `TT<T>'. */
10595 WALK_SUBTREE (TYPE_TI_ARGS (t));
10596 /* Fall through. */
10598 case TEMPLATE_TEMPLATE_PARM:
10599 case TEMPLATE_TYPE_PARM:
10600 case TEMPLATE_PARM_INDEX:
10601 if (fn && (*fn)(t, data))
10602 return t;
10603 else if (!fn)
10604 return t;
10605 break;
10607 case TEMPLATE_DECL:
10608 /* A template template parameter is encountered. */
10609 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10610 WALK_SUBTREE (TREE_TYPE (t));
10612 /* Already substituted template template parameter */
10613 *walk_subtrees = 0;
10614 break;
10616 case TYPENAME_TYPE:
10617 /* A template-id in a TYPENAME_TYPE might be a deduced context after
10618 partial instantiation. */
10619 WALK_SUBTREE (TYPENAME_TYPE_FULLNAME (t));
10620 *walk_subtrees = 0;
10621 break;
10623 case INDIRECT_REF:
10624 case COMPONENT_REF:
10625 /* If there's no type, then this thing must be some expression
10626 involving template parameters. */
10627 if (!fn && !TREE_TYPE (t))
10628 return error_mark_node;
10629 break;
10631 case CONSTRUCTOR:
10632 case TRAIT_EXPR:
10633 case PLUS_EXPR:
10634 case MULT_EXPR:
10635 case SCOPE_REF:
10636 /* These are non-deduced contexts. */
10637 if (!pfd->include_nondeduced_p)
10638 *walk_subtrees = 0;
10639 break;
10641 case MODOP_EXPR:
10642 case CAST_EXPR:
10643 case IMPLICIT_CONV_EXPR:
10644 case REINTERPRET_CAST_EXPR:
10645 case CONST_CAST_EXPR:
10646 case STATIC_CAST_EXPR:
10647 case DYNAMIC_CAST_EXPR:
10648 case ARROW_EXPR:
10649 case DOTSTAR_EXPR:
10650 case TYPEID_EXPR:
10651 case PSEUDO_DTOR_EXPR:
10652 if (!fn)
10653 return error_mark_node;
10654 break;
10656 default:
10657 break;
10660 #undef WALK_SUBTREE
10662 /* We didn't find any template parameters we liked. */
10663 out:
10664 return result;
10667 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
10668 BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
10669 call FN with the parameter and the DATA.
10670 If FN returns nonzero, the iteration is terminated, and
10671 for_each_template_parm returns 1. Otherwise, the iteration
10672 continues. If FN never returns a nonzero value, the value
10673 returned by for_each_template_parm is 0. If FN is NULL, it is
10674 considered to be the function which always returns 1.
10676 If INCLUDE_NONDEDUCED_P, then this routine will also visit template
10677 parameters that occur in non-deduced contexts. When false, only
10678 visits those template parameters that can be deduced. */
10680 static tree
10681 for_each_template_parm (tree t, tree_fn_t fn, void* data,
10682 hash_set<tree> *visited,
10683 bool include_nondeduced_p,
10684 tree_fn_t any_fn)
10686 struct pair_fn_data pfd;
10687 tree result;
10689 /* Set up. */
10690 pfd.fn = fn;
10691 pfd.any_fn = any_fn;
10692 pfd.data = data;
10693 pfd.include_nondeduced_p = include_nondeduced_p;
10695 /* Walk the tree. (Conceptually, we would like to walk without
10696 duplicates, but for_each_template_parm_r recursively calls
10697 for_each_template_parm, so we would need to reorganize a fair
10698 bit to use walk_tree_without_duplicates, so we keep our own
10699 visited list.) */
10700 if (visited)
10701 pfd.visited = visited;
10702 else
10703 pfd.visited = new hash_set<tree>;
10704 result = cp_walk_tree (&t,
10705 for_each_template_parm_r,
10706 &pfd,
10707 pfd.visited);
10709 /* Clean up. */
10710 if (!visited)
10712 delete pfd.visited;
10713 pfd.visited = 0;
10716 return result;
10719 struct find_template_parameter_info
10721 explicit find_template_parameter_info (tree ctx_parms)
10722 : ctx_parms (ctx_parms),
10723 max_depth (TMPL_PARMS_DEPTH (ctx_parms))
10726 hash_set<tree> visited;
10727 hash_set<tree> parms;
10728 tree parm_list = NULL_TREE;
10729 tree *parm_list_tail = &parm_list;
10730 tree ctx_parms;
10731 int max_depth;
10733 tree find_in (tree);
10734 tree find_in_recursive (tree);
10735 bool found (tree);
10736 unsigned num_found () { return parms.elements (); }
10739 /* Appends the declaration of T to the list in DATA. */
10741 static int
10742 keep_template_parm (tree t, void* data)
10744 find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
10746 /* Template parameters declared within the expression are not part of
10747 the parameter mapping. For example, in this concept:
10749 template<typename T>
10750 concept C = requires { <expr> } -> same_as<int>;
10752 the return specifier same_as<int> declares a new decltype parameter
10753 that must not be part of the parameter mapping. The same is true
10754 for generic lambda parameters, lambda template parameters, etc. */
10755 int level;
10756 int index;
10757 template_parm_level_and_index (t, &level, &index);
10758 if (level == 0 || level > ftpi->max_depth)
10759 return 0;
10761 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
10762 /* We want the underlying TEMPLATE_TEMPLATE_PARM, not the
10763 BOUND_TEMPLATE_TEMPLATE_PARM itself. */
10764 t = TREE_TYPE (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (t));
10766 /* This template parameter might be an argument to a cached dependent
10767 specalization that was formed earlier inside some other template, in
10768 which case the parameter is not among the ones that are in-scope.
10769 Look in CTX_PARMS to find the corresponding in-scope template
10770 parameter, and use it instead. */
10771 if (tree in_scope = corresponding_template_parameter (ftpi->ctx_parms, t))
10772 t = in_scope;
10774 /* Arguments like const T yield parameters like const T. This means that
10775 a template-id like X<T, const T> would yield two distinct parameters:
10776 T and const T. Adjust types to their unqualified versions. */
10777 if (TYPE_P (t))
10778 t = TYPE_MAIN_VARIANT (t);
10779 if (!ftpi->parms.add (t))
10781 /* Append T to PARM_LIST. */
10782 tree node = build_tree_list (NULL_TREE, t);
10783 *ftpi->parm_list_tail = node;
10784 ftpi->parm_list_tail = &TREE_CHAIN (node);
10787 /* Verify the parameter we found has a valid index. */
10788 if (flag_checking)
10790 tree parms = ftpi->ctx_parms;
10791 while (TMPL_PARMS_DEPTH (parms) > level)
10792 parms = TREE_CHAIN (parms);
10793 if (int len = TREE_VEC_LENGTH (TREE_VALUE (parms)))
10794 gcc_assert (index < len);
10797 return 0;
10800 /* Ensure that we recursively examine certain terms that are not normally
10801 visited in for_each_template_parm_r. */
10803 static int
10804 any_template_parm_r (tree t, void *data)
10806 find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
10808 #define WALK_SUBTREE(NODE) \
10809 do \
10811 for_each_template_parm (NODE, keep_template_parm, data, \
10812 &ftpi->visited, true, \
10813 any_template_parm_r); \
10815 while (0)
10817 /* A mention of a member alias/typedef is a use of all of its template
10818 arguments, including those from the enclosing class, so we don't use
10819 alias_template_specialization_p here. */
10820 if (TYPE_P (t) && typedef_variant_p (t))
10821 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
10822 WALK_SUBTREE (TI_ARGS (tinfo));
10824 switch (TREE_CODE (t))
10826 case TEMPLATE_TYPE_PARM:
10827 /* Type constraints of a placeholder type may contain parameters. */
10828 if (is_auto (t))
10829 if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (t))
10830 WALK_SUBTREE (constr);
10831 break;
10833 case TEMPLATE_ID_EXPR:
10834 /* Search through references to variable templates. */
10835 WALK_SUBTREE (TREE_OPERAND (t, 0));
10836 WALK_SUBTREE (TREE_OPERAND (t, 1));
10837 break;
10839 case TEMPLATE_PARM_INDEX:
10840 WALK_SUBTREE (TREE_TYPE (t));
10841 break;
10843 case TEMPLATE_DECL:
10844 /* If T is a member template that shares template parameters with
10845 ctx_parms, we need to mark all those parameters for mapping.
10846 To that end, it should suffice to just walk the DECL_CONTEXT of
10847 the template (assuming the template is not overly general). */
10848 WALK_SUBTREE (DECL_CONTEXT (t));
10849 break;
10851 case LAMBDA_EXPR:
10853 /* Look in the parms and body. */
10854 tree fn = lambda_function (t);
10855 WALK_SUBTREE (TREE_TYPE (fn));
10856 WALK_SUBTREE (DECL_SAVED_TREE (fn));
10858 break;
10860 case IDENTIFIER_NODE:
10861 if (IDENTIFIER_CONV_OP_P (t))
10862 /* The conversion-type-id of a conversion operator may be dependent. */
10863 WALK_SUBTREE (TREE_TYPE (t));
10864 break;
10866 case CONVERT_EXPR:
10867 if (is_dummy_object (t))
10868 WALK_SUBTREE (TREE_TYPE (t));
10869 break;
10871 default:
10872 break;
10875 /* Keep walking. */
10876 return 0;
10879 /* Look through T for template parameters. */
10881 tree
10882 find_template_parameter_info::find_in (tree t)
10884 return for_each_template_parm (t, keep_template_parm, this, &visited,
10885 /*include_nondeduced*/true,
10886 any_template_parm_r);
10889 /* As above, but also recursively look into the default arguments of template
10890 parameters we found. Used for alias CTAD. */
10892 tree
10893 find_template_parameter_info::find_in_recursive (tree t)
10895 if (tree r = find_in (t))
10896 return r;
10897 /* Since newly found parms are added to the end of the list, we
10898 can just walk it until we reach the end. */
10899 for (tree pl = parm_list; pl; pl = TREE_CHAIN (pl))
10901 tree parm = TREE_VALUE (pl);
10902 tree list = corresponding_template_parameter_list (ctx_parms, parm);
10903 if (tree r = find_in (TREE_PURPOSE (list)))
10904 return r;
10906 return NULL_TREE;
10909 /* True if PARM was found by a previous call to find_in. PARM can be a
10910 TREE_LIST, a DECL_TEMPLATE_PARM_P, or a TEMPLATE_PARM_P. */
10912 bool
10913 find_template_parameter_info::found (tree parm)
10915 if (TREE_CODE (parm) == TREE_LIST)
10916 parm = TREE_VALUE (parm);
10917 if (TREE_CODE (parm) == TYPE_DECL)
10918 parm = TREE_TYPE (parm);
10919 else
10920 parm = DECL_INITIAL (parm);
10921 gcc_checking_assert (TEMPLATE_PARM_P (parm));
10922 return parms.contains (parm);
10925 /* Returns a list of unique template parameters found within T, where CTX_PARMS
10926 are the template parameters in scope. */
10928 tree
10929 find_template_parameters (tree t, tree ctx_parms)
10931 if (!ctx_parms)
10932 return NULL_TREE;
10934 find_template_parameter_info ftpi (ctx_parms);
10935 ftpi.find_in (t);
10936 return ftpi.parm_list;
10939 /* Returns true if T depends on any template parameter. */
10941 bool
10942 uses_template_parms (tree t)
10944 if (t == NULL_TREE || t == error_mark_node)
10945 return false;
10947 /* Namespaces can't depend on any template parameters. */
10948 if (TREE_CODE (t) == NAMESPACE_DECL)
10949 return false;
10951 processing_template_decl_sentinel ptds (/*reset*/false);
10952 ++processing_template_decl;
10954 if (TYPE_P (t))
10955 return dependent_type_p (t);
10956 else if (TREE_CODE (t) == TREE_VEC)
10957 return any_dependent_template_arguments_p (t);
10958 else if (TREE_CODE (t) == TREE_LIST)
10959 return (uses_template_parms (TREE_VALUE (t))
10960 || uses_template_parms (TREE_CHAIN (t)));
10961 else if (TREE_CODE (t) == TYPE_DECL)
10962 return dependent_type_p (TREE_TYPE (t));
10963 else
10964 return instantiation_dependent_expression_p (t);
10967 /* Returns true if T depends on any template parameter with level LEVEL. */
10969 bool
10970 uses_template_parms_level (tree t, int level)
10972 return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
10973 /*include_nondeduced_p=*/true);
10976 /* Returns true if the signature of DECL depends on any template parameter from
10977 its enclosing class. */
10979 static bool
10980 uses_outer_template_parms (tree decl)
10982 int depth;
10983 if (DECL_TEMPLATE_TEMPLATE_PARM_P (decl))
10984 depth = TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl)) - 1;
10985 else
10986 depth = template_class_depth (CP_DECL_CONTEXT (decl));
10987 if (depth == 0)
10988 return false;
10989 if (for_each_template_parm (TREE_TYPE (decl), template_parm_outer_level,
10990 &depth, NULL, /*include_nondeduced_p=*/true))
10991 return true;
10992 if (PRIMARY_TEMPLATE_P (decl)
10993 || DECL_TEMPLATE_TEMPLATE_PARM_P (decl))
10995 tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (decl));
10996 for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
10998 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
10999 tree defarg = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
11000 if (TREE_CODE (parm) == PARM_DECL
11001 && for_each_template_parm (TREE_TYPE (parm),
11002 template_parm_outer_level,
11003 &depth, NULL, /*nondeduced*/true))
11004 return true;
11005 if (TREE_CODE (parm) == TEMPLATE_DECL
11006 && uses_outer_template_parms (parm))
11007 return true;
11008 if (defarg
11009 && for_each_template_parm (defarg, template_parm_outer_level,
11010 &depth, NULL, /*nondeduced*/true))
11011 return true;
11014 if (uses_outer_template_parms_in_constraints (decl))
11015 return true;
11016 return false;
11019 /* Returns true if the constraints of DECL depend on any template parameters
11020 from its enclosing scope. */
11022 bool
11023 uses_outer_template_parms_in_constraints (tree decl, tree ctx/*=NULL_TREE*/)
11025 tree ci = get_constraints (decl);
11026 if (ci)
11027 ci = CI_ASSOCIATED_CONSTRAINTS (ci);
11028 if (!ci)
11029 return false;
11030 if (!ctx)
11032 if (tree fc = DECL_FRIEND_CONTEXT (decl))
11033 ctx = fc;
11034 else
11035 ctx = CP_DECL_CONTEXT (decl);
11037 int depth = template_class_depth (ctx);
11038 if (depth == 0)
11039 return false;
11040 return for_each_template_parm (ci, template_parm_outer_level,
11041 &depth, NULL, /*nondeduced*/true);
11044 /* Returns TRUE iff INST is an instantiation we don't need to do in an
11045 ill-formed translation unit, i.e. a variable or function that isn't
11046 usable in a constant expression. */
11048 static inline bool
11049 neglectable_inst_p (tree d)
11051 return (d && DECL_P (d)
11052 && !undeduced_auto_decl (d)
11053 && !(TREE_CODE (d) == FUNCTION_DECL
11054 ? FNDECL_MANIFESTLY_CONST_EVALUATED (d)
11055 : decl_maybe_constant_var_p (d)));
11058 /* Returns TRUE iff we should refuse to instantiate DECL because it's
11059 neglectable and instantiated from within an erroneous instantiation. */
11061 static bool
11062 limit_bad_template_recursion (tree decl)
11064 struct tinst_level *lev = current_tinst_level;
11065 int errs = errorcount + sorrycount;
11066 if (errs == 0 || !neglectable_inst_p (decl))
11067 return false;
11069 /* Avoid instantiating members of an ill-formed class. */
11070 bool refuse
11071 = (DECL_CLASS_SCOPE_P (decl)
11072 && CLASSTYPE_ERRONEOUS (DECL_CONTEXT (decl)));
11074 if (!refuse)
11076 for (; lev; lev = lev->next)
11077 if (neglectable_inst_p (lev->maybe_get_node ()))
11078 break;
11079 refuse = (lev && errs > lev->errors);
11082 if (refuse)
11084 /* Don't warn about it not being defined. */
11085 suppress_warning (decl, OPT_Wunused);
11086 tree clone;
11087 FOR_EACH_CLONE (clone, decl)
11088 suppress_warning (clone, OPT_Wunused);
11090 return refuse;
11093 static int tinst_depth;
11094 extern int max_tinst_depth;
11095 int depth_reached;
11097 static GTY(()) struct tinst_level *last_error_tinst_level;
11099 /* We're starting to instantiate D; record the template instantiation context
11100 at LOC for diagnostics and to restore it later. */
11102 bool
11103 push_tinst_level_loc (tree tldcl, tree targs, location_t loc)
11105 struct tinst_level *new_level;
11107 if (tinst_depth >= max_tinst_depth)
11109 /* Tell error.cc not to try to instantiate any templates. */
11110 at_eof = 2;
11111 fatal_error (input_location,
11112 "template instantiation depth exceeds maximum of %d"
11113 " (use %<-ftemplate-depth=%> to increase the maximum)",
11114 max_tinst_depth);
11115 return false;
11118 /* If the current instantiation caused problems, don't let it instantiate
11119 anything else. Do allow deduction substitution and decls usable in
11120 constant expressions. */
11121 if (!targs && limit_bad_template_recursion (tldcl))
11123 /* Avoid no_linkage_errors and unused function (and all other)
11124 warnings for this decl. */
11125 suppress_warning (tldcl);
11126 return false;
11129 /* When not -quiet, dump template instantiations other than functions, since
11130 announce_function will take care of those. */
11131 if (!quiet_flag && !targs
11132 && TREE_CODE (tldcl) != TREE_LIST
11133 && TREE_CODE (tldcl) != FUNCTION_DECL)
11134 fprintf (stderr, " %s", decl_as_string (tldcl, TFF_DECL_SPECIFIERS));
11136 new_level = tinst_level_freelist ().alloc ();
11137 new_level->tldcl = tldcl;
11138 new_level->targs = targs;
11139 new_level->locus = loc;
11140 new_level->errors = errorcount + sorrycount;
11141 new_level->next = NULL;
11142 new_level->refcount = 0;
11143 new_level->path = new_level->visible = nullptr;
11144 set_refcount_ptr (new_level->next, current_tinst_level);
11145 set_refcount_ptr (current_tinst_level, new_level);
11147 ++tinst_depth;
11148 if (GATHER_STATISTICS && (tinst_depth > depth_reached))
11149 depth_reached = tinst_depth;
11151 return true;
11154 /* We're starting substitution of TMPL<ARGS>; record the template
11155 substitution context for diagnostics and to restore it later. */
11157 bool
11158 push_tinst_level (tree tmpl, tree args)
11160 return push_tinst_level_loc (tmpl, args, input_location);
11163 /* We're starting to instantiate D; record INPUT_LOCATION and the
11164 template instantiation context for diagnostics and to restore it
11165 later. */
11167 bool
11168 push_tinst_level (tree d)
11170 return push_tinst_level_loc (d, input_location);
11173 /* Likewise, but record LOC as the program location. */
11175 bool
11176 push_tinst_level_loc (tree d, location_t loc)
11178 gcc_assert (TREE_CODE (d) != TREE_LIST);
11179 return push_tinst_level_loc (d, NULL, loc);
11182 /* We're done instantiating this template; return to the instantiation
11183 context. */
11185 void
11186 pop_tinst_level (void)
11188 /* Restore the filename and line number stashed away when we started
11189 this instantiation. */
11190 input_location = current_tinst_level->locus;
11191 set_refcount_ptr (current_tinst_level, current_tinst_level->next);
11192 --tinst_depth;
11195 /* We're instantiating a deferred template; restore the template
11196 instantiation context in which the instantiation was requested, which
11197 is one step out from LEVEL. Return the corresponding DECL or TYPE. */
11199 static tree
11200 reopen_tinst_level (struct tinst_level *level)
11202 struct tinst_level *t;
11204 tinst_depth = 0;
11205 for (t = level; t; t = t->next)
11206 ++tinst_depth;
11208 set_refcount_ptr (current_tinst_level, level);
11209 pop_tinst_level ();
11210 if (current_tinst_level)
11211 current_tinst_level->errors = errorcount+sorrycount;
11212 return level->maybe_get_node ();
11215 /* Returns the TINST_LEVEL which gives the original instantiation
11216 context. */
11218 struct tinst_level *
11219 outermost_tinst_level (void)
11221 struct tinst_level *level = current_tinst_level;
11222 if (level)
11223 while (level->next)
11224 level = level->next;
11225 return level;
11228 /* True iff T is a friend function declaration that is not itself a template
11229 and is not defined in a class template. */
11231 bool
11232 non_templated_friend_p (tree t)
11234 if (t && TREE_CODE (t) == FUNCTION_DECL
11235 && DECL_UNIQUE_FRIEND_P (t))
11237 tree ti = DECL_TEMPLATE_INFO (t);
11238 if (!ti)
11239 return true;
11240 /* DECL_FRIEND_CONTEXT is set for a friend defined in class. */
11241 if (DECL_FRIEND_CONTEXT (t))
11242 return false;
11243 /* Non-templated friends in a class template are still represented with a
11244 TEMPLATE_DECL; check that its primary template is the befriending
11245 class. Note that DECL_PRIMARY_TEMPLATE is null for
11246 template <class T> friend A<T>::f(); */
11247 tree tmpl = TI_TEMPLATE (ti);
11248 tree primary = DECL_PRIMARY_TEMPLATE (tmpl);
11249 return (primary && primary != tmpl);
11251 else
11252 return false;
11255 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL. ARGS is the
11256 vector of template arguments, as for tsubst.
11258 Returns an appropriate tsubst'd friend declaration. */
11260 static tree
11261 tsubst_friend_function (tree decl, tree args)
11263 tree new_friend;
11265 if (TREE_CODE (decl) == FUNCTION_DECL
11266 && DECL_TEMPLATE_INSTANTIATION (decl)
11267 && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
11268 /* This was a friend declared with an explicit template
11269 argument list, e.g.:
11271 friend void f<>(T);
11273 to indicate that f was a template instantiation, not a new
11274 function declaration. Now, we have to figure out what
11275 instantiation of what template. */
11277 tree template_id, arglist, fns;
11278 tree new_args;
11279 tree tmpl;
11280 tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
11282 /* Friend functions are looked up in the containing namespace scope.
11283 We must enter that scope, to avoid finding member functions of the
11284 current class with same name. */
11285 push_nested_namespace (ns);
11286 fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
11287 tf_warning_or_error, NULL_TREE);
11288 pop_nested_namespace (ns);
11289 arglist = tsubst (DECL_TI_ARGS (decl), args,
11290 tf_warning_or_error, NULL_TREE);
11291 template_id = lookup_template_function (fns, arglist);
11293 new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
11294 tmpl = determine_specialization (template_id, new_friend,
11295 &new_args,
11296 /*need_member_template=*/0,
11297 TREE_VEC_LENGTH (args),
11298 tsk_none);
11299 return instantiate_template (tmpl, new_args, tf_error);
11302 new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
11303 if (new_friend == error_mark_node)
11304 return error_mark_node;
11306 /* The NEW_FRIEND will look like an instantiation, to the
11307 compiler, but is not an instantiation from the point of view of
11308 the language. For example, we might have had:
11310 template <class T> struct S {
11311 template <class U> friend void f(T, U);
11314 Then, in S<int>, template <class U> void f(int, U) is not an
11315 instantiation of anything. */
11317 DECL_USE_TEMPLATE (new_friend) = 0;
11318 if (TREE_CODE (new_friend) == TEMPLATE_DECL)
11320 DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (new_friend) = false;
11321 DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
11322 DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
11323 = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
11325 /* Substitute TEMPLATE_PARMS_CONSTRAINTS so that parameter levels will
11326 match in decls_match. */
11327 tree parms = DECL_TEMPLATE_PARMS (new_friend);
11328 tree treqs = TEMPLATE_PARMS_CONSTRAINTS (parms);
11329 treqs = maybe_substitute_reqs_for (treqs, new_friend);
11330 if (treqs != TEMPLATE_PARMS_CONSTRAINTS (parms))
11332 TEMPLATE_PARMS_CONSTRAINTS (parms) = treqs;
11333 /* As well as each TEMPLATE_PARM_CONSTRAINTS. */
11334 tsubst_each_template_parm_constraints (parms, args,
11335 tf_warning_or_error);
11339 /* The mangled name for the NEW_FRIEND is incorrect. The function
11340 is not a template instantiation and should not be mangled like
11341 one. Therefore, we forget the mangling here; we'll recompute it
11342 later if we need it. */
11343 if (TREE_CODE (new_friend) != TEMPLATE_DECL)
11345 SET_DECL_RTL (new_friend, NULL);
11346 SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
11349 if (DECL_NAMESPACE_SCOPE_P (new_friend))
11351 tree old_decl;
11352 tree ns;
11354 /* We must save some information from NEW_FRIEND before calling
11355 duplicate decls since that function will free NEW_FRIEND if
11356 possible. */
11357 tree new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
11358 tree new_friend_result_template_info = NULL_TREE;
11359 bool new_friend_is_defn =
11360 (new_friend_template_info
11361 && (DECL_INITIAL (DECL_TEMPLATE_RESULT
11362 (template_for_substitution (new_friend)))
11363 != NULL_TREE));
11364 tree not_tmpl = new_friend;
11366 if (TREE_CODE (new_friend) == TEMPLATE_DECL)
11368 /* This declaration is a `primary' template. */
11369 DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
11371 not_tmpl = DECL_TEMPLATE_RESULT (new_friend);
11372 new_friend_result_template_info = DECL_TEMPLATE_INFO (not_tmpl);
11375 /* Inside pushdecl_namespace_level, we will push into the
11376 current namespace. However, the friend function should go
11377 into the namespace of the template. */
11378 ns = decl_namespace_context (new_friend);
11379 push_nested_namespace (ns);
11380 old_decl = pushdecl_namespace_level (new_friend, /*hiding=*/true);
11381 pop_nested_namespace (ns);
11383 if (old_decl == error_mark_node)
11384 return error_mark_node;
11386 if (old_decl != new_friend)
11388 /* This new friend declaration matched an existing
11389 declaration. For example, given:
11391 template <class T> void f(T);
11392 template <class U> class C {
11393 template <class T> friend void f(T) {}
11396 the friend declaration actually provides the definition
11397 of `f', once C has been instantiated for some type. So,
11398 old_decl will be the out-of-class template declaration,
11399 while new_friend is the in-class definition.
11401 But, if `f' was called before this point, the
11402 instantiation of `f' will have DECL_TI_ARGS corresponding
11403 to `T' but not to `U', references to which might appear
11404 in the definition of `f'. Previously, the most general
11405 template for an instantiation of `f' was the out-of-class
11406 version; now it is the in-class version. Therefore, we
11407 run through all specialization of `f', adding to their
11408 DECL_TI_ARGS appropriately. In particular, they need a
11409 new set of outer arguments, corresponding to the
11410 arguments for this class instantiation.
11412 The same situation can arise with something like this:
11414 friend void f(int);
11415 template <class T> class C {
11416 friend void f(T) {}
11419 when `C<int>' is instantiated. Now, `f(int)' is defined
11420 in the class. */
11422 if (!new_friend_is_defn)
11423 /* On the other hand, if the in-class declaration does
11424 *not* provide a definition, then we don't want to alter
11425 existing definitions. We can just leave everything
11426 alone. */
11428 else
11430 tree new_template = TI_TEMPLATE (new_friend_template_info);
11431 tree new_args = TI_ARGS (new_friend_template_info);
11433 /* Overwrite whatever template info was there before, if
11434 any, with the new template information pertaining to
11435 the declaration. */
11436 DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
11438 if (TREE_CODE (old_decl) != TEMPLATE_DECL)
11440 /* We should have called reregister_specialization in
11441 duplicate_decls. */
11442 gcc_assert (retrieve_specialization (new_template,
11443 new_args, 0)
11444 == old_decl);
11446 /* Instantiate it if the global has already been used. */
11447 if (DECL_ODR_USED (old_decl))
11448 instantiate_decl (old_decl, /*defer_ok=*/true,
11449 /*expl_inst_class_mem_p=*/false);
11451 else
11453 tree t;
11455 /* Indicate that the old function template is a partial
11456 instantiation. */
11457 DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
11458 = new_friend_result_template_info;
11460 gcc_assert (new_template
11461 == most_general_template (new_template));
11462 gcc_assert (new_template != old_decl);
11464 /* Reassign any specializations already in the hash table
11465 to the new more general template, and add the
11466 additional template args. */
11467 for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
11468 t != NULL_TREE;
11469 t = TREE_CHAIN (t))
11471 tree spec = TREE_VALUE (t);
11472 spec_entry elt;
11474 elt.tmpl = old_decl;
11475 elt.args = DECL_TI_ARGS (spec);
11476 elt.spec = NULL_TREE;
11478 decl_specializations->remove_elt (&elt);
11480 DECL_TI_ARGS (spec)
11481 = add_outermost_template_args (new_args,
11482 DECL_TI_ARGS (spec));
11484 register_specialization
11485 (spec, new_template, DECL_TI_ARGS (spec), true, 0);
11488 DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
11492 /* The information from NEW_FRIEND has been merged into OLD_DECL
11493 by duplicate_decls. */
11494 new_friend = old_decl;
11497 /* We've just introduced a namespace-scope function in the purview
11498 without necessarily having opened the enclosing namespace, so
11499 make sure the namespace is in the purview now too. */
11500 if (modules_p ()
11501 && DECL_MODULE_PURVIEW_P (STRIP_TEMPLATE (new_friend))
11502 && TREE_CODE (DECL_CONTEXT (new_friend)) == NAMESPACE_DECL)
11503 DECL_MODULE_PURVIEW_P (DECL_CONTEXT (new_friend)) = true;
11505 else
11507 tree context = DECL_CONTEXT (new_friend);
11508 bool dependent_p;
11510 /* In the code
11511 template <class T> class C {
11512 template <class U> friend void C1<U>::f (); // case 1
11513 friend void C2<T>::f (); // case 2
11515 we only need to make sure CONTEXT is a complete type for
11516 case 2. To distinguish between the two cases, we note that
11517 CONTEXT of case 1 remains dependent type after tsubst while
11518 this isn't true for case 2. */
11519 ++processing_template_decl;
11520 dependent_p = dependent_type_p (context);
11521 --processing_template_decl;
11523 if (!dependent_p
11524 && !complete_type_or_else (context, NULL_TREE))
11525 return error_mark_node;
11527 if (COMPLETE_TYPE_P (context))
11529 tree fn = new_friend;
11530 /* do_friend adds the TEMPLATE_DECL for any member friend
11531 template even if it isn't a member template, i.e.
11532 template <class T> friend A<T>::f();
11533 Look through it in that case. */
11534 if (TREE_CODE (fn) == TEMPLATE_DECL
11535 && !PRIMARY_TEMPLATE_P (fn))
11536 fn = DECL_TEMPLATE_RESULT (fn);
11537 /* Check to see that the declaration is really present, and,
11538 possibly obtain an improved declaration. */
11539 fn = check_classfn (context, fn, NULL_TREE);
11541 if (fn)
11542 new_friend = fn;
11546 return new_friend;
11549 /* FRIEND_TMPL is a friend TEMPLATE_DECL. ARGS is the vector of
11550 template arguments, as for tsubst.
11552 Returns an appropriate tsubst'd friend type or error_mark_node on
11553 failure. */
11555 static tree
11556 tsubst_friend_class (tree friend_tmpl, tree args)
11558 tree tmpl;
11560 if (DECL_TEMPLATE_TEMPLATE_PARM_P (friend_tmpl))
11562 tmpl = tsubst (TREE_TYPE (friend_tmpl), args, tf_none, NULL_TREE);
11563 return TREE_TYPE (tmpl);
11566 tree context = CP_DECL_CONTEXT (friend_tmpl);
11567 if (TREE_CODE (context) == NAMESPACE_DECL)
11568 push_nested_namespace (context);
11569 else
11571 context = tsubst (context, args, tf_error, NULL_TREE);
11572 push_nested_class (context);
11575 tmpl = lookup_name (DECL_NAME (friend_tmpl), LOOK_where::CLASS_NAMESPACE,
11576 LOOK_want::NORMAL | LOOK_want::HIDDEN_FRIEND);
11578 if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
11580 /* The friend template has already been declared. Just
11581 check to see that the declarations match, and install any new
11582 default parameters. We must tsubst the default parameters,
11583 of course. We only need the innermost template parameters
11584 because that is all that redeclare_class_template will look
11585 at. */
11586 if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
11587 > TMPL_ARGS_DEPTH (args))
11589 tree parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
11590 args, tf_warning_or_error);
11591 tsubst_each_template_parm_constraints (parms, args,
11592 tf_warning_or_error);
11593 location_t saved_input_location = input_location;
11594 input_location = DECL_SOURCE_LOCATION (friend_tmpl);
11595 tree cons = get_constraints (friend_tmpl);
11596 ++processing_template_decl;
11597 cons = tsubst_constraint_info (cons, args, tf_warning_or_error,
11598 DECL_FRIEND_CONTEXT (friend_tmpl));
11599 --processing_template_decl;
11600 redeclare_class_template (TREE_TYPE (tmpl), parms, cons);
11601 input_location = saved_input_location;
11604 else
11606 /* The friend template has not already been declared. In this
11607 case, the instantiation of the template class will cause the
11608 injection of this template into the namespace scope. */
11609 tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
11611 if (tmpl != error_mark_node)
11613 /* The new TMPL is not an instantiation of anything, so we
11614 forget its origins. We don't reset CLASSTYPE_TI_TEMPLATE
11615 for the new type because that is supposed to be the
11616 corresponding template decl, i.e., TMPL. */
11617 DECL_USE_TEMPLATE (tmpl) = 0;
11618 DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
11619 CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
11620 CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
11621 = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
11623 /* Substitute into and set the constraints on the new declaration. */
11624 if (tree ci = get_constraints (friend_tmpl))
11626 ++processing_template_decl;
11627 ci = tsubst_constraint_info (ci, args, tf_warning_or_error,
11628 DECL_FRIEND_CONTEXT (friend_tmpl));
11629 --processing_template_decl;
11630 set_constraints (tmpl, ci);
11631 tsubst_each_template_parm_constraints (DECL_TEMPLATE_PARMS (tmpl),
11632 args, tf_warning_or_error);
11635 /* Inject this template into the enclosing namspace scope. */
11636 tmpl = pushdecl_namespace_level (tmpl, /*hiding=*/true);
11640 if (TREE_CODE (context) == NAMESPACE_DECL)
11641 pop_nested_namespace (context);
11642 else
11643 pop_nested_class ();
11645 return TREE_TYPE (tmpl);
11648 /* Returns zero if TYPE cannot be completed later due to circularity.
11649 Otherwise returns one. */
11651 static int
11652 can_complete_type_without_circularity (tree type)
11654 if (type == NULL_TREE || type == error_mark_node)
11655 return 0;
11656 else if (COMPLETE_TYPE_P (type))
11657 return 1;
11658 else if (TREE_CODE (type) == ARRAY_TYPE)
11659 return can_complete_type_without_circularity (TREE_TYPE (type));
11660 else if (CLASS_TYPE_P (type)
11661 && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
11662 return 0;
11663 else
11664 return 1;
11667 static tree tsubst_omp_clauses (tree, enum c_omp_region_type, tree,
11668 tsubst_flags_t, tree);
11670 /* Instantiate the contract statement. */
11672 static tree
11673 tsubst_contract (tree decl, tree t, tree args, tsubst_flags_t complain,
11674 tree in_decl)
11676 tree type = decl ? TREE_TYPE (TREE_TYPE (decl)) : NULL_TREE;
11677 bool auto_p = type_uses_auto (type);
11679 tree r = copy_node (t);
11681 /* Rebuild the result variable. */
11682 if (type && POSTCONDITION_P (t) && POSTCONDITION_IDENTIFIER (t))
11684 tree oldvar = POSTCONDITION_IDENTIFIER (t);
11686 tree newvar = copy_node (oldvar);
11687 TREE_TYPE (newvar) = type;
11688 DECL_CONTEXT (newvar) = decl;
11689 POSTCONDITION_IDENTIFIER (r) = newvar;
11691 /* Make sure the postcondition is valid. */
11692 location_t loc = DECL_SOURCE_LOCATION (oldvar);
11693 if (!auto_p)
11694 if (!check_postcondition_result (decl, type, loc))
11695 return invalidate_contract (r);
11697 /* Make the variable available for lookup. */
11698 register_local_specialization (newvar, oldvar);
11701 /* Instantiate the condition. If the return type is undeduced, process
11702 the expression as if inside a template to avoid spurious type errors. */
11703 if (auto_p)
11704 ++processing_template_decl;
11705 ++processing_contract_condition;
11706 CONTRACT_CONDITION (r)
11707 = tsubst_expr (CONTRACT_CONDITION (t), args, complain, in_decl);
11708 --processing_contract_condition;
11709 if (auto_p)
11710 --processing_template_decl;
11712 /* And the comment. */
11713 CONTRACT_COMMENT (r)
11714 = tsubst_expr (CONTRACT_COMMENT (r), args, complain, in_decl);
11716 return r;
11719 /* Update T by instantiating its contract attribute. */
11721 static void
11722 tsubst_contract_attribute (tree decl, tree t, tree args,
11723 tsubst_flags_t complain, tree in_decl)
11725 /* For non-specializations, adjust the current declaration to the most general
11726 version of in_decl. Because we defer the instantiation of contracts as long
11727 as possible, they are still written in terms of the parameters (and return
11728 type) of the most general template. */
11729 tree tmpl = DECL_TI_TEMPLATE (in_decl);
11730 if (!DECL_TEMPLATE_SPECIALIZATION (tmpl))
11731 in_decl = DECL_TEMPLATE_RESULT (most_general_template (in_decl));
11732 local_specialization_stack specs (lss_copy);
11733 register_parameter_specializations (in_decl, decl);
11735 /* Get the contract to be instantiated. */
11736 tree contract = CONTRACT_STATEMENT (t);
11738 /* Use the complete set of template arguments for instantiation. The
11739 contract may not have been instantiated and still refer to outer levels
11740 of template parameters. */
11741 args = DECL_TI_ARGS (decl);
11743 /* For member functions, make this available for semantic analysis. */
11744 tree save_ccp = current_class_ptr;
11745 tree save_ccr = current_class_ref;
11746 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
11748 tree arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
11749 tree this_type = TREE_TYPE (TREE_VALUE (arg_types));
11750 inject_this_parameter (this_type, cp_type_quals (this_type));
11753 contract = tsubst_contract (decl, contract, args, complain, in_decl);
11755 current_class_ptr = save_ccp;
11756 current_class_ref = save_ccr;
11758 /* Rebuild the attribute. */
11759 TREE_VALUE (t) = build_tree_list (NULL_TREE, contract);
11762 /* Rebuild the attribute list for DECL, substituting into contracts
11763 as needed. */
11765 void
11766 tsubst_contract_attributes (tree decl, tree args, tsubst_flags_t complain, tree in_decl)
11768 tree list = copy_list (DECL_ATTRIBUTES (decl));
11769 for (tree attr = list; attr; attr = CONTRACT_CHAIN (attr))
11771 if (cxx_contract_attribute_p (attr))
11772 tsubst_contract_attribute (decl, attr, args, complain, in_decl);
11774 DECL_ATTRIBUTES (decl) = list;
11777 /* Instantiate a single dependent attribute T (a TREE_LIST), and return either
11778 T or a new TREE_LIST, possibly a chain in the case of a pack expansion. */
11780 static tree
11781 tsubst_attribute (tree t, tree *decl_p, tree args,
11782 tsubst_flags_t complain, tree in_decl)
11784 gcc_assert (ATTR_IS_DEPENDENT (t));
11786 /* Note that contract attributes are never substituted from this function.
11787 Their instantiation is triggered by regenerate_from_template_decl when
11788 we instantiate the body of the function. */
11790 tree val = TREE_VALUE (t);
11791 if (val == NULL_TREE)
11792 /* Nothing to do. */;
11793 else if ((flag_openmp || flag_openmp_simd)
11794 && is_attribute_p ("omp declare simd",
11795 get_attribute_name (t)))
11797 tree clauses = TREE_VALUE (val);
11798 clauses = tsubst_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD, args,
11799 complain, in_decl);
11800 c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
11801 clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
11802 tree parms = DECL_ARGUMENTS (*decl_p);
11803 clauses
11804 = c_omp_declare_simd_clauses_to_numbers (parms, clauses);
11805 if (clauses)
11806 val = build_tree_list (NULL_TREE, clauses);
11807 else
11808 val = NULL_TREE;
11810 else if (flag_openmp
11811 && is_attribute_p ("omp declare variant base",
11812 get_attribute_name (t)))
11814 ++cp_unevaluated_operand;
11815 tree varid = tsubst_expr (TREE_PURPOSE (val), args, complain, in_decl);
11816 --cp_unevaluated_operand;
11817 tree chain = TREE_CHAIN (val);
11818 location_t match_loc = cp_expr_loc_or_input_loc (TREE_PURPOSE (chain));
11819 tree ctx = copy_list (TREE_VALUE (val));
11820 tree simd = get_identifier ("simd");
11821 tree score = get_identifier (" score");
11822 tree condition = get_identifier ("condition");
11823 for (tree t1 = ctx; t1; t1 = TREE_CHAIN (t1))
11825 const char *set = IDENTIFIER_POINTER (TREE_PURPOSE (t1));
11826 TREE_VALUE (t1) = copy_list (TREE_VALUE (t1));
11827 for (tree t2 = TREE_VALUE (t1); t2; t2 = TREE_CHAIN (t2))
11829 if (TREE_PURPOSE (t2) == simd && set[0] == 'c')
11831 tree clauses = TREE_VALUE (t2);
11832 clauses = tsubst_omp_clauses (clauses,
11833 C_ORT_OMP_DECLARE_SIMD, args,
11834 complain, in_decl);
11835 c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
11836 clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
11837 TREE_VALUE (t2) = clauses;
11839 else
11841 TREE_VALUE (t2) = copy_list (TREE_VALUE (t2));
11842 for (tree t3 = TREE_VALUE (t2); t3; t3 = TREE_CHAIN (t3))
11843 if (TREE_VALUE (t3))
11845 bool allow_string
11846 = ((TREE_PURPOSE (t2) != condition || set[0] != 'u')
11847 && TREE_PURPOSE (t3) != score);
11848 tree v = TREE_VALUE (t3);
11849 if (TREE_CODE (v) == STRING_CST && allow_string)
11850 continue;
11851 v = tsubst_expr (v, args, complain, in_decl);
11852 v = fold_non_dependent_expr (v);
11853 if (!INTEGRAL_TYPE_P (TREE_TYPE (v))
11854 || (TREE_PURPOSE (t3) == score
11855 ? TREE_CODE (v) != INTEGER_CST
11856 : !tree_fits_shwi_p (v)))
11858 location_t loc
11859 = cp_expr_loc_or_loc (TREE_VALUE (t3),
11860 match_loc);
11861 if (TREE_PURPOSE (t3) == score)
11862 error_at (loc, "score argument must be "
11863 "constant integer expression");
11864 else if (allow_string)
11865 error_at (loc, "property must be constant "
11866 "integer expression or string "
11867 "literal");
11868 else
11869 error_at (loc, "property must be constant "
11870 "integer expression");
11871 return NULL_TREE;
11873 else if (TREE_PURPOSE (t3) == score
11874 && tree_int_cst_sgn (v) < 0)
11876 location_t loc
11877 = cp_expr_loc_or_loc (TREE_VALUE (t3),
11878 match_loc);
11879 error_at (loc, "score argument must be "
11880 "non-negative");
11881 return NULL_TREE;
11883 TREE_VALUE (t3) = v;
11888 val = tree_cons (varid, ctx, chain);
11890 /* If the first attribute argument is an identifier, don't
11891 pass it through tsubst. Attributes like mode, format,
11892 cleanup and several target specific attributes expect it
11893 unmodified. */
11894 else if (attribute_takes_identifier_p (get_attribute_name (t)))
11896 tree chain
11897 = tsubst_expr (TREE_CHAIN (val), args, complain, in_decl);
11898 if (chain != TREE_CHAIN (val))
11899 val = tree_cons (NULL_TREE, TREE_VALUE (val), chain);
11901 else if (PACK_EXPANSION_P (val))
11903 /* An attribute pack expansion. */
11904 tree purp = TREE_PURPOSE (t);
11905 tree pack = tsubst_pack_expansion (val, args, complain, in_decl);
11906 if (pack == error_mark_node)
11907 return error_mark_node;
11908 int len = TREE_VEC_LENGTH (pack);
11909 tree list = NULL_TREE;
11910 tree *q = &list;
11911 for (int i = 0; i < len; ++i)
11913 tree elt = TREE_VEC_ELT (pack, i);
11914 *q = build_tree_list (purp, elt);
11915 q = &TREE_CHAIN (*q);
11917 return list;
11919 else
11920 val = tsubst_expr (val, args, complain, in_decl);
11922 if (val == error_mark_node)
11923 return error_mark_node;
11924 if (val != TREE_VALUE (t))
11925 return build_tree_list (TREE_PURPOSE (t), val);
11926 return t;
11929 /* Instantiate any dependent attributes in ATTRIBUTES, returning either it
11930 unchanged or a new TREE_LIST chain. */
11932 static tree
11933 tsubst_attributes (tree attributes, tree args,
11934 tsubst_flags_t complain, tree in_decl)
11936 tree last_dep = NULL_TREE;
11938 for (tree t = attributes; t; t = TREE_CHAIN (t))
11939 if (ATTR_IS_DEPENDENT (t))
11941 last_dep = t;
11942 attributes = copy_list (attributes);
11943 break;
11946 if (last_dep)
11947 for (tree *p = &attributes; *p; )
11949 tree t = *p;
11950 if (ATTR_IS_DEPENDENT (t))
11952 tree subst = tsubst_attribute (t, NULL, args, complain, in_decl);
11953 if (subst != t)
11955 *p = subst;
11956 while (*p)
11957 p = &TREE_CHAIN (*p);
11958 *p = TREE_CHAIN (t);
11959 continue;
11962 p = &TREE_CHAIN (*p);
11965 return attributes;
11968 /* Apply any attributes which had to be deferred until instantiation
11969 time. DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
11970 ARGS, COMPLAIN, IN_DECL are as tsubst. Returns true normally,
11971 false on error. */
11973 static bool
11974 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
11975 tree args, tsubst_flags_t complain, tree in_decl)
11977 tree t;
11978 tree *p;
11980 if (attributes == NULL_TREE)
11981 return true;
11983 if (DECL_P (*decl_p))
11985 if (TREE_TYPE (*decl_p) == error_mark_node)
11986 return false;
11987 p = &DECL_ATTRIBUTES (*decl_p);
11988 /* DECL_ATTRIBUTES comes from copy_node in tsubst_decl, and is identical
11989 to our attributes parameter. */
11990 gcc_assert (*p == attributes);
11992 else
11994 p = &TYPE_ATTRIBUTES (*decl_p);
11995 /* TYPE_ATTRIBUTES was set up (with abi_tag and may_alias) in
11996 lookup_template_class_1, and should be preserved. */
11997 gcc_assert (*p != attributes);
11998 while (*p)
11999 p = &TREE_CHAIN (*p);
12002 /* save_template_attributes puts the dependent attributes at the beginning of
12003 the list; find the non-dependent ones. */
12004 for (t = attributes; t; t = TREE_CHAIN (t))
12005 if (!ATTR_IS_DEPENDENT (t))
12006 break;
12007 tree nondep = t;
12009 /* Apply any non-dependent attributes. */
12010 *p = nondep;
12012 if (nondep == attributes)
12013 return true;
12015 /* And then any dependent ones. */
12016 tree late_attrs = NULL_TREE;
12017 tree *q = &late_attrs;
12018 for (t = attributes; t != nondep; t = TREE_CHAIN (t))
12020 *q = tsubst_attribute (t, decl_p, args, complain, in_decl);
12021 if (*q == error_mark_node)
12022 return false;
12023 if (*q == t)
12025 *q = copy_node (t);
12026 TREE_CHAIN (*q) = NULL_TREE;
12028 while (*q)
12029 q = &TREE_CHAIN (*q);
12032 /* cplus_decl_attributes can add some attributes implicitly. For templates,
12033 those attributes should have been added already when those templates were
12034 parsed, and shouldn't be added based on from which context they are
12035 first time instantiated. */
12036 auto o1 = make_temp_override (current_optimize_pragma, NULL_TREE);
12037 auto o2 = make_temp_override (optimization_current_node,
12038 optimization_default_node);
12039 auto o3 = make_temp_override (current_target_pragma, NULL_TREE);
12040 auto o4 = make_temp_override (scope_chain->omp_declare_target_attribute,
12041 NULL);
12042 auto o5 = make_temp_override (scope_chain->omp_begin_assumes, NULL);
12044 cplus_decl_attributes (decl_p, late_attrs, attr_flags);
12046 return true;
12049 /* The template TMPL is being instantiated with the template arguments TARGS.
12050 Perform the access checks that we deferred when parsing the template. */
12052 static void
12053 perform_instantiation_time_access_checks (tree tmpl, tree targs)
12055 unsigned i;
12056 deferred_access_check *chk;
12058 if (!CLASS_TYPE_P (tmpl) && TREE_CODE (tmpl) != FUNCTION_DECL)
12059 return;
12061 if (vec<deferred_access_check, va_gc> *access_checks
12062 = TI_DEFERRED_ACCESS_CHECKS (get_template_info (tmpl)))
12063 FOR_EACH_VEC_ELT (*access_checks, i, chk)
12065 tree decl = chk->decl;
12066 tree diag_decl = chk->diag_decl;
12067 tree type_scope = TREE_TYPE (chk->binfo);
12069 if (uses_template_parms (type_scope))
12070 type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
12072 /* Make access check error messages point to the location
12073 of the use of the typedef. */
12074 iloc_sentinel ils (chk->loc);
12075 perform_or_defer_access_check (TYPE_BINFO (type_scope),
12076 decl, diag_decl, tf_warning_or_error);
12080 tree
12081 instantiate_class_template (tree type)
12083 auto_timevar tv (TV_TEMPLATE_INST);
12085 tree templ, args, pattern, t, member;
12086 tree typedecl;
12087 tree pbinfo;
12088 tree base_list;
12089 unsigned int saved_maximum_field_alignment;
12090 tree fn_context;
12092 if (type == error_mark_node)
12093 return error_mark_node;
12095 if (COMPLETE_OR_OPEN_TYPE_P (type)
12096 || (uses_template_parms (type)
12097 && !TYPE_FUNCTION_SCOPE_P (type)))
12098 return type;
12100 /* Figure out which template is being instantiated. */
12101 templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
12102 gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
12104 /* Mark the type as in the process of being defined. */
12105 TYPE_BEING_DEFINED (type) = 1;
12107 /* We may be in the middle of deferred access check. Disable
12108 it now. */
12109 deferring_access_check_sentinel acs (dk_no_deferred);
12111 /* Determine what specialization of the original template to
12112 instantiate. */
12113 t = most_specialized_partial_spec (type, tf_warning_or_error);
12114 if (t == error_mark_node)
12115 return error_mark_node;
12116 else if (t)
12118 /* This TYPE is actually an instantiation of a partial
12119 specialization. We replace the innermost set of ARGS with
12120 the arguments appropriate for substitution. For example,
12121 given:
12123 template <class T> struct S {};
12124 template <class T> struct S<T*> {};
12126 and supposing that we are instantiating S<int*>, ARGS will
12127 presently be {int*} -- but we need {int}. */
12128 pattern = TREE_TYPE (TI_TEMPLATE (t));
12129 args = TI_ARGS (t);
12131 else
12133 pattern = TREE_TYPE (templ);
12134 args = CLASSTYPE_TI_ARGS (type);
12137 /* If the template we're instantiating is incomplete, then clearly
12138 there's nothing we can do. */
12139 if (!COMPLETE_TYPE_P (pattern))
12141 /* We can try again later. */
12142 TYPE_BEING_DEFINED (type) = 0;
12143 return type;
12146 /* If we've recursively instantiated too many templates, stop. */
12147 if (! push_tinst_level (type))
12148 return type;
12150 int saved_unevaluated_operand = cp_unevaluated_operand;
12151 int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
12153 fn_context = decl_function_context (TYPE_MAIN_DECL (type));
12154 /* Also avoid push_to_top_level for a lambda in an NSDMI. */
12155 if (!fn_context && LAMBDA_TYPE_P (type) && TYPE_CLASS_SCOPE_P (type))
12156 fn_context = error_mark_node;
12157 if (!fn_context)
12158 push_to_top_level ();
12159 else
12161 cp_unevaluated_operand = 0;
12162 c_inhibit_evaluation_warnings = 0;
12165 mark_template_arguments_used (templ, CLASSTYPE_TI_ARGS (type));
12167 /* Use #pragma pack from the template context. */
12168 saved_maximum_field_alignment = maximum_field_alignment;
12169 maximum_field_alignment = TYPE_PRECISION (pattern);
12171 SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
12173 /* Set the input location to the most specialized template definition.
12174 This is needed if tsubsting causes an error. */
12175 typedecl = TYPE_MAIN_DECL (pattern);
12176 input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
12177 DECL_SOURCE_LOCATION (typedecl);
12179 set_instantiating_module (TYPE_NAME (type));
12181 TYPE_PACKED (type) = TYPE_PACKED (pattern);
12182 SET_TYPE_ALIGN (type, TYPE_ALIGN (pattern));
12183 TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
12184 CLASSTYPE_NON_AGGREGATE (type) = CLASSTYPE_NON_AGGREGATE (pattern);
12185 if (ANON_AGGR_TYPE_P (pattern))
12186 SET_ANON_AGGR_TYPE_P (type);
12187 if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
12189 CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
12190 CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
12191 /* Adjust visibility for template arguments. */
12192 determine_visibility (TYPE_MAIN_DECL (type));
12194 if (CLASS_TYPE_P (type))
12195 CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
12197 pbinfo = TYPE_BINFO (pattern);
12199 /* We should never instantiate a nested class before its enclosing
12200 class; we need to look up the nested class by name before we can
12201 instantiate it, and that lookup should instantiate the enclosing
12202 class. */
12203 gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
12204 || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
12206 base_list = NULL_TREE;
12207 /* Defer access checking while we substitute into the types named in
12208 the base-clause. */
12209 push_deferring_access_checks (dk_deferred);
12210 if (BINFO_N_BASE_BINFOS (pbinfo))
12212 tree pbase_binfo;
12213 int i;
12215 /* Substitute into each of the bases to determine the actual
12216 basetypes. */
12217 for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
12219 tree base;
12220 tree access = BINFO_BASE_ACCESS (pbinfo, i);
12221 tree expanded_bases = NULL_TREE;
12222 int idx, len = 1;
12224 if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
12226 expanded_bases =
12227 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
12228 args, tf_error, NULL_TREE);
12229 if (expanded_bases == error_mark_node)
12230 continue;
12232 len = TREE_VEC_LENGTH (expanded_bases);
12235 for (idx = 0; idx < len; idx++)
12237 if (expanded_bases)
12238 /* Extract the already-expanded base class. */
12239 base = TREE_VEC_ELT (expanded_bases, idx);
12240 else
12241 /* Substitute to figure out the base class. */
12242 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error,
12243 NULL_TREE);
12245 if (base == error_mark_node)
12246 continue;
12248 base_list = tree_cons (access, base, base_list);
12249 if (BINFO_VIRTUAL_P (pbase_binfo))
12250 TREE_TYPE (base_list) = integer_type_node;
12254 /* The list is now in reverse order; correct that. */
12255 base_list = nreverse (base_list);
12257 /* Now call xref_basetypes to set up all the base-class
12258 information. */
12259 xref_basetypes (type, base_list);
12261 apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
12262 (int) ATTR_FLAG_TYPE_IN_PLACE,
12263 args, tf_error, NULL_TREE);
12264 fixup_attribute_variants (type);
12266 /* Now that our base classes are set up, enter the scope of the
12267 class, so that name lookups into base classes, etc. will work
12268 correctly. This is precisely analogous to what we do in
12269 begin_class_definition when defining an ordinary non-template
12270 class, except we also need to push the enclosing classes. */
12271 push_nested_class (type);
12273 /* Now check accessibility of the types named in its base-clause,
12274 relative to the scope of the class. */
12275 pop_to_parent_deferring_access_checks ();
12277 /* A vector to hold members marked with attribute used. */
12278 auto_vec<tree> used;
12280 /* Now members are processed in the order of declaration. */
12281 for (member = CLASSTYPE_DECL_LIST (pattern);
12282 member; member = TREE_CHAIN (member))
12284 tree t = TREE_VALUE (member);
12286 if (TREE_PURPOSE (member))
12288 if (TYPE_P (t))
12290 if (LAMBDA_TYPE_P (t))
12291 /* A closure type for a lambda in an NSDMI or default argument.
12292 Ignore it; it will be regenerated when needed. */
12293 continue;
12295 /* If the member is a class template, we've
12296 already substituted its type. */
12297 if (CLASS_TYPE_P (t)
12298 && CLASSTYPE_IS_TEMPLATE (t))
12299 continue;
12301 tree newtag = tsubst (t, args, tf_error, NULL_TREE);
12302 if (newtag == error_mark_node)
12303 continue;
12305 if (TREE_CODE (newtag) != ENUMERAL_TYPE)
12307 tree name = TYPE_IDENTIFIER (t);
12309 /* Now, install the tag. We don't use pushtag
12310 because that does too much work -- creating an
12311 implicit typedef, which we've already done. */
12312 set_identifier_type_value (name, TYPE_NAME (newtag));
12313 maybe_add_class_template_decl_list (type, newtag, false);
12314 TREE_PUBLIC (TYPE_NAME (newtag)) = true;
12315 determine_visibility (TYPE_NAME (newtag));
12318 else if (DECL_DECLARES_FUNCTION_P (t))
12320 tree r;
12322 if (TREE_CODE (t) == TEMPLATE_DECL)
12323 ++processing_template_decl;
12324 r = tsubst (t, args, tf_error, NULL_TREE);
12325 if (TREE_CODE (t) == TEMPLATE_DECL)
12326 --processing_template_decl;
12328 set_current_access_from_decl (r);
12329 finish_member_declaration (r);
12330 /* Instantiate members marked with attribute used. */
12331 if (r != error_mark_node && DECL_PRESERVE_P (r))
12332 used.safe_push (r);
12333 if (TREE_CODE (r) == FUNCTION_DECL
12334 && DECL_OMP_DECLARE_REDUCTION_P (r))
12335 cp_check_omp_declare_reduction (r);
12337 else if ((DECL_CLASS_TEMPLATE_P (t) || DECL_IMPLICIT_TYPEDEF_P (t))
12338 && LAMBDA_TYPE_P (TREE_TYPE (t)))
12339 /* A closure type for a lambda in an NSDMI or default argument.
12340 Ignore it; it will be regenerated when needed. */;
12341 else
12343 /* Build new TYPE_FIELDS. */
12344 if (TREE_CODE (t) == STATIC_ASSERT)
12345 tsubst_stmt (t, args, tf_warning_or_error, NULL_TREE);
12346 else if (TREE_CODE (t) != CONST_DECL)
12348 tree r;
12349 tree vec = NULL_TREE;
12350 int len = 1;
12352 gcc_checking_assert (TREE_CODE (t) != CONST_DECL);
12353 /* The file and line for this declaration, to
12354 assist in error message reporting. Since we
12355 called push_tinst_level above, we don't need to
12356 restore these. */
12357 input_location = DECL_SOURCE_LOCATION (t);
12359 if (TREE_CODE (t) == TEMPLATE_DECL)
12360 ++processing_template_decl;
12361 r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
12362 if (TREE_CODE (t) == TEMPLATE_DECL)
12363 --processing_template_decl;
12365 if (TREE_CODE (r) == TREE_VEC)
12367 /* A capture pack became multiple fields. */
12368 vec = r;
12369 len = TREE_VEC_LENGTH (vec);
12372 for (int i = 0; i < len; ++i)
12374 if (vec)
12375 r = TREE_VEC_ELT (vec, i);
12376 if (VAR_P (r))
12378 /* In [temp.inst]:
12380 [t]he initialization (and any associated
12381 side-effects) of a static data member does
12382 not occur unless the static data member is
12383 itself used in a way that requires the
12384 definition of the static data member to
12385 exist.
12387 Therefore, we do not substitute into the
12388 initialized for the static data member here. */
12389 finish_static_data_member_decl
12391 /*init=*/NULL_TREE,
12392 /*init_const_expr_p=*/false,
12393 /*asmspec_tree=*/NULL_TREE,
12394 /*flags=*/0);
12395 /* Instantiate members marked with attribute used. */
12396 if (r != error_mark_node && DECL_PRESERVE_P (r))
12397 used.safe_push (r);
12399 else if (TREE_CODE (r) == FIELD_DECL)
12401 /* Determine whether R has a valid type and can be
12402 completed later. If R is invalid, then its type
12403 is replaced by error_mark_node. */
12404 tree rtype = TREE_TYPE (r);
12405 if (can_complete_type_without_circularity (rtype))
12406 complete_type (rtype);
12408 if (!complete_or_array_type_p (rtype))
12410 /* If R's type couldn't be completed and
12411 it isn't a flexible array member (whose
12412 type is incomplete by definition) give
12413 an error. */
12414 cxx_incomplete_type_error (r, rtype);
12415 TREE_TYPE (r) = error_mark_node;
12417 else if (TREE_CODE (rtype) == ARRAY_TYPE
12418 && TYPE_DOMAIN (rtype) == NULL_TREE
12419 && (TREE_CODE (type) == UNION_TYPE
12420 || TREE_CODE (type) == QUAL_UNION_TYPE))
12422 error ("flexible array member %qD in union", r);
12423 TREE_TYPE (r) = error_mark_node;
12425 else if (!verify_type_context (input_location,
12426 TCTX_FIELD, rtype))
12427 TREE_TYPE (r) = error_mark_node;
12430 /* If it is a TYPE_DECL for a class-scoped
12431 ENUMERAL_TYPE, such a thing will already have
12432 been added to the field list by tsubst_enum
12433 in finish_member_declaration case above. */
12434 if (!(TREE_CODE (r) == TYPE_DECL
12435 && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
12436 && DECL_ARTIFICIAL (r)))
12438 set_current_access_from_decl (r);
12439 finish_member_declaration (r);
12445 else
12447 if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t)
12448 || DECL_TEMPLATE_TEMPLATE_PARM_P (t))
12450 /* Build new CLASSTYPE_FRIEND_CLASSES. */
12452 tree friend_type = t;
12453 if (TREE_CODE (friend_type) == TEMPLATE_DECL)
12455 /* template <class T> friend class C; */
12456 friend_type = tsubst_friend_class (friend_type, args);
12458 else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
12460 /* template <class T> friend class C::D; */
12461 friend_type = tsubst (friend_type, args,
12462 tf_warning_or_error, NULL_TREE);
12463 if (TREE_CODE (friend_type) == TEMPLATE_DECL)
12464 friend_type = TREE_TYPE (friend_type);
12466 else if (TREE_CODE (friend_type) == TYPENAME_TYPE
12467 || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
12469 /* This could be either
12471 friend class T::C;
12473 when dependent_type_p is false or
12475 template <class U> friend class T::C;
12477 otherwise. */
12478 /* Bump processing_template_decl in case this is something like
12479 template <class T> friend struct A<T>::B. */
12480 ++processing_template_decl;
12481 friend_type = tsubst (friend_type, args,
12482 tf_warning_or_error, NULL_TREE);
12483 --processing_template_decl;
12485 else if (uses_template_parms (friend_type))
12486 /* friend class C<T>; */
12487 friend_type = tsubst (friend_type, args,
12488 tf_warning_or_error, NULL_TREE);
12490 /* Otherwise it's
12492 friend class C;
12494 where C is already declared or
12496 friend class C<int>;
12498 We don't have to do anything in these cases. */
12500 if (friend_type != error_mark_node)
12501 make_friend_class (type, friend_type, /*complain=*/false);
12503 else
12505 /* Build new DECL_FRIENDLIST. */
12506 tree r;
12508 /* The file and line for this declaration, to
12509 assist in error message reporting. Since we
12510 called push_tinst_level above, we don't need to
12511 restore these. */
12512 input_location = DECL_SOURCE_LOCATION (t);
12514 if (TREE_CODE (t) == TEMPLATE_DECL)
12516 ++processing_template_decl;
12517 push_deferring_access_checks (dk_no_check);
12520 r = tsubst_friend_function (t, args);
12521 add_friend (type, r, /*complain=*/false);
12522 if (TREE_CODE (t) == TEMPLATE_DECL)
12524 pop_deferring_access_checks ();
12525 --processing_template_decl;
12531 if (fn_context)
12533 /* Restore these before substituting into the lambda capture
12534 initializers. */
12535 cp_unevaluated_operand = saved_unevaluated_operand;
12536 c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
12539 /* Set the file and line number information to whatever is given for
12540 the class itself. This puts error messages involving generated
12541 implicit functions at a predictable point, and the same point
12542 that would be used for non-template classes. */
12543 input_location = DECL_SOURCE_LOCATION (typedecl);
12545 unreverse_member_declarations (type);
12546 finish_struct_1 (type);
12547 TYPE_BEING_DEFINED (type) = 0;
12549 /* Remember if instantiating this class ran into errors, so we can avoid
12550 instantiating member functions in limit_bad_template_recursion. We set
12551 this flag even if the problem was in another instantiation triggered by
12552 this one, as that will likely also cause trouble for member functions. */
12553 if (errorcount + sorrycount > current_tinst_level->errors)
12554 CLASSTYPE_ERRONEOUS (type) = true;
12556 /* We don't instantiate default arguments for member functions. 14.7.1:
12558 The implicit instantiation of a class template specialization causes
12559 the implicit instantiation of the declarations, but not of the
12560 definitions or default arguments, of the class member functions,
12561 member classes, static data members and member templates.... */
12563 perform_instantiation_time_access_checks (pattern, args);
12564 perform_deferred_access_checks (tf_warning_or_error);
12566 /* Now that we've gone through all the members, instantiate those
12567 marked with attribute used. We must do this in the context of
12568 the class -- not the context we pushed from, as that might be
12569 inside a template and change the behaviour of mark_used. */
12570 for (tree x : used)
12571 mark_used (x);
12573 pop_nested_class ();
12574 maximum_field_alignment = saved_maximum_field_alignment;
12575 if (!fn_context)
12576 pop_from_top_level ();
12577 pop_tinst_level ();
12579 /* The vtable for a template class can be emitted in any translation
12580 unit in which the class is instantiated. When there is no key
12581 method, however, finish_struct_1 will already have added TYPE to
12582 the keyed_classes. */
12583 if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
12584 vec_safe_push (keyed_classes, type);
12586 return type;
12589 tree
12590 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12592 tree r;
12594 if (!t)
12595 r = t;
12596 else if (TYPE_P (t))
12597 r = tsubst (t, args, complain, in_decl);
12598 else
12600 if (!(complain & tf_warning))
12601 ++c_inhibit_evaluation_warnings;
12602 r = tsubst_expr (t, args, complain, in_decl);
12603 if (!(complain & tf_warning))
12604 --c_inhibit_evaluation_warnings;
12607 return r;
12610 /* Given a function parameter pack TMPL_PARM and some function parameters
12611 instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
12612 and set *SPEC_P to point at the next point in the list. */
12614 tree
12615 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
12617 /* Collect all of the extra "packed" parameters into an
12618 argument pack. */
12619 tree argpack;
12620 tree spec_parm = *spec_p;
12621 int len;
12623 for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
12624 if (tmpl_parm
12625 && !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
12626 break;
12628 spec_parm = *spec_p;
12629 if (len == 1 && DECL_PACK_P (spec_parm))
12631 /* The instantiation is still a parameter pack; don't wrap it in a
12632 NONTYPE_ARGUMENT_PACK. */
12633 argpack = spec_parm;
12634 spec_parm = DECL_CHAIN (spec_parm);
12636 else
12638 /* Fill in PARMVEC with all of the parameters. */
12639 tree parmvec = make_tree_vec (len);
12640 argpack = make_node (NONTYPE_ARGUMENT_PACK);
12641 for (int i = 0; i < len; i++)
12643 tree elt = spec_parm;
12644 if (DECL_PACK_P (elt))
12645 elt = make_pack_expansion (elt);
12646 TREE_VEC_ELT (parmvec, i) = elt;
12647 spec_parm = DECL_CHAIN (spec_parm);
12650 /* Build the argument packs. */
12651 ARGUMENT_PACK_ARGS (argpack) = parmvec;
12653 *spec_p = spec_parm;
12655 return argpack;
12658 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
12659 NONTYPE_ARGUMENT_PACK. */
12661 static tree
12662 make_fnparm_pack (tree spec_parm)
12664 return extract_fnparm_pack (NULL_TREE, &spec_parm);
12667 /* Return 1 if the Ith element of the argument pack ARG_PACK is a
12668 pack expansion with no extra args, 2 if it has extra args, or 0
12669 if it is not a pack expansion. */
12671 static int
12672 argument_pack_element_is_expansion_p (tree arg_pack, int i)
12674 if (TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
12675 /* We're being called before this happens in tsubst_pack_expansion. */
12676 arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
12677 tree vec = ARGUMENT_PACK_ARGS (arg_pack);
12678 if (i >= TREE_VEC_LENGTH (vec))
12679 return 0;
12680 tree elt = TREE_VEC_ELT (vec, i);
12681 if (DECL_P (elt))
12682 /* A decl pack is itself an expansion. */
12683 elt = TREE_TYPE (elt);
12684 if (!PACK_EXPANSION_P (elt))
12685 return 0;
12686 if (PACK_EXPANSION_EXTRA_ARGS (elt))
12687 return 2;
12688 return 1;
12692 /* Creates and return an ARGUMENT_PACK_SELECT tree node. */
12694 static tree
12695 make_argument_pack_select (tree arg_pack, unsigned index)
12697 tree aps = make_node (ARGUMENT_PACK_SELECT);
12699 ARGUMENT_PACK_SELECT_FROM_PACK (aps) = arg_pack;
12700 ARGUMENT_PACK_SELECT_INDEX (aps) = index;
12702 return aps;
12705 /* This is a subroutine of tsubst_pack_expansion.
12707 It returns TRUE if we need to use the PACK_EXPANSION_EXTRA_ARGS
12708 mechanism to store the (non complete list of) arguments of the
12709 substitution and return a non substituted pack expansion, in order
12710 to wait for when we have enough arguments to really perform the
12711 substitution. */
12713 static bool
12714 use_pack_expansion_extra_args_p (tree t,
12715 tree parm_packs,
12716 int arg_pack_len,
12717 bool has_empty_arg)
12719 if (has_empty_arg
12720 && PACK_EXPANSION_FORCE_EXTRA_ARGS_P (t))
12721 return true;
12723 /* If one pack has an expansion and another pack has a normal
12724 argument or if one pack has an empty argument and an another
12725 one hasn't then tsubst_pack_expansion cannot perform the
12726 substitution and need to fall back on the
12727 PACK_EXPANSION_EXTRA mechanism. */
12728 if (parm_packs == NULL_TREE)
12729 return false;
12730 else if (has_empty_arg)
12732 /* If all the actual packs are pack expansions, we can still
12733 subsitute directly. */
12734 for (tree p = parm_packs; p; p = TREE_CHAIN (p))
12736 tree a = TREE_VALUE (p);
12737 if (TREE_CODE (a) == ARGUMENT_PACK_SELECT)
12738 a = ARGUMENT_PACK_SELECT_FROM_PACK (a);
12739 a = ARGUMENT_PACK_ARGS (a);
12740 if (TREE_VEC_LENGTH (a) == 1)
12741 a = TREE_VEC_ELT (a, 0);
12742 if (PACK_EXPANSION_P (a))
12743 continue;
12744 return true;
12746 return false;
12749 for (int i = 0 ; i < arg_pack_len; ++i)
12751 bool has_expansion_arg = false;
12752 bool has_non_expansion_arg = false;
12753 for (tree parm_pack = parm_packs;
12754 parm_pack;
12755 parm_pack = TREE_CHAIN (parm_pack))
12757 tree arg = TREE_VALUE (parm_pack);
12759 int exp = argument_pack_element_is_expansion_p (arg, i);
12760 if (exp == 2)
12761 /* We can't substitute a pack expansion with extra args into
12762 our pattern. */
12763 return true;
12764 else if (exp)
12765 has_expansion_arg = true;
12766 else
12767 has_non_expansion_arg = true;
12770 if (has_expansion_arg && has_non_expansion_arg)
12772 gcc_checking_assert (false);
12773 return true;
12776 return false;
12779 /* [temp.variadic]/6 says that:
12781 The instantiation of a pack expansion [...]
12782 produces a list E1,E2, ..., En, where N is the number of elements
12783 in the pack expansion parameters.
12785 This subroutine of tsubst_pack_expansion produces one of these Ei.
12787 PATTERN is the pattern of the pack expansion. PARM_PACKS is a
12788 TREE_LIST in which each TREE_PURPOSE is a parameter pack of
12789 PATTERN, and each TREE_VALUE is its corresponding argument pack.
12790 INDEX is the index 'i' of the element Ei to produce. ARGS,
12791 COMPLAIN, and IN_DECL are the same parameters as for the
12792 tsubst_pack_expansion function.
12794 The function returns the resulting Ei upon successful completion,
12795 or error_mark_node.
12797 Note that this function possibly modifies the ARGS parameter, so
12798 it's the responsibility of the caller to restore it. */
12800 static tree
12801 gen_elem_of_pack_expansion_instantiation (tree pattern,
12802 tree parm_packs,
12803 unsigned index,
12804 tree args /* This parm gets
12805 modified. */,
12806 tsubst_flags_t complain,
12807 tree in_decl)
12809 tree t;
12810 bool ith_elem_is_expansion = false;
12812 /* For each parameter pack, change the substitution of the parameter
12813 pack to the ith argument in its argument pack, then expand the
12814 pattern. */
12815 for (tree pack = parm_packs; pack; pack = TREE_CHAIN (pack))
12817 tree parm = TREE_PURPOSE (pack);
12818 tree arg_pack = TREE_VALUE (pack);
12819 tree aps; /* instance of ARGUMENT_PACK_SELECT. */
12821 ith_elem_is_expansion |=
12822 argument_pack_element_is_expansion_p (arg_pack, index);
12824 /* Select the Ith argument from the pack. */
12825 if (TREE_CODE (parm) == PARM_DECL
12826 || VAR_P (parm)
12827 || TREE_CODE (parm) == FIELD_DECL)
12829 if (index == 0)
12831 aps = make_argument_pack_select (arg_pack, index);
12832 if (!mark_used (parm, complain) && !(complain & tf_error))
12833 return error_mark_node;
12834 register_local_specialization (aps, parm);
12836 else
12837 aps = retrieve_local_specialization (parm);
12839 else
12841 int idx, level;
12842 template_parm_level_and_index (parm, &level, &idx);
12844 if (index == 0)
12846 aps = make_argument_pack_select (arg_pack, index);
12847 /* Update the corresponding argument. */
12848 TMPL_ARG (args, level, idx) = aps;
12850 else
12851 /* Re-use the ARGUMENT_PACK_SELECT. */
12852 aps = TMPL_ARG (args, level, idx);
12854 ARGUMENT_PACK_SELECT_INDEX (aps) = index;
12857 /* Substitute into the PATTERN with the (possibly altered)
12858 arguments. */
12859 if (pattern == in_decl)
12860 /* Expanding a fixed parameter pack from
12861 coerce_template_parameter_pack. */
12862 t = tsubst_decl (pattern, args, complain);
12863 else if (pattern == error_mark_node)
12864 t = error_mark_node;
12865 else if (!TYPE_P (pattern))
12866 t = tsubst_expr (pattern, args, complain, in_decl);
12867 else
12869 t = tsubst (pattern, args, complain, in_decl);
12870 if (is_auto (t) && !ith_elem_is_expansion)
12871 /* When expanding the fake auto... pack expansion from add_capture, we
12872 need to mark that the expansion is no longer a pack. */
12873 TEMPLATE_TYPE_PARAMETER_PACK (t) = false;
12876 /* If the Ith argument pack element is a pack expansion, then
12877 the Ith element resulting from the substituting is going to
12878 be a pack expansion as well. */
12879 if (ith_elem_is_expansion)
12880 t = make_pack_expansion (t, complain);
12882 return t;
12885 /* When the unexpanded parameter pack in a fold expression expands to an empty
12886 sequence, the value of the expression is as follows; the program is
12887 ill-formed if the operator is not listed in this table.
12889 && true
12890 || false
12891 , void() */
12893 tree
12894 expand_empty_fold (tree t, tsubst_flags_t complain)
12896 tree_code code = (tree_code)TREE_INT_CST_LOW (TREE_OPERAND (t, 0));
12897 if (!FOLD_EXPR_MODIFY_P (t))
12898 switch (code)
12900 case TRUTH_ANDIF_EXPR:
12901 return boolean_true_node;
12902 case TRUTH_ORIF_EXPR:
12903 return boolean_false_node;
12904 case COMPOUND_EXPR:
12905 return void_node;
12906 default:
12907 break;
12910 if (complain & tf_error)
12911 error_at (location_of (t),
12912 "fold of empty expansion over %O", code);
12913 return error_mark_node;
12916 /* Given a fold-expression T and a current LEFT and RIGHT operand,
12917 form an expression that combines the two terms using the
12918 operator of T. */
12920 static tree
12921 fold_expression (tree t, tree left, tree right, tsubst_flags_t complain)
12923 tree_code code = FOLD_EXPR_OP (t);
12925 tree lookups = templated_operator_saved_lookups (t);
12927 // Handle compound assignment operators.
12928 if (FOLD_EXPR_MODIFY_P (t))
12929 return build_x_modify_expr (input_location, left, code, right,
12930 lookups, complain);
12932 warning_sentinel s(warn_parentheses);
12933 switch (code)
12935 case COMPOUND_EXPR:
12936 return build_x_compound_expr (input_location, left, right,
12937 lookups, complain);
12938 default:
12939 return build_x_binary_op (input_location, code,
12940 left, TREE_CODE (left),
12941 right, TREE_CODE (right),
12942 lookups, /*overload=*/NULL,
12943 complain);
12947 /* Substitute ARGS into the pack of a fold expression T. */
12949 static inline tree
12950 tsubst_fold_expr_pack (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12952 return tsubst_pack_expansion (FOLD_EXPR_PACK (t), args, complain, in_decl);
12955 /* Substitute ARGS into the pack of a fold expression T. */
12957 static inline tree
12958 tsubst_fold_expr_init (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12960 return tsubst_expr (FOLD_EXPR_INIT (t), args, complain, in_decl);
12963 /* Expand a PACK of arguments into a grouped as left fold.
12964 Given a pack containing elements A0, A1, ..., An and an
12965 operator @, this builds the expression:
12967 ((A0 @ A1) @ A2) ... @ An
12969 Note that PACK must not be empty.
12971 The operator is defined by the original fold expression T. */
12973 static tree
12974 expand_left_fold (tree t, tree pack, tsubst_flags_t complain)
12976 tree left = TREE_VEC_ELT (pack, 0);
12977 for (int i = 1; i < TREE_VEC_LENGTH (pack); ++i)
12979 tree right = TREE_VEC_ELT (pack, i);
12980 left = fold_expression (t, left, right, complain);
12982 return left;
12985 /* Substitute into a unary left fold expression. */
12987 static tree
12988 tsubst_unary_left_fold (tree t, tree args, tsubst_flags_t complain,
12989 tree in_decl)
12991 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12992 if (pack == error_mark_node)
12993 return error_mark_node;
12994 if (PACK_EXPANSION_P (pack))
12996 tree r = copy_node (t);
12997 FOLD_EXPR_PACK (r) = pack;
12998 return r;
13000 if (TREE_VEC_LENGTH (pack) == 0)
13001 return expand_empty_fold (t, complain);
13002 else
13003 return expand_left_fold (t, pack, complain);
13006 /* Substitute into a binary left fold expression.
13008 Do ths by building a single (non-empty) vector of argumnts and
13009 building the expression from those elements. */
13011 static tree
13012 tsubst_binary_left_fold (tree t, tree args, tsubst_flags_t complain,
13013 tree in_decl)
13015 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
13016 if (pack == error_mark_node)
13017 return error_mark_node;
13018 tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
13019 if (init == error_mark_node)
13020 return error_mark_node;
13022 if (PACK_EXPANSION_P (pack))
13024 tree r = copy_node (t);
13025 FOLD_EXPR_PACK (r) = pack;
13026 FOLD_EXPR_INIT (r) = init;
13027 return r;
13030 tree vec = make_tree_vec (TREE_VEC_LENGTH (pack) + 1);
13031 TREE_VEC_ELT (vec, 0) = init;
13032 for (int i = 0; i < TREE_VEC_LENGTH (pack); ++i)
13033 TREE_VEC_ELT (vec, i + 1) = TREE_VEC_ELT (pack, i);
13035 return expand_left_fold (t, vec, complain);
13038 /* Expand a PACK of arguments into a grouped as right fold.
13039 Given a pack containing elementns A0, A1, ..., and an
13040 operator @, this builds the expression:
13042 A0@ ... (An-2 @ (An-1 @ An))
13044 Note that PACK must not be empty.
13046 The operator is defined by the original fold expression T. */
13048 tree
13049 expand_right_fold (tree t, tree pack, tsubst_flags_t complain)
13051 // Build the expression.
13052 int n = TREE_VEC_LENGTH (pack);
13053 tree right = TREE_VEC_ELT (pack, n - 1);
13054 for (--n; n != 0; --n)
13056 tree left = TREE_VEC_ELT (pack, n - 1);
13057 right = fold_expression (t, left, right, complain);
13059 return right;
13062 /* Substitute into a unary right fold expression. */
13064 static tree
13065 tsubst_unary_right_fold (tree t, tree args, tsubst_flags_t complain,
13066 tree in_decl)
13068 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
13069 if (pack == error_mark_node)
13070 return error_mark_node;
13071 if (PACK_EXPANSION_P (pack))
13073 tree r = copy_node (t);
13074 FOLD_EXPR_PACK (r) = pack;
13075 return r;
13077 if (TREE_VEC_LENGTH (pack) == 0)
13078 return expand_empty_fold (t, complain);
13079 else
13080 return expand_right_fold (t, pack, complain);
13083 /* Substitute into a binary right fold expression.
13085 Do ths by building a single (non-empty) vector of arguments and
13086 building the expression from those elements. */
13088 static tree
13089 tsubst_binary_right_fold (tree t, tree args, tsubst_flags_t complain,
13090 tree in_decl)
13092 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
13093 if (pack == error_mark_node)
13094 return error_mark_node;
13095 tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
13096 if (init == error_mark_node)
13097 return error_mark_node;
13099 if (PACK_EXPANSION_P (pack))
13101 tree r = copy_node (t);
13102 FOLD_EXPR_PACK (r) = pack;
13103 FOLD_EXPR_INIT (r) = init;
13104 return r;
13107 int n = TREE_VEC_LENGTH (pack);
13108 tree vec = make_tree_vec (n + 1);
13109 for (int i = 0; i < n; ++i)
13110 TREE_VEC_ELT (vec, i) = TREE_VEC_ELT (pack, i);
13111 TREE_VEC_ELT (vec, n) = init;
13113 return expand_right_fold (t, vec, complain);
13116 /* Walk through the pattern of a pack expansion, adding everything in
13117 local_specializations to a list. */
13119 class el_data
13121 public:
13122 /* Set of variables declared within the pattern. */
13123 hash_set<tree> internal;
13124 /* Set of AST nodes that have been visited by the traversal. */
13125 hash_set<tree> visited;
13126 /* List of local_specializations used within the pattern. */
13127 tree extra;
13128 tsubst_flags_t complain;
13129 /* True iff we don't want to walk into unevaluated contexts. */
13130 bool skip_unevaluated_operands = false;
13131 /* The unevaluated contexts that we avoided walking. */
13132 auto_vec<tree> skipped_trees;
13134 el_data (tsubst_flags_t c)
13135 : extra (NULL_TREE), complain (c) {}
13137 static tree
13138 extract_locals_r (tree *tp, int *walk_subtrees, void *data_)
13140 el_data &data = *reinterpret_cast<el_data*>(data_);
13141 tree *extra = &data.extra;
13142 tsubst_flags_t complain = data.complain;
13144 if (data.skip_unevaluated_operands
13145 && unevaluated_p (TREE_CODE (*tp)))
13147 data.skipped_trees.safe_push (*tp);
13148 *walk_subtrees = 0;
13149 return NULL_TREE;
13152 if (TYPE_P (*tp) && typedef_variant_p (*tp))
13153 /* Remember local typedefs (85214). */
13154 tp = &TYPE_NAME (*tp);
13156 if (TREE_CODE (*tp) == DECL_EXPR)
13158 tree decl = DECL_EXPR_DECL (*tp);
13159 data.internal.add (decl);
13160 if (VAR_P (decl)
13161 && DECL_DECOMPOSITION_P (decl)
13162 && TREE_TYPE (decl) != error_mark_node)
13164 gcc_assert (DECL_NAME (decl) == NULL_TREE);
13165 for (tree decl2 = DECL_CHAIN (decl);
13166 decl2
13167 && VAR_P (decl2)
13168 && DECL_DECOMPOSITION_P (decl2)
13169 && DECL_NAME (decl2)
13170 && TREE_TYPE (decl2) != error_mark_node;
13171 decl2 = DECL_CHAIN (decl2))
13173 gcc_assert (DECL_DECOMP_BASE (decl2) == decl);
13174 data.internal.add (decl2);
13178 else if (TREE_CODE (*tp) == LAMBDA_EXPR)
13180 /* Since we defer implicit capture, look in the parms and body. */
13181 tree fn = lambda_function (*tp);
13182 cp_walk_tree (&TREE_TYPE (fn), &extract_locals_r, &data,
13183 &data.visited);
13184 cp_walk_tree (&DECL_SAVED_TREE (fn), &extract_locals_r, &data,
13185 &data.visited);
13187 else if (tree spec = retrieve_local_specialization (*tp))
13189 if (data.internal.contains (*tp))
13190 /* Don't mess with variables declared within the pattern. */
13191 return NULL_TREE;
13192 if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
13194 /* Maybe pull out the PARM_DECL for a partial instantiation. */
13195 tree args = ARGUMENT_PACK_ARGS (spec);
13196 if (TREE_VEC_LENGTH (args) == 1)
13198 tree elt = TREE_VEC_ELT (args, 0);
13199 if (PACK_EXPANSION_P (elt))
13200 elt = PACK_EXPANSION_PATTERN (elt);
13201 if (DECL_PACK_P (elt))
13202 spec = elt;
13204 if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
13206 /* Handle lambda capture here, since we aren't doing any
13207 substitution now, and so tsubst_copy won't call
13208 process_outer_var_ref. */
13209 tree args = ARGUMENT_PACK_ARGS (spec);
13210 int len = TREE_VEC_LENGTH (args);
13211 for (int i = 0; i < len; ++i)
13213 tree arg = TREE_VEC_ELT (args, i);
13214 tree carg = arg;
13215 if (outer_automatic_var_p (arg))
13216 carg = process_outer_var_ref (arg, complain);
13217 if (carg != arg)
13219 /* Make a new NONTYPE_ARGUMENT_PACK of the capture
13220 proxies. */
13221 if (i == 0)
13223 spec = copy_node (spec);
13224 args = copy_node (args);
13225 ARGUMENT_PACK_ARGS (spec) = args;
13226 register_local_specialization (spec, *tp);
13228 TREE_VEC_ELT (args, i) = carg;
13233 if (outer_automatic_var_p (spec))
13234 spec = process_outer_var_ref (spec, complain);
13235 *extra = tree_cons (*tp, spec, *extra);
13237 return NULL_TREE;
13239 static tree
13240 extract_local_specs (tree pattern, tsubst_flags_t complain)
13242 el_data data (complain);
13243 /* Walk the pattern twice, ignoring unevaluated operands the first time
13244 around, so that if a local specialization appears in both an evaluated
13245 and unevaluated context we prefer to process it in the evaluated context
13246 (since e.g. process_outer_var_ref is a no-op inside an unevaluated
13247 context). */
13248 data.skip_unevaluated_operands = true;
13249 cp_walk_tree (&pattern, extract_locals_r, &data, &data.visited);
13250 /* Now walk the unevaluated contexts we skipped the first time around. */
13251 data.skip_unevaluated_operands = false;
13252 for (tree t : data.skipped_trees)
13254 data.visited.remove (t);
13255 cp_walk_tree (&t, extract_locals_r, &data, &data.visited);
13257 return data.extra;
13260 /* Extract any uses of local_specializations from PATTERN and add them to ARGS
13261 for use in PACK_EXPANSION_EXTRA_ARGS. */
13263 tree
13264 build_extra_args (tree pattern, tree args, tsubst_flags_t complain)
13266 /* Make a copy of the extra arguments so that they won't get changed
13267 out from under us. */
13268 tree extra = preserve_args (copy_template_args (args), /*cow_p=*/false);
13269 if (local_specializations)
13270 if (tree locals = extract_local_specs (pattern, complain))
13271 extra = tree_cons (NULL_TREE, extra, locals);
13272 return extra;
13275 /* Apply any local specializations from PACK_EXPANSION_EXTRA_ARGS and add the
13276 normal template args to ARGS. */
13278 tree
13279 add_extra_args (tree extra, tree args, tsubst_flags_t complain, tree in_decl)
13281 if (extra && TREE_CODE (extra) == TREE_LIST)
13283 for (tree elt = TREE_CHAIN (extra); elt; elt = TREE_CHAIN (elt))
13285 /* The partial instantiation involved local declarations collected in
13286 extract_local_specs; map from the general template to our local
13287 context. */
13288 tree gen = TREE_PURPOSE (elt);
13289 tree inst = TREE_VALUE (elt);
13290 if (DECL_P (inst))
13291 if (tree local = retrieve_local_specialization (inst))
13292 inst = local;
13293 /* else inst is already a full instantiation of the pack. */
13294 register_local_specialization (inst, gen);
13296 gcc_assert (!TREE_PURPOSE (extra));
13297 extra = TREE_VALUE (extra);
13299 if (uses_template_parms (extra))
13301 /* This can happen after dependent substitution into a
13302 requires-expr or a lambda that uses constexpr if. */
13303 extra = tsubst_template_args (extra, args, complain, in_decl);
13304 args = add_outermost_template_args (args, extra);
13306 else
13307 args = add_to_template_args (extra, args);
13308 return args;
13311 /* Substitute ARGS into T, which is an pack expansion
13312 (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
13313 TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
13314 (if only a partial substitution could be performed) or
13315 ERROR_MARK_NODE if there was an error. */
13316 tree
13317 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
13318 tree in_decl)
13320 tree pattern;
13321 tree pack, packs = NULL_TREE;
13322 bool unsubstituted_packs = false;
13323 int i, len = -1;
13324 tree result;
13325 bool need_local_specializations = false;
13326 int levels;
13328 gcc_assert (PACK_EXPANSION_P (t));
13329 pattern = PACK_EXPANSION_PATTERN (t);
13331 /* Add in any args remembered from an earlier partial instantiation. */
13332 args = add_extra_args (PACK_EXPANSION_EXTRA_ARGS (t), args, complain, in_decl);
13334 levels = TMPL_ARGS_DEPTH (args);
13336 /* Determine the argument packs that will instantiate the parameter
13337 packs used in the expansion expression. While we're at it,
13338 compute the number of arguments to be expanded and make sure it
13339 is consistent. */
13340 for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
13341 pack = TREE_CHAIN (pack))
13343 tree parm_pack = TREE_VALUE (pack);
13344 tree arg_pack = NULL_TREE;
13345 tree orig_arg = NULL_TREE;
13346 int level = 0;
13348 if (TREE_CODE (parm_pack) == BASES)
13350 gcc_assert (parm_pack == pattern);
13351 tree type = tsubst (BASES_TYPE (parm_pack), args, complain, in_decl);
13352 if (BASES_DIRECT (parm_pack))
13353 return calculate_direct_bases (type, complain);
13354 else
13355 return calculate_bases (type, complain);
13357 else if (builtin_pack_call_p (parm_pack))
13359 if (parm_pack != pattern)
13361 if (complain & tf_error)
13362 sorry ("%qE is not the entire pattern of the pack expansion",
13363 parm_pack);
13364 return error_mark_node;
13366 return expand_builtin_pack_call (parm_pack, args,
13367 complain, in_decl);
13369 else if (TREE_CODE (parm_pack) == PARM_DECL)
13371 /* We know we have correct local_specializations if this
13372 expansion is at function scope, or if we're dealing with a
13373 local parameter in a requires expression; for the latter,
13374 tsubst_requires_expr set it up appropriately. */
13375 if (PACK_EXPANSION_LOCAL_P (t) || CONSTRAINT_VAR_P (parm_pack))
13376 arg_pack = retrieve_local_specialization (parm_pack);
13377 else
13378 /* We can't rely on local_specializations for a parameter
13379 name used later in a function declaration (such as in a
13380 late-specified return type). Even if it exists, it might
13381 have the wrong value for a recursive call. */
13382 need_local_specializations = true;
13384 if (!arg_pack)
13386 /* This parameter pack was used in an unevaluated context. Just
13387 make a dummy decl, since it's only used for its type. */
13388 ++cp_unevaluated_operand;
13389 arg_pack = tsubst_decl (parm_pack, args, complain);
13390 --cp_unevaluated_operand;
13391 if (arg_pack && DECL_PACK_P (arg_pack))
13392 /* Partial instantiation of the parm_pack, we can't build
13393 up an argument pack yet. */
13394 arg_pack = NULL_TREE;
13395 else
13396 arg_pack = make_fnparm_pack (arg_pack);
13398 else if (DECL_PACK_P (arg_pack))
13399 /* This argument pack isn't fully instantiated yet. */
13400 arg_pack = NULL_TREE;
13402 else if (is_capture_proxy (parm_pack))
13404 arg_pack = retrieve_local_specialization (parm_pack);
13405 if (DECL_PACK_P (arg_pack))
13406 arg_pack = NULL_TREE;
13408 else
13410 int idx;
13411 template_parm_level_and_index (parm_pack, &level, &idx);
13412 if (level <= levels)
13413 arg_pack = TMPL_ARG (args, level, idx);
13415 if (arg_pack && TREE_CODE (arg_pack) == TEMPLATE_TYPE_PARM
13416 && TEMPLATE_TYPE_PARAMETER_PACK (arg_pack))
13417 arg_pack = NULL_TREE;
13420 orig_arg = arg_pack;
13421 if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
13422 arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
13424 if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
13425 /* This can only happen if we forget to expand an argument
13426 pack somewhere else. Just return an error, silently. */
13428 result = make_tree_vec (1);
13429 TREE_VEC_ELT (result, 0) = error_mark_node;
13430 return result;
13433 if (arg_pack)
13435 int my_len =
13436 TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
13438 /* Don't bother trying to do a partial substitution with
13439 incomplete packs; we'll try again after deduction. */
13440 if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
13441 return t;
13443 if (len < 0)
13444 len = my_len;
13445 else if (len != my_len)
13447 if (!(complain & tf_error))
13448 /* Fail quietly. */;
13449 else if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
13450 error ("mismatched argument pack lengths while expanding %qT",
13451 pattern);
13452 else
13453 error ("mismatched argument pack lengths while expanding %qE",
13454 pattern);
13455 return error_mark_node;
13458 /* Keep track of the parameter packs and their corresponding
13459 argument packs. */
13460 packs = tree_cons (parm_pack, arg_pack, packs);
13461 TREE_TYPE (packs) = orig_arg;
13463 else
13465 /* We can't substitute for this parameter pack. We use a flag as
13466 well as the missing_level counter because function parameter
13467 packs don't have a level. */
13468 gcc_assert (processing_template_decl || is_auto (parm_pack));
13469 unsubstituted_packs = true;
13473 /* If the expansion is just T..., return the matching argument pack, unless
13474 we need to call convert_from_reference on all the elements. This is an
13475 important optimization; see c++/68422. */
13476 if (!unsubstituted_packs
13477 && TREE_PURPOSE (packs) == pattern)
13479 tree args = ARGUMENT_PACK_ARGS (TREE_VALUE (packs));
13481 /* If the argument pack is a single pack expansion, pull it out. */
13482 if (TREE_VEC_LENGTH (args) == 1
13483 && pack_expansion_args_count (args))
13484 return TREE_VEC_ELT (args, 0);
13486 /* Types need no adjustment, nor does sizeof..., and if we still have
13487 some pack expansion args we won't do anything yet. */
13488 if (TREE_CODE (t) == TYPE_PACK_EXPANSION
13489 || PACK_EXPANSION_SIZEOF_P (t)
13490 || pack_expansion_args_count (args))
13491 return args;
13492 /* Also optimize expression pack expansions if we can tell that the
13493 elements won't have reference type. */
13494 tree type = TREE_TYPE (pattern);
13495 if (type && !TYPE_REF_P (type)
13496 && !PACK_EXPANSION_P (type)
13497 && !WILDCARD_TYPE_P (type))
13498 return args;
13499 /* Otherwise use the normal path so we get convert_from_reference. */
13502 /* We cannot expand this expansion expression, because we don't have
13503 all of the argument packs we need. */
13504 if (use_pack_expansion_extra_args_p (t, packs, len, unsubstituted_packs))
13506 /* We got some full packs, but we can't substitute them in until we
13507 have values for all the packs. So remember these until then. */
13509 t = make_pack_expansion (pattern, complain);
13510 PACK_EXPANSION_EXTRA_ARGS (t)
13511 = build_extra_args (pattern, args, complain);
13512 return t;
13515 /* If NEED_LOCAL_SPECIALIZATIONS then we're in a late-specified return
13516 type, so create our own local specializations map; the current map is
13517 either NULL or (in the case of recursive unification) might have
13518 bindings that we don't want to use or alter. */
13519 local_specialization_stack lss (need_local_specializations
13520 ? lss_blank : lss_nop);
13522 if (unsubstituted_packs)
13524 /* There were no real arguments, we're just replacing a parameter
13525 pack with another version of itself. Substitute into the
13526 pattern and return a PACK_EXPANSION_*. The caller will need to
13527 deal with that. */
13528 if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
13529 result = tsubst_expr (pattern, args, complain, in_decl);
13530 else
13531 result = tsubst (pattern, args, complain, in_decl);
13532 result = make_pack_expansion (result, complain);
13533 PACK_EXPANSION_LOCAL_P (result) = PACK_EXPANSION_LOCAL_P (t);
13534 PACK_EXPANSION_SIZEOF_P (result) = PACK_EXPANSION_SIZEOF_P (t);
13535 if (PACK_EXPANSION_AUTO_P (t))
13537 /* This is a fake auto... pack expansion created in add_capture with
13538 _PACKS that don't appear in the pattern. Copy one over. */
13539 packs = PACK_EXPANSION_PARAMETER_PACKS (t);
13540 pack = retrieve_local_specialization (TREE_VALUE (packs));
13541 gcc_checking_assert (DECL_PACK_P (pack));
13542 PACK_EXPANSION_PARAMETER_PACKS (result)
13543 = build_tree_list (NULL_TREE, pack);
13544 PACK_EXPANSION_AUTO_P (result) = true;
13546 return result;
13549 gcc_assert (len >= 0);
13551 /* For each argument in each argument pack, substitute into the
13552 pattern. */
13553 result = make_tree_vec (len);
13554 tree elem_args = copy_template_args (args);
13555 for (i = 0; i < len; ++i)
13557 t = gen_elem_of_pack_expansion_instantiation (pattern, packs,
13559 elem_args, complain,
13560 in_decl);
13561 TREE_VEC_ELT (result, i) = t;
13562 if (t == error_mark_node)
13564 result = error_mark_node;
13565 break;
13569 /* Update ARGS to restore the substitution from parameter packs to
13570 their argument packs. */
13571 for (pack = packs; pack; pack = TREE_CHAIN (pack))
13573 tree parm = TREE_PURPOSE (pack);
13575 if (TREE_CODE (parm) == PARM_DECL
13576 || VAR_P (parm)
13577 || TREE_CODE (parm) == FIELD_DECL)
13578 register_local_specialization (TREE_TYPE (pack), parm);
13579 else
13581 int idx, level;
13583 if (TREE_VALUE (pack) == NULL_TREE)
13584 continue;
13586 template_parm_level_and_index (parm, &level, &idx);
13588 /* Update the corresponding argument. */
13589 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
13590 TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
13591 TREE_TYPE (pack);
13592 else
13593 TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
13597 /* If the dependent pack arguments were such that we end up with only a
13598 single pack expansion again, there's no need to keep it in a TREE_VEC. */
13599 if (len == 1 && TREE_CODE (result) == TREE_VEC
13600 && PACK_EXPANSION_P (TREE_VEC_ELT (result, 0)))
13601 return TREE_VEC_ELT (result, 0);
13603 return result;
13606 /* Make an argument pack out of the TREE_VEC VEC. */
13608 static tree
13609 make_argument_pack (tree vec)
13611 tree pack;
13613 if (TYPE_P (TREE_VEC_ELT (vec, 0)))
13614 pack = cxx_make_type (TYPE_ARGUMENT_PACK);
13615 else
13617 pack = make_node (NONTYPE_ARGUMENT_PACK);
13618 TREE_CONSTANT (pack) = 1;
13620 ARGUMENT_PACK_ARGS (pack) = vec;
13621 return pack;
13624 /* Return an exact copy of template args T that can be modified
13625 independently. */
13627 static tree
13628 copy_template_args (tree t)
13630 if (t == error_mark_node)
13631 return t;
13633 int len = TREE_VEC_LENGTH (t);
13634 tree new_vec = make_tree_vec (len);
13636 for (int i = 0; i < len; ++i)
13638 tree elt = TREE_VEC_ELT (t, i);
13639 if (elt && TREE_CODE (elt) == TREE_VEC)
13640 elt = copy_template_args (elt);
13641 TREE_VEC_ELT (new_vec, i) = elt;
13644 NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_vec)
13645 = NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
13647 return new_vec;
13650 /* Substitute ARGS into the *_ARGUMENT_PACK orig_arg. */
13652 tree
13653 tsubst_argument_pack (tree orig_arg, tree args, tsubst_flags_t complain,
13654 tree in_decl)
13656 /* This flag is used only during deduction, and we don't expect to
13657 substitute such ARGUMENT_PACKs. */
13658 gcc_assert (!ARGUMENT_PACK_INCOMPLETE_P (orig_arg));
13660 /* Substitute into each of the arguments. */
13661 tree pack_args = tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
13662 args, complain, in_decl);
13663 if (pack_args == error_mark_node)
13664 return error_mark_node;
13666 if (pack_args == ARGUMENT_PACK_ARGS (orig_arg))
13667 return orig_arg;
13669 /* If we're substituting into a generic ARGUMENT_PACK for a variadic
13670 template parameter, we might be able to avoid allocating a new
13671 ARGUMENT_PACK and reuse the corresponding ARGUMENT_PACK from ARGS
13672 if the substituted result is identical to it. */
13673 if (tree parm = template_arg_to_parm (orig_arg))
13675 int level, index;
13676 template_parm_level_and_index (parm, &level, &index);
13677 if (TMPL_ARGS_DEPTH (args) >= level)
13678 if (tree arg = TMPL_ARG (args, level, index))
13679 if (TREE_CODE (arg) == TREE_CODE (orig_arg)
13680 && ARGUMENT_PACK_ARGS (arg) == pack_args)
13682 gcc_assert (!ARGUMENT_PACK_INCOMPLETE_P (arg));
13683 return arg;
13687 tree new_arg;
13688 if (TYPE_P (orig_arg))
13690 new_arg = cxx_make_type (TREE_CODE (orig_arg));
13691 SET_TYPE_STRUCTURAL_EQUALITY (new_arg);
13693 else
13695 new_arg = make_node (TREE_CODE (orig_arg));
13696 TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
13698 ARGUMENT_PACK_ARGS (new_arg) = pack_args;
13699 return new_arg;
13702 /* Substitute ARGS into the vector or list of template arguments T. */
13704 tree
13705 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
13707 if (t == error_mark_node)
13708 return error_mark_node;
13710 /* In "sizeof(X<I>)" we need to evaluate "I". */
13711 cp_evaluated ev;
13713 const int len = TREE_VEC_LENGTH (t);
13714 tree *elts = XALLOCAVEC (tree, len);
13715 int expanded_len_adjust = 0;
13717 /* True iff the substituted result is identical to T. */
13718 bool const_subst_p = true;
13720 for (int i = 0; i < len; i++)
13722 tree orig_arg = TREE_VEC_ELT (t, i);
13723 tree new_arg;
13725 if (!orig_arg)
13726 new_arg = NULL_TREE;
13727 else if (TREE_CODE (orig_arg) == TREE_VEC)
13728 new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
13729 else if (PACK_EXPANSION_P (orig_arg))
13731 /* Substitute into an expansion expression. */
13732 new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
13734 if (TREE_CODE (new_arg) == TREE_VEC)
13735 /* Add to the expanded length adjustment the number of
13736 expanded arguments. We subtract one from this
13737 measurement, because the argument pack expression
13738 itself is already counted as 1 in
13739 LEN. EXPANDED_LEN_ADJUST can actually be negative, if
13740 the argument pack is empty. */
13741 expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
13743 else if (ARGUMENT_PACK_P (orig_arg))
13744 new_arg = tsubst_argument_pack (orig_arg, args, complain, in_decl);
13745 else
13746 new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
13748 if (new_arg == error_mark_node)
13749 return error_mark_node;
13751 elts[i] = new_arg;
13752 if (new_arg != orig_arg)
13753 const_subst_p = false;
13756 if (const_subst_p)
13757 return t;
13759 tree maybe_reuse = NULL_TREE;
13761 /* If ARGS and T are both multi-level, the substituted result may be
13762 identical to ARGS. */
13763 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (t)
13764 && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args)
13765 && TMPL_ARGS_DEPTH (t) == TMPL_ARGS_DEPTH (args))
13766 maybe_reuse = args;
13767 /* If T appears to be a vector of generic template arguments, the
13768 substituted result may be identical to the corresponding level
13769 from ARGS. */
13770 else if (tree parm = template_arg_to_parm (TREE_VEC_ELT (t, 0)))
13772 int level, index;
13773 template_parm_level_and_index (parm, &level, &index);
13774 if (index == 0 && TMPL_ARGS_DEPTH (args) >= level)
13775 maybe_reuse = TMPL_ARGS_LEVEL (args, level);
13778 /* If the substituted result is identical to MAYBE_REUSE, return
13779 it and avoid allocating a new TREE_VEC, as an optimization. */
13780 if (maybe_reuse != NULL_TREE
13781 && TREE_VEC_LENGTH (maybe_reuse) == len
13782 && std::equal (elts, elts+len, TREE_VEC_BEGIN (maybe_reuse)))
13783 return maybe_reuse;
13785 /* If T consists of only a pack expansion for which substitution yielded
13786 a TREE_VEC of the expanded elements, then reuse that TREE_VEC instead
13787 of effectively making a copy. */
13788 if (len == 1
13789 && PACK_EXPANSION_P (TREE_VEC_ELT (t, 0))
13790 && TREE_CODE (elts[0]) == TREE_VEC)
13791 return elts[0];
13793 /* Make space for the expanded arguments coming from template
13794 argument packs. */
13795 tree r = make_tree_vec (len + expanded_len_adjust);
13796 /* T can contain TREE_VECs. That happens if T contains the
13797 arguments for a member template.
13798 In that case each TREE_VEC in T represents a level of template
13799 arguments, and T won't carry any non defaulted argument count.
13800 It will rather be the nested TREE_VECs that will carry one.
13801 In other words, T carries a non defaulted argument count only
13802 if it doesn't contain any nested TREE_VEC. */
13803 if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (t))
13805 int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
13806 count += expanded_len_adjust;
13807 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (r, count);
13810 int out = 0;
13811 for (int i = 0; i < len; i++)
13813 tree orig_arg = TREE_VEC_ELT (t, i);
13814 if (orig_arg
13815 && PACK_EXPANSION_P (orig_arg)
13816 && TREE_CODE (elts[i]) == TREE_VEC)
13818 /* Now expand the template argument pack "in place". */
13819 for (int idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
13820 TREE_VEC_ELT (r, out) = TREE_VEC_ELT (elts[i], idx);
13822 else
13824 TREE_VEC_ELT (r, out) = elts[i];
13825 out++;
13828 gcc_assert (out == TREE_VEC_LENGTH (r));
13830 return r;
13833 /* Substitute ARGS into one level PARMS of template parameters. */
13835 static tree
13836 tsubst_template_parms_level (tree parms, tree args, tsubst_flags_t complain)
13838 if (parms == error_mark_node)
13839 return error_mark_node;
13841 tree new_vec = make_tree_vec (TREE_VEC_LENGTH (parms));
13843 for (int i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
13845 tree tuple = TREE_VEC_ELT (parms, i);
13847 if (tuple == error_mark_node)
13848 continue;
13850 TREE_VEC_ELT (new_vec, i) =
13851 tsubst_template_parm (tuple, args, complain);
13854 return new_vec;
13857 /* Return the result of substituting ARGS into the template parameters
13858 given by PARMS. If there are m levels of ARGS and m + n levels of
13859 PARMS, then the result will contain n levels of PARMS. For
13860 example, if PARMS is `template <class T> template <class U>
13861 template <T*, U, class V>' and ARGS is {{int}, {double}} then the
13862 result will be `template <int*, double, class V>'. */
13864 static tree
13865 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
13867 tree r = NULL_TREE;
13868 tree* new_parms;
13870 /* When substituting into a template, we must set
13871 PROCESSING_TEMPLATE_DECL as the template parameters may be
13872 dependent if they are based on one-another, and the dependency
13873 predicates are short-circuit outside of templates. */
13874 ++processing_template_decl;
13876 for (new_parms = &r;
13877 parms && TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
13878 new_parms = &(TREE_CHAIN (*new_parms)),
13879 parms = TREE_CHAIN (parms))
13881 tree new_vec = tsubst_template_parms_level (TREE_VALUE (parms),
13882 args, complain);
13883 *new_parms =
13884 tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
13885 - TMPL_ARGS_DEPTH (args)),
13886 new_vec, NULL_TREE);
13887 TEMPLATE_PARMS_CONSTRAINTS (*new_parms)
13888 = TEMPLATE_PARMS_CONSTRAINTS (parms);
13891 --processing_template_decl;
13893 return r;
13896 /* Return the result of substituting ARGS into one template parameter
13897 given by T. T Must be a TREE_LIST which TREE_VALUE is the template
13898 parameter and which TREE_PURPOSE is the default argument of the
13899 template parameter. */
13901 static tree
13902 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
13904 tree default_value, parm_decl;
13906 if (args == NULL_TREE
13907 || t == NULL_TREE
13908 || t == error_mark_node)
13909 return t;
13911 gcc_assert (TREE_CODE (t) == TREE_LIST);
13913 default_value = TREE_PURPOSE (t);
13914 parm_decl = TREE_VALUE (t);
13916 parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
13917 if (TREE_CODE (parm_decl) == PARM_DECL
13918 && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
13919 parm_decl = error_mark_node;
13920 default_value = tsubst_template_arg (default_value, args,
13921 complain, NULL_TREE);
13923 tree r = build_tree_list (default_value, parm_decl);
13924 TEMPLATE_PARM_CONSTRAINTS (r) = TEMPLATE_PARM_CONSTRAINTS (t);
13925 return r;
13928 /* Substitute in-place the TEMPLATE_PARM_CONSTRAINTS of each template
13929 parameter in PARMS for sake of declaration matching. */
13931 static void
13932 tsubst_each_template_parm_constraints (tree parms, tree args,
13933 tsubst_flags_t complain)
13935 ++processing_template_decl;
13936 for (; parms; parms = TREE_CHAIN (parms))
13938 tree level = TREE_VALUE (parms);
13939 for (tree parm : tree_vec_range (level))
13940 TEMPLATE_PARM_CONSTRAINTS (parm)
13941 = tsubst_constraint (TEMPLATE_PARM_CONSTRAINTS (parm), args,
13942 complain, NULL_TREE);
13944 --processing_template_decl;
13947 /* Substitute the ARGS into the indicated aggregate (or enumeration)
13948 type T. If T is not an aggregate or enumeration type, it is
13949 handled as if by tsubst. IN_DECL is as for tsubst. If
13950 ENTERING_SCOPE is nonzero, T is the context for a template which
13951 we are presently tsubst'ing. Return the substituted value. */
13953 static tree
13954 tsubst_aggr_type (tree t,
13955 tree args,
13956 tsubst_flags_t complain,
13957 tree in_decl,
13958 int entering_scope)
13960 if (t == NULL_TREE)
13961 return NULL_TREE;
13963 /* Handle typedefs via tsubst so that they get consistently reused. */
13964 if (typedef_variant_p (t))
13966 t = tsubst (t, args, complain, in_decl);
13967 if (t == error_mark_node)
13968 return error_mark_node;
13970 /* The effect of entering_scope is that for a dependent specialization
13971 A<T>, lookup_template_class prefers to return A's primary template
13972 type instead of the implicit instantiation. So when entering_scope,
13973 we mirror this behavior by inspecting TYPE_CANONICAL appropriately,
13974 taking advantage of the fact that lookup_template_class links the two
13975 types by setting TYPE_CANONICAL of the latter to the former. */
13976 if (entering_scope
13977 && CLASS_TYPE_P (t)
13978 && dependent_type_p (t)
13979 && TYPE_TEMPLATE_INFO (t)
13980 && TYPE_CANONICAL (t) == TREE_TYPE (TYPE_TI_TEMPLATE (t)))
13981 t = TYPE_CANONICAL (t);
13983 return t;
13986 switch (TREE_CODE (t))
13988 case RECORD_TYPE:
13989 case ENUMERAL_TYPE:
13990 case UNION_TYPE:
13991 return tsubst_aggr_type_1 (t, args, complain, in_decl, entering_scope);
13993 default:
13994 return tsubst (t, args, complain, in_decl);
13998 /* The part of tsubst_aggr_type that's shared with the RECORD_, UNION_
13999 and ENUMERAL_TYPE cases of tsubst. */
14001 static tree
14002 tsubst_aggr_type_1 (tree t,
14003 tree args,
14004 tsubst_flags_t complain,
14005 tree in_decl,
14006 int entering_scope)
14008 if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
14010 complain &= ~tf_qualifying_scope;
14012 /* Figure out what arguments are appropriate for the
14013 type we are trying to find. For example, given:
14015 template <class T> struct S;
14016 template <class T, class U> void f(T, U) { S<U> su; }
14018 and supposing that we are instantiating f<int, double>,
14019 then our ARGS will be {int, double}, but, when looking up
14020 S we only want {double}. */
14021 tree argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
14022 complain, in_decl);
14023 if (argvec == error_mark_node)
14024 return error_mark_node;
14026 tree r = lookup_template_class (t, argvec, in_decl, NULL_TREE,
14027 entering_scope, complain);
14028 return cp_build_qualified_type (r, cp_type_quals (t), complain);
14030 else
14031 /* This is not a template type, so there's nothing to do. */
14032 return t;
14035 /* Map from a FUNCTION_DECL to a vec of default argument instantiations,
14036 indexed in reverse order of the parameters. */
14038 static GTY((cache)) hash_table<tree_vec_map_cache_hasher> *defarg_inst;
14040 /* Return a reference to the vec* of defarg insts for FN. */
14042 static vec<tree,va_gc> *&
14043 defarg_insts_for (tree fn)
14045 if (!defarg_inst)
14046 defarg_inst = hash_table<tree_vec_map_cache_hasher>::create_ggc (13);
14047 tree_vec_map in = { { fn }, nullptr };
14048 tree_vec_map **slot
14049 = defarg_inst->find_slot_with_hash (&in, DECL_UID (fn), INSERT);
14050 if (!*slot)
14052 *slot = ggc_alloc<tree_vec_map> ();
14053 **slot = in;
14055 return (*slot)->to;
14058 /* Substitute into the default argument ARG (a default argument for
14059 FN), which has the indicated TYPE. */
14061 tree
14062 tsubst_default_argument (tree fn, int parmnum, tree type, tree arg,
14063 tsubst_flags_t complain)
14065 int errs = errorcount + sorrycount;
14067 /* This can happen in invalid code. */
14068 if (TREE_CODE (arg) == DEFERRED_PARSE)
14069 return arg;
14071 /* Shortcut {}. */
14072 if (BRACE_ENCLOSED_INITIALIZER_P (arg)
14073 && CONSTRUCTOR_NELTS (arg) == 0)
14074 return arg;
14076 tree parm = FUNCTION_FIRST_USER_PARM (fn);
14077 parm = chain_index (parmnum, parm);
14078 tree parmtype = TREE_TYPE (parm);
14079 if (DECL_BY_REFERENCE (parm))
14080 parmtype = TREE_TYPE (parmtype);
14081 if (parmtype == error_mark_node)
14082 return error_mark_node;
14084 gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, parmtype));
14086 /* Remember the location of the pointer to the vec rather than the location
14087 of the particular element, in case the vec grows in tsubst_expr. */
14088 vec<tree,va_gc> *&defs = defarg_insts_for (fn);
14089 /* Index in reverse order to avoid allocating space for initial parameters
14090 that don't have default arguments. */
14091 unsigned ridx = list_length (parm);
14092 if (vec_safe_length (defs) < ridx)
14093 vec_safe_grow_cleared (defs, ridx);
14094 else if (tree inst = (*defs)[ridx - 1])
14095 return inst;
14097 /* This default argument came from a template. Instantiate the
14098 default argument here, not in tsubst. In the case of
14099 something like:
14101 template <class T>
14102 struct S {
14103 static T t();
14104 void f(T = t());
14107 we must be careful to do name lookup in the scope of S<T>,
14108 rather than in the current class. */
14109 push_to_top_level ();
14110 push_access_scope (fn);
14111 push_deferring_access_checks (dk_no_deferred);
14112 /* So in_immediate_context knows this is a default argument. */
14113 begin_scope (sk_function_parms, fn);
14114 start_lambda_scope (parm);
14116 /* The default argument expression may cause implicitly defined
14117 member functions to be synthesized, which will result in garbage
14118 collection. We must treat this situation as if we were within
14119 the body of function so as to avoid collecting live data on the
14120 stack. */
14121 ++function_depth;
14122 arg = tsubst_expr (arg, DECL_TI_ARGS (fn), complain, NULL_TREE);
14123 --function_depth;
14125 finish_lambda_scope ();
14127 /* Make sure the default argument is reasonable. */
14128 arg = check_default_argument (type, arg, complain);
14130 if (errorcount+sorrycount > errs
14131 && (complain & tf_warning_or_error))
14132 inform (input_location,
14133 " when instantiating default argument for call to %qD", fn);
14135 leave_scope ();
14136 pop_deferring_access_checks ();
14137 pop_access_scope (fn);
14138 pop_from_top_level ();
14140 if (arg != error_mark_node && !cp_unevaluated_operand)
14141 (*defs)[ridx - 1] = arg;
14143 return arg;
14146 /* Substitute into all the default arguments for FN. */
14148 static void
14149 tsubst_default_arguments (tree fn, tsubst_flags_t complain)
14151 tree arg;
14152 tree tmpl_args;
14154 tmpl_args = DECL_TI_ARGS (fn);
14156 /* If this function is not yet instantiated, we certainly don't need
14157 its default arguments. */
14158 if (uses_template_parms (tmpl_args))
14159 return;
14160 /* Don't do this again for clones. */
14161 if (DECL_CLONED_FUNCTION_P (fn))
14162 return;
14164 int i = 0;
14165 for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
14166 arg;
14167 arg = TREE_CHAIN (arg), ++i)
14168 if (TREE_PURPOSE (arg))
14169 TREE_PURPOSE (arg) = tsubst_default_argument (fn, i,
14170 TREE_VALUE (arg),
14171 TREE_PURPOSE (arg),
14172 complain);
14175 /* Hash table mapping a FUNCTION_DECL to its dependent explicit-specifier. */
14176 static GTY((cache)) decl_tree_cache_map *explicit_specifier_map;
14178 /* Store a pair to EXPLICIT_SPECIFIER_MAP. */
14180 void
14181 store_explicit_specifier (tree v, tree t)
14183 if (!explicit_specifier_map)
14184 explicit_specifier_map = decl_tree_cache_map::create_ggc (37);
14185 DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (v) = true;
14186 explicit_specifier_map->put (v, t);
14189 /* Lookup an element in EXPLICIT_SPECIFIER_MAP. */
14191 tree
14192 lookup_explicit_specifier (tree v)
14194 return *explicit_specifier_map->get (v);
14197 /* Given T, a FUNCTION_TYPE or METHOD_TYPE, construct and return a corresponding
14198 FUNCTION_TYPE or METHOD_TYPE whose return type is RETURN_TYPE, argument types
14199 are ARG_TYPES, and exception specification is RAISES, and otherwise is
14200 identical to T. */
14202 static tree
14203 rebuild_function_or_method_type (tree t, tree return_type, tree arg_types,
14204 tree raises, tsubst_flags_t complain)
14206 gcc_assert (FUNC_OR_METHOD_TYPE_P (t));
14208 tree new_type;
14209 if (TREE_CODE (t) == FUNCTION_TYPE)
14211 new_type = build_function_type (return_type, arg_types);
14212 new_type = apply_memfn_quals (new_type, type_memfn_quals (t));
14214 else
14216 tree r = TREE_TYPE (TREE_VALUE (arg_types));
14217 /* Don't pick up extra function qualifiers from the basetype. */
14218 r = cp_build_qualified_type (r, type_memfn_quals (t), complain);
14219 if (! MAYBE_CLASS_TYPE_P (r))
14221 /* [temp.deduct]
14223 Type deduction may fail for any of the following
14224 reasons:
14226 -- Attempting to create "pointer to member of T" when T
14227 is not a class type. */
14228 if (complain & tf_error)
14229 error ("creating pointer to member function of non-class type %qT",
14231 return error_mark_node;
14234 new_type = build_method_type_directly (r, return_type,
14235 TREE_CHAIN (arg_types));
14237 new_type = cp_build_type_attribute_variant (new_type, TYPE_ATTRIBUTES (t));
14239 cp_ref_qualifier rqual = type_memfn_rqual (t);
14240 bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
14241 return build_cp_fntype_variant (new_type, rqual, raises, late_return_type_p);
14244 /* Check if the function type of DECL, a FUNCTION_DECL, agrees with the type of
14245 each of its formal parameters. If there is a disagreement then rebuild
14246 DECL's function type according to its formal parameter types, as part of a
14247 resolution for Core issues 1001/1322. */
14249 static void
14250 maybe_rebuild_function_decl_type (tree decl)
14252 bool function_type_needs_rebuilding = false;
14253 if (tree parm_list = FUNCTION_FIRST_USER_PARM (decl))
14255 tree parm_type_list = FUNCTION_FIRST_USER_PARMTYPE (decl);
14256 while (parm_type_list && parm_type_list != void_list_node)
14258 tree parm_type = TREE_VALUE (parm_type_list);
14259 tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
14260 if (!same_type_p (parm_type, formal_parm_type_unqual))
14262 function_type_needs_rebuilding = true;
14263 break;
14266 parm_list = DECL_CHAIN (parm_list);
14267 parm_type_list = TREE_CHAIN (parm_type_list);
14271 if (!function_type_needs_rebuilding)
14272 return;
14274 const tree fntype = TREE_TYPE (decl);
14275 tree parm_list = DECL_ARGUMENTS (decl);
14276 tree old_parm_type_list = TYPE_ARG_TYPES (fntype);
14277 tree new_parm_type_list = NULL_TREE;
14278 tree *q = &new_parm_type_list;
14279 for (int skip = num_artificial_parms_for (decl); skip > 0; skip--)
14281 *q = copy_node (old_parm_type_list);
14282 parm_list = DECL_CHAIN (parm_list);
14283 old_parm_type_list = TREE_CHAIN (old_parm_type_list);
14284 q = &TREE_CHAIN (*q);
14286 while (old_parm_type_list && old_parm_type_list != void_list_node)
14288 *q = copy_node (old_parm_type_list);
14289 tree *new_parm_type = &TREE_VALUE (*q);
14290 tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
14291 if (!same_type_p (*new_parm_type, formal_parm_type_unqual))
14292 *new_parm_type = formal_parm_type_unqual;
14294 parm_list = DECL_CHAIN (parm_list);
14295 old_parm_type_list = TREE_CHAIN (old_parm_type_list);
14296 q = &TREE_CHAIN (*q);
14298 if (old_parm_type_list == void_list_node)
14299 *q = void_list_node;
14301 TREE_TYPE (decl)
14302 = rebuild_function_or_method_type (fntype,
14303 TREE_TYPE (fntype), new_parm_type_list,
14304 TYPE_RAISES_EXCEPTIONS (fntype), tf_none);
14307 /* Subroutine of tsubst_decl for the case when T is a FUNCTION_DECL. */
14309 static tree
14310 tsubst_function_decl (tree t, tree args, tsubst_flags_t complain,
14311 tree lambda_fntype, bool use_spec_table = true)
14313 tree gen_tmpl = NULL_TREE, argvec = NULL_TREE;
14314 hashval_t hash = 0;
14315 tree in_decl = t;
14317 /* Nobody should be tsubst'ing into non-template functions. */
14318 gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE
14319 || DECL_LOCAL_DECL_P (t));
14321 if (DECL_LOCAL_DECL_P (t))
14323 if (tree spec = retrieve_local_specialization (t))
14324 return spec;
14326 else if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
14328 /* If T is not dependent, just return it. */
14329 if (!uses_template_parms (DECL_TI_ARGS (t))
14330 && !LAMBDA_FUNCTION_P (t))
14331 return t;
14333 /* A non-templated friend doesn't get DECL_TEMPLATE_INFO. */
14334 if (non_templated_friend_p (t))
14335 goto friend_case;
14337 /* Calculate the most general template of which R is a
14338 specialization. */
14339 gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
14341 /* We're substituting a lambda function under tsubst_lambda_expr but not
14342 directly from it; find the matching function we're already inside.
14343 But don't do this if T is a generic lambda with a single level of
14344 template parms, as in that case we're doing a normal instantiation. */
14345 if (LAMBDA_FUNCTION_P (t) && !lambda_fntype
14346 && (!generic_lambda_fn_p (t)
14347 || TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)) > 1))
14348 return enclosing_instantiation_of (t);
14350 /* Calculate the complete set of arguments used to
14351 specialize R. */
14352 if (use_spec_table && !lambda_fntype)
14354 argvec = tsubst_template_args (DECL_TI_ARGS
14355 (DECL_TEMPLATE_RESULT
14356 (DECL_TI_TEMPLATE (t))),
14357 args, complain, in_decl);
14358 if (argvec == error_mark_node)
14359 return error_mark_node;
14361 /* Check to see if we already have this specialization. */
14362 hash = spec_hasher::hash (gen_tmpl, argvec);
14363 if (tree spec = retrieve_specialization (gen_tmpl, argvec, hash))
14364 /* The spec for these args might be a partial instantiation of the
14365 template, but here what we want is the FUNCTION_DECL. */
14366 return STRIP_TEMPLATE (spec);
14368 else
14369 argvec = args;
14371 else
14373 /* This special case arises when we have something like this:
14375 template <class T> struct S {
14376 friend void f<int>(int, double);
14379 Here, the DECL_TI_TEMPLATE for the friend declaration
14380 will be an IDENTIFIER_NODE. We are being called from
14381 tsubst_friend_function, and we want only to create a
14382 new decl (R) with appropriate types so that we can call
14383 determine_specialization. */
14384 friend_case:
14385 gen_tmpl = NULL_TREE;
14386 argvec = NULL_TREE;
14389 tree closure = (lambda_fntype ? TYPE_METHOD_BASETYPE (lambda_fntype)
14390 : NULL_TREE);
14391 tree ctx = closure ? closure : DECL_CONTEXT (t);
14392 bool member = ctx && TYPE_P (ctx);
14394 /* If this is a static lambda, remove the 'this' pointer added in
14395 tsubst_lambda_expr now that we know the closure type. */
14396 if (lambda_fntype && DECL_STATIC_FUNCTION_P (t))
14397 lambda_fntype = static_fn_type (lambda_fntype);
14399 if (member && !closure)
14400 ctx = tsubst_aggr_type (ctx, args,
14401 complain, t, /*entering_scope=*/1);
14403 tree type = (lambda_fntype ? lambda_fntype
14404 : tsubst (TREE_TYPE (t), args,
14405 complain | tf_fndecl_type, in_decl));
14406 if (type == error_mark_node)
14407 return error_mark_node;
14409 /* If we hit excessive deduction depth, the type is bogus even if
14410 it isn't error_mark_node, so don't build a decl. */
14411 if (excessive_deduction_depth)
14412 return error_mark_node;
14414 /* We do NOT check for matching decls pushed separately at this
14415 point, as they may not represent instantiations of this
14416 template, and in any case are considered separate under the
14417 discrete model. */
14418 tree r = copy_decl (t);
14419 DECL_USE_TEMPLATE (r) = 0;
14420 TREE_TYPE (r) = type;
14421 /* Clear out the mangled name and RTL for the instantiation. */
14422 SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
14423 SET_DECL_RTL (r, NULL);
14424 /* Leave DECL_INITIAL set on deleted instantiations. */
14425 if (!DECL_DELETED_FN (r))
14426 DECL_INITIAL (r) = NULL_TREE;
14427 DECL_CONTEXT (r) = ctx;
14428 set_instantiating_module (r);
14430 /* Handle explicit(dependent-expr). */
14431 if (DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (t))
14433 tree spec = lookup_explicit_specifier (t);
14434 spec = tsubst_expr (spec, args, complain, in_decl);
14435 spec = build_explicit_specifier (spec, complain);
14436 if (spec == error_mark_node)
14437 return error_mark_node;
14438 if (instantiation_dependent_expression_p (spec))
14439 store_explicit_specifier (r, spec);
14440 else
14442 DECL_NONCONVERTING_P (r) = (spec == boolean_true_node);
14443 DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (r) = false;
14447 /* OpenMP UDRs have the only argument a reference to the declared
14448 type. We want to diagnose if the declared type is a reference,
14449 which is invalid, but as references to references are usually
14450 quietly merged, diagnose it here. */
14451 if (DECL_OMP_DECLARE_REDUCTION_P (t))
14453 tree argtype
14454 = TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (t))));
14455 argtype = tsubst (argtype, args, complain, in_decl);
14456 if (TYPE_REF_P (argtype))
14457 error_at (DECL_SOURCE_LOCATION (t),
14458 "reference type %qT in "
14459 "%<#pragma omp declare reduction%>", argtype);
14460 if (strchr (IDENTIFIER_POINTER (DECL_NAME (t)), '~') == NULL)
14461 DECL_NAME (r) = omp_reduction_id (ERROR_MARK, DECL_NAME (t),
14462 argtype);
14465 if (member && DECL_CONV_FN_P (r))
14466 /* Type-conversion operator. Reconstruct the name, in
14467 case it's the name of one of the template's parameters. */
14468 DECL_NAME (r) = make_conv_op_name (TREE_TYPE (type));
14470 tree parms = DECL_ARGUMENTS (t);
14471 if (closure && !DECL_STATIC_FUNCTION_P (t))
14472 parms = DECL_CHAIN (parms);
14473 parms = tsubst (parms, args, complain, t);
14474 for (tree parm = parms; parm; parm = DECL_CHAIN (parm))
14475 DECL_CONTEXT (parm) = r;
14476 if (closure && !DECL_STATIC_FUNCTION_P (t))
14478 tree tparm = build_this_parm (r, closure, type_memfn_quals (type));
14479 DECL_NAME (tparm) = closure_identifier;
14480 DECL_CHAIN (tparm) = parms;
14481 parms = tparm;
14483 DECL_ARGUMENTS (r) = parms;
14484 DECL_RESULT (r) = NULL_TREE;
14486 maybe_rebuild_function_decl_type (r);
14488 TREE_STATIC (r) = 0;
14489 TREE_PUBLIC (r) = TREE_PUBLIC (t);
14490 DECL_EXTERNAL (r) = 1;
14491 /* If this is an instantiation of a function with internal
14492 linkage, we already know what object file linkage will be
14493 assigned to the instantiation. */
14494 DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
14495 DECL_DEFER_OUTPUT (r) = 0;
14496 DECL_CHAIN (r) = NULL_TREE;
14497 DECL_PENDING_INLINE_INFO (r) = 0;
14498 DECL_PENDING_INLINE_P (r) = 0;
14499 DECL_SAVED_TREE (r) = NULL_TREE;
14500 DECL_STRUCT_FUNCTION (r) = NULL;
14501 TREE_USED (r) = 0;
14502 /* We'll re-clone as appropriate in instantiate_template. */
14503 DECL_CLONED_FUNCTION (r) = NULL_TREE;
14505 /* If we aren't complaining now, return on error before we register
14506 the specialization so that we'll complain eventually. */
14507 if ((complain & tf_error) == 0
14508 && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
14509 && !grok_op_properties (r, /*complain=*/false))
14510 return error_mark_node;
14512 /* Associate the constraints directly with the instantiation. We
14513 don't substitute through the constraints; that's only done when
14514 they are checked. */
14515 if (tree ci = get_constraints (t))
14516 set_constraints (r, ci);
14518 if (DECL_FRIEND_CONTEXT (t))
14519 SET_DECL_FRIEND_CONTEXT (r,
14520 tsubst (DECL_FRIEND_CONTEXT (t),
14521 args, complain, in_decl));
14523 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14524 args, complain, in_decl))
14525 return error_mark_node;
14527 /* Set up the DECL_TEMPLATE_INFO for R. There's no need to do
14528 this in the special friend case mentioned above where
14529 GEN_TMPL is NULL. */
14530 if (gen_tmpl && !closure)
14532 DECL_TEMPLATE_INFO (r)
14533 = build_template_info (gen_tmpl, argvec);
14534 SET_DECL_IMPLICIT_INSTANTIATION (r);
14536 if (use_spec_table)
14538 tree new_r
14539 = register_specialization (r, gen_tmpl, argvec, false, hash);
14540 if (new_r != r)
14541 /* We instantiated this while substituting into
14542 the type earlier (template/friend54.C). */
14543 return new_r;
14546 /* We're not supposed to instantiate default arguments
14547 until they are called, for a template. But, for a
14548 declaration like:
14550 template <class T> void f ()
14551 { extern void g(int i = T()); }
14553 we should do the substitution when the template is
14554 instantiated. We handle the member function case in
14555 instantiate_class_template since the default arguments
14556 might refer to other members of the class. */
14557 if (!member
14558 && !PRIMARY_TEMPLATE_P (gen_tmpl)
14559 && !uses_template_parms (argvec))
14560 tsubst_default_arguments (r, complain);
14562 else if (DECL_LOCAL_DECL_P (r))
14564 if (!cp_unevaluated_operand)
14565 register_local_specialization (r, t);
14567 else
14568 DECL_TEMPLATE_INFO (r) = NULL_TREE;
14570 /* Copy the list of befriending classes. */
14571 for (tree *friends = &DECL_BEFRIENDING_CLASSES (r);
14572 *friends;
14573 friends = &TREE_CHAIN (*friends))
14575 *friends = copy_node (*friends);
14576 TREE_VALUE (*friends)
14577 = tsubst (TREE_VALUE (*friends), args, complain, in_decl);
14580 if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
14582 maybe_retrofit_in_chrg (r);
14583 if (DECL_CONSTRUCTOR_P (r) && !grok_ctor_properties (ctx, r))
14584 return error_mark_node;
14585 /* If this is an instantiation of a member template, clone it.
14586 If it isn't, that'll be handled by
14587 clone_constructors_and_destructors. */
14588 if (gen_tmpl && PRIMARY_TEMPLATE_P (gen_tmpl))
14589 clone_cdtor (r, /*update_methods=*/false);
14591 else if ((complain & tf_error) != 0
14592 && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
14593 && !grok_op_properties (r, /*complain=*/true))
14594 return error_mark_node;
14596 /* Possibly limit visibility based on template args. */
14597 DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
14598 if (DECL_VISIBILITY_SPECIFIED (t))
14600 DECL_VISIBILITY_SPECIFIED (r) = 0;
14601 DECL_ATTRIBUTES (r)
14602 = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
14604 determine_visibility (r);
14605 if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
14606 && !processing_template_decl)
14607 defaulted_late_check (r);
14609 if (flag_openmp)
14610 if (tree attr = lookup_attribute ("omp declare variant base",
14611 DECL_ATTRIBUTES (r)))
14612 omp_declare_variant_finalize (r, attr);
14614 return r;
14617 /* Subroutine of tsubst_decl for the case when T is a TEMPLATE_DECL. */
14619 static tree
14620 tsubst_template_decl (tree t, tree args, tsubst_flags_t complain,
14621 tree lambda_fntype, tree lambda_tparms)
14623 /* We can get here when processing a member function template,
14624 member class template, or template template parameter. */
14625 tree decl = DECL_TEMPLATE_RESULT (t);
14626 tree in_decl = t;
14627 tree spec;
14628 tree tmpl_args;
14629 tree full_args = NULL_TREE;
14630 tree r;
14631 hashval_t hash = 0;
14633 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
14635 /* Template template parameter is treated here. */
14636 tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14637 if (new_type == error_mark_node)
14638 r = error_mark_node;
14639 /* If we get a real template back, return it. This can happen in
14640 the context of most_specialized_partial_spec. */
14641 else if (TREE_CODE (new_type) == TEMPLATE_DECL)
14642 r = new_type;
14643 else
14644 /* The new TEMPLATE_DECL was built in
14645 reduce_template_parm_level. */
14646 r = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (new_type);
14647 return r;
14650 if (!lambda_fntype)
14652 /* We might already have an instance of this template.
14653 The ARGS are for the surrounding class type, so the
14654 full args contain the tsubst'd args for the context,
14655 plus the innermost args from the template decl. */
14656 tmpl_args = DECL_CLASS_TEMPLATE_P (t)
14657 ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
14658 : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
14659 /* Because this is a template, the arguments will still be
14660 dependent, even after substitution. If
14661 PROCESSING_TEMPLATE_DECL is not set, the dependency
14662 predicates will short-circuit. */
14663 ++processing_template_decl;
14664 full_args = tsubst_template_args (tmpl_args, args,
14665 complain, in_decl);
14666 --processing_template_decl;
14667 if (full_args == error_mark_node)
14668 return error_mark_node;
14670 /* If this is a default template template argument,
14671 tsubst might not have changed anything. */
14672 if (full_args == tmpl_args)
14673 return t;
14675 hash = spec_hasher::hash (t, full_args);
14676 spec = retrieve_specialization (t, full_args, hash);
14677 if (spec != NULL_TREE)
14679 if (TYPE_P (spec))
14680 /* Type partial instantiations are stored as the type by
14681 lookup_template_class_1, not here as the template. */
14682 spec = CLASSTYPE_TI_TEMPLATE (spec);
14683 else if (TREE_CODE (spec) != TEMPLATE_DECL)
14684 spec = DECL_TI_TEMPLATE (spec);
14685 return spec;
14689 /* Make a new template decl. It will be similar to the
14690 original, but will record the current template arguments.
14691 We also create a new function declaration, which is just
14692 like the old one, but points to this new template, rather
14693 than the old one. */
14694 r = copy_decl (t);
14695 gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
14696 DECL_CHAIN (r) = NULL_TREE;
14698 // Build new template info linking to the original template decl.
14699 if (!lambda_fntype)
14701 DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
14702 SET_DECL_IMPLICIT_INSTANTIATION (r);
14704 else
14705 DECL_TEMPLATE_INFO (r) = NULL_TREE;
14707 /* The template parameters for this new template are all the
14708 template parameters for the old template, except the
14709 outermost level of parameters. */
14710 auto tparm_guard = make_temp_override (current_template_parms);
14711 DECL_TEMPLATE_PARMS (r)
14712 = current_template_parms
14713 = (lambda_tparms
14714 ? lambda_tparms
14715 : tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
14716 complain));
14718 bool class_p = false;
14719 tree inner = decl;
14720 ++processing_template_decl;
14721 if (TREE_CODE (inner) == FUNCTION_DECL)
14722 inner = tsubst_function_decl (inner, args, complain, lambda_fntype,
14723 /*use_spec_table=*/false);
14724 else
14726 if (TREE_CODE (inner) == TYPE_DECL && !TYPE_DECL_ALIAS_P (inner))
14728 class_p = true;
14729 inner = TREE_TYPE (inner);
14731 if (class_p)
14732 inner = tsubst_aggr_type (inner, args, complain,
14733 in_decl, /*entering*/1);
14734 else
14735 inner = tsubst_decl (inner, args, complain, /*use_spec_table=*/false);
14737 --processing_template_decl;
14738 if (inner == error_mark_node)
14739 return error_mark_node;
14741 if (class_p)
14743 /* For a partial specialization, we need to keep pointing to
14744 the primary template. */
14745 if (!DECL_TEMPLATE_SPECIALIZATION (t))
14747 CLASSTYPE_TI_TEMPLATE (inner) = r;
14748 CLASSTYPE_USE_TEMPLATE (inner) = 0;
14751 DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (inner);
14752 inner = TYPE_MAIN_DECL (inner);
14754 else if (lambda_fntype)
14756 tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (r));
14757 DECL_TEMPLATE_INFO (inner) = build_template_info (r, args);
14759 else
14761 DECL_TI_TEMPLATE (inner) = r;
14762 /* Set DECL_TI_ARGS to the full set of template arguments,
14763 which tsubst_function_decl / tsubst_decl didn't do due to
14764 use_spec_table=false. */
14765 DECL_TI_ARGS (inner) = full_args;
14766 DECL_TI_ARGS (r) = DECL_TI_ARGS (inner);
14769 DECL_TEMPLATE_RESULT (r) = inner;
14770 TREE_TYPE (r) = TREE_TYPE (inner);
14771 DECL_CONTEXT (r) = DECL_CONTEXT (inner);
14773 if (modules_p ())
14775 /* Propagate module information from the decl. */
14776 DECL_MODULE_EXPORT_P (r) = DECL_MODULE_EXPORT_P (inner);
14777 if (DECL_LANG_SPECIFIC (inner))
14778 /* If this is a constrained template, the above tsubst of
14779 inner can find the unconstrained template, which may have
14780 come from an import. This is ok, because we don't
14781 register this instantiation (see below). */
14782 gcc_checking_assert (!DECL_MODULE_IMPORT_P (inner)
14783 || (TEMPLATE_PARMS_CONSTRAINTS
14784 (DECL_TEMPLATE_PARMS (t))));
14787 DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
14788 DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
14790 if (PRIMARY_TEMPLATE_P (t))
14791 DECL_PRIMARY_TEMPLATE (r) = r;
14793 if (!lambda_fntype && !class_p)
14795 /* Record this non-type partial instantiation. */
14796 /* FIXME we'd like to always register the TEMPLATE_DECL, or always
14797 the DECL_TEMPLATE_RESULT, but it seems the modules code relies
14798 on this current behavior. */
14799 if (TREE_CODE (inner) == FUNCTION_DECL)
14800 register_specialization (r, t, full_args, false, hash);
14801 else
14802 register_specialization (inner, t, full_args, false, hash);
14805 return r;
14808 /* True if FN is the op() for a lambda in an uninstantiated template. */
14810 bool
14811 lambda_fn_in_template_p (tree fn)
14813 if (!fn || !LAMBDA_FUNCTION_P (fn))
14814 return false;
14815 tree closure = DECL_CONTEXT (fn);
14816 return CLASSTYPE_TEMPLATE_INFO (closure) != NULL_TREE;
14819 /* True if FN is the substitution (via tsubst_lambda_expr) of a function for
14820 which the above is true. */
14822 bool
14823 regenerated_lambda_fn_p (tree fn)
14825 if (!fn || !LAMBDA_FUNCTION_P (fn))
14826 return false;
14827 tree closure = DECL_CONTEXT (fn);
14828 tree lam = CLASSTYPE_LAMBDA_EXPR (closure);
14829 return LAMBDA_EXPR_REGEN_INFO (lam) != NULL_TREE;
14832 /* Return the LAMBDA_EXPR from which T was ultimately regenerated.
14833 If T is not a regenerated LAMBDA_EXPR, return T. */
14835 tree
14836 most_general_lambda (tree t)
14838 while (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
14839 t = TI_TEMPLATE (ti);
14840 return t;
14843 /* Return the set of template arguments used to regenerate the lambda T
14844 from its most general lambda. */
14846 tree
14847 lambda_regenerating_args (tree t)
14849 if (LAMBDA_FUNCTION_P (t))
14850 t = CLASSTYPE_LAMBDA_EXPR (DECL_CONTEXT (t));
14851 gcc_assert (TREE_CODE (t) == LAMBDA_EXPR);
14852 if (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
14853 return TI_ARGS (ti);
14854 else
14855 return NULL_TREE;
14858 /* We're instantiating a variable from template function TCTX. Return the
14859 corresponding current enclosing scope. We can match them up using
14860 DECL_SOURCE_LOCATION because lambdas only ever have one source location, and
14861 the DECL_SOURCE_LOCATION for a function instantiation is updated to match
14862 the template definition in regenerate_decl_from_template. */
14864 static tree
14865 enclosing_instantiation_of (tree tctx)
14867 tree fn = current_function_decl;
14869 /* We shouldn't ever need to do this for other artificial functions. */
14870 gcc_assert (!DECL_ARTIFICIAL (tctx) || LAMBDA_FUNCTION_P (tctx));
14872 for (; fn; fn = decl_function_context (fn))
14873 if (DECL_SOURCE_LOCATION (fn) == DECL_SOURCE_LOCATION (tctx))
14874 return fn;
14875 gcc_unreachable ();
14878 /* Substitute the ARGS into the T, which is a _DECL. Return the
14879 result of the substitution. Issue error and warning messages under
14880 control of COMPLAIN. The flag USE_SPEC_TABLE controls if we look up
14881 and insert into the specializations table or if we can assume it's
14882 the caller's responsibility; this is used by instantiate_template
14883 to avoid doing some redundant work. */
14885 static tree
14886 tsubst_decl (tree t, tree args, tsubst_flags_t complain,
14887 bool use_spec_table /* = true */)
14889 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
14890 location_t saved_loc;
14891 tree r = NULL_TREE;
14892 tree in_decl = t;
14893 hashval_t hash = 0;
14895 if (t == error_mark_node)
14896 return error_mark_node;
14898 /* Set the filename and linenumber to improve error-reporting. */
14899 saved_loc = input_location;
14900 input_location = DECL_SOURCE_LOCATION (t);
14902 switch (TREE_CODE (t))
14904 case TEMPLATE_DECL:
14905 r = tsubst_template_decl (t, args, complain,
14906 /*lambda_fntype=*/NULL_TREE,
14907 /*lambda_tparms=*/NULL_TREE);
14908 break;
14910 case FUNCTION_DECL:
14911 r = tsubst_function_decl (t, args, complain, /*lambda*/NULL_TREE,
14912 use_spec_table);
14913 break;
14915 case PARM_DECL:
14917 tree type = NULL_TREE;
14918 int i, len = 1;
14919 tree expanded_types = NULL_TREE;
14920 tree prev_r = NULL_TREE;
14921 tree first_r = NULL_TREE;
14923 if (DECL_PACK_P (t))
14925 /* If there is a local specialization that isn't a
14926 parameter pack, it means that we're doing a "simple"
14927 substitution from inside tsubst_pack_expansion. Just
14928 return the local specialization (which will be a single
14929 parm). */
14930 tree spec = retrieve_local_specialization (t);
14931 if (spec
14932 && TREE_CODE (spec) == PARM_DECL
14933 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
14934 RETURN (spec);
14936 /* Expand the TYPE_PACK_EXPANSION that provides the types for
14937 the parameters in this function parameter pack. */
14938 expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
14939 complain, in_decl);
14940 if (TREE_CODE (expanded_types) == TREE_VEC)
14942 len = TREE_VEC_LENGTH (expanded_types);
14944 /* Zero-length parameter packs are boring. Just substitute
14945 into the chain. */
14946 if (len == 0 && !cp_unevaluated_operand)
14947 RETURN (tsubst (TREE_CHAIN (t), args, complain,
14948 TREE_CHAIN (t)));
14950 else
14952 /* All we did was update the type. Make a note of that. */
14953 type = expanded_types;
14954 expanded_types = NULL_TREE;
14958 /* Loop through all of the parameters we'll build. When T is
14959 a function parameter pack, LEN is the number of expanded
14960 types in EXPANDED_TYPES; otherwise, LEN is 1. */
14961 r = NULL_TREE;
14962 for (i = 0; i < len; ++i)
14964 prev_r = r;
14965 r = copy_node (t);
14966 if (DECL_TEMPLATE_PARM_P (t))
14967 SET_DECL_TEMPLATE_PARM_P (r);
14969 if (expanded_types)
14970 /* We're on the Ith parameter of the function parameter
14971 pack. */
14973 /* Get the Ith type. */
14974 type = TREE_VEC_ELT (expanded_types, i);
14976 /* Rename the parameter to include the index. */
14977 DECL_NAME (r)
14978 = make_ith_pack_parameter_name (DECL_NAME (r), i);
14980 else if (!type)
14981 /* We're dealing with a normal parameter. */
14982 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14984 type = type_decays_to (type);
14985 TREE_TYPE (r) = type;
14986 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
14988 if (DECL_INITIAL (r))
14990 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
14991 DECL_INITIAL (r) = TREE_TYPE (r);
14992 else
14993 DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
14994 complain, in_decl);
14997 DECL_CONTEXT (r) = NULL_TREE;
14999 if (!DECL_TEMPLATE_PARM_P (r))
15000 DECL_ARG_TYPE (r) = type_passed_as (type);
15002 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
15003 args, complain, in_decl))
15004 return error_mark_node;
15006 /* Keep track of the first new parameter we
15007 generate. That's what will be returned to the
15008 caller. */
15009 if (!first_r)
15010 first_r = r;
15012 /* Build a proper chain of parameters when substituting
15013 into a function parameter pack. */
15014 if (prev_r)
15015 DECL_CHAIN (prev_r) = r;
15018 /* If cp_unevaluated_operand is set, we're just looking for a
15019 single dummy parameter, so don't keep going. */
15020 if (DECL_CHAIN (t) && !cp_unevaluated_operand)
15021 DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
15022 complain, DECL_CHAIN (t));
15024 /* FIRST_R contains the start of the chain we've built. */
15025 r = first_r;
15027 break;
15029 case FIELD_DECL:
15031 tree type = NULL_TREE;
15032 tree vec = NULL_TREE;
15033 tree expanded_types = NULL_TREE;
15034 int len = 1;
15036 if (PACK_EXPANSION_P (TREE_TYPE (t)))
15038 /* This field is a lambda capture pack. Return a TREE_VEC of
15039 the expanded fields to instantiate_class_template_1. */
15040 expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
15041 complain, in_decl);
15042 if (TREE_CODE (expanded_types) == TREE_VEC)
15044 len = TREE_VEC_LENGTH (expanded_types);
15045 vec = make_tree_vec (len);
15047 else
15049 /* All we did was update the type. Make a note of that. */
15050 type = expanded_types;
15051 expanded_types = NULL_TREE;
15055 for (int i = 0; i < len; ++i)
15057 r = copy_decl (t);
15058 if (expanded_types)
15060 type = TREE_VEC_ELT (expanded_types, i);
15061 DECL_NAME (r)
15062 = make_ith_pack_parameter_name (DECL_NAME (r), i);
15064 else if (!type)
15065 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15067 if (type == error_mark_node)
15068 RETURN (error_mark_node);
15069 TREE_TYPE (r) = type;
15070 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
15072 if (DECL_C_BIT_FIELD (r))
15073 /* For bit-fields, DECL_BIT_FIELD_REPRESENTATIVE gives the
15074 number of bits. */
15075 DECL_BIT_FIELD_REPRESENTATIVE (r)
15076 = tsubst_expr (DECL_BIT_FIELD_REPRESENTATIVE (t), args,
15077 complain, in_decl);
15078 if (DECL_INITIAL (t))
15080 /* Set up DECL_TEMPLATE_INFO so that we can get at the
15081 NSDMI in perform_member_init. Still set DECL_INITIAL
15082 so that we know there is one. */
15083 DECL_INITIAL (r) = void_node;
15084 gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
15085 retrofit_lang_decl (r);
15086 DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
15088 /* We don't have to set DECL_CONTEXT here; it is set by
15089 finish_member_declaration. */
15090 DECL_CHAIN (r) = NULL_TREE;
15092 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
15093 args, complain, in_decl))
15094 return error_mark_node;
15096 if (vec)
15097 TREE_VEC_ELT (vec, i) = r;
15100 if (vec)
15101 r = vec;
15103 break;
15105 case USING_DECL:
15106 /* We reach here only for member using decls. We also need to check
15107 uses_template_parms because DECL_DEPENDENT_P is not set for a
15108 using-declaration that designates a member of the current
15109 instantiation (c++/53549). */
15110 if (DECL_DEPENDENT_P (t)
15111 || uses_template_parms (USING_DECL_SCOPE (t)))
15113 /* True iff this using-decl was written as a pack expansion
15114 (and a pack appeared in its scope or name). If a pack
15115 appeared in both, we expand the packs separately and
15116 manually merge them. */
15117 bool variadic_p = false;
15119 tree scope = USING_DECL_SCOPE (t);
15120 if (PACK_EXPANSION_P (scope))
15122 scope = tsubst_pack_expansion (scope, args,
15123 complain | tf_qualifying_scope,
15124 in_decl);
15125 variadic_p = true;
15127 else
15128 scope = tsubst_scope (scope, args, complain, in_decl);
15130 tree name = DECL_NAME (t);
15131 if (IDENTIFIER_CONV_OP_P (name)
15132 && PACK_EXPANSION_P (TREE_TYPE (name)))
15134 name = tsubst_pack_expansion (TREE_TYPE (name), args,
15135 complain, in_decl);
15136 if (name == error_mark_node)
15138 r = error_mark_node;
15139 break;
15141 for (tree& elt : tree_vec_range (name))
15142 elt = make_conv_op_name (elt);
15143 variadic_p = true;
15145 else
15146 name = tsubst_name (name, args, complain, in_decl);
15148 int len;
15149 if (!variadic_p)
15150 len = 1;
15151 else if (TREE_CODE (scope) == TREE_VEC
15152 && TREE_CODE (name) == TREE_VEC)
15154 if (TREE_VEC_LENGTH (scope) != TREE_VEC_LENGTH (name))
15156 error ("mismatched argument pack lengths (%d vs %d)",
15157 TREE_VEC_LENGTH (scope), TREE_VEC_LENGTH (name));
15158 r = error_mark_node;
15159 break;
15161 len = TREE_VEC_LENGTH (scope);
15163 else if (TREE_CODE (scope) == TREE_VEC)
15164 len = TREE_VEC_LENGTH (scope);
15165 else /* TREE_CODE (name) == TREE_VEC */
15166 len = TREE_VEC_LENGTH (name);
15168 r = make_tree_vec (len);
15169 for (int i = 0; i < len; ++i)
15171 tree escope = (TREE_CODE (scope) == TREE_VEC
15172 ? TREE_VEC_ELT (scope, i)
15173 : scope);
15174 tree ename = (TREE_CODE (name) == TREE_VEC
15175 ? TREE_VEC_ELT (name, i)
15176 : name);
15177 tree elt = do_class_using_decl (escope, ename);
15178 if (!elt)
15180 r = error_mark_node;
15181 break;
15183 TREE_PROTECTED (elt) = TREE_PROTECTED (t);
15184 TREE_PRIVATE (elt) = TREE_PRIVATE (t);
15185 TREE_VEC_ELT (r, i) = elt;
15188 if (!variadic_p && r != error_mark_node)
15189 r = TREE_VEC_ELT (r, 0);
15191 else
15193 r = copy_node (t);
15194 DECL_CHAIN (r) = NULL_TREE;
15196 break;
15198 case TYPE_DECL:
15199 case VAR_DECL:
15201 tree argvec = NULL_TREE;
15202 tree gen_tmpl = NULL_TREE;
15203 tree tmpl = NULL_TREE;
15204 tree type = NULL_TREE;
15206 if (TREE_TYPE (t) == error_mark_node)
15207 RETURN (error_mark_node);
15209 if (TREE_CODE (t) == TYPE_DECL
15210 && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
15212 /* If this is the canonical decl, we don't have to
15213 mess with instantiations, and often we can't (for
15214 typename, template type parms and such). Note that
15215 TYPE_NAME is not correct for the above test if
15216 we've copied the type for a typedef. */
15217 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15218 if (type == error_mark_node)
15219 RETURN (error_mark_node);
15220 r = TYPE_NAME (type);
15221 break;
15224 /* Check to see if we already have the specialization we
15225 need. */
15226 tree spec = NULL_TREE;
15227 bool local_p = false;
15228 tree ctx = DECL_CONTEXT (t);
15229 if (!(VAR_P (t) && DECL_LOCAL_DECL_P (t))
15230 && (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t)))
15232 local_p = false;
15233 if (DECL_CLASS_SCOPE_P (t))
15235 ctx = tsubst_aggr_type (ctx, args,
15236 complain,
15237 in_decl, /*entering_scope=*/1);
15238 if (DECL_SELF_REFERENCE_P (t))
15239 /* The context and type of an injected-class-name are
15240 the same, so we don't need to substitute both. */
15241 type = ctx;
15242 /* If CTX is unchanged, then T is in fact the
15243 specialization we want. That situation occurs when
15244 referencing a static data member within in its own
15245 class. We can use pointer equality, rather than
15246 same_type_p, because DECL_CONTEXT is always
15247 canonical... */
15248 if (ctx == DECL_CONTEXT (t)
15249 /* ... unless T is a member template; in which
15250 case our caller can be willing to create a
15251 specialization of that template represented
15252 by T. */
15253 && !(DECL_TI_TEMPLATE (t)
15254 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (t))))
15255 spec = t;
15258 if (!spec)
15260 tmpl = DECL_TI_TEMPLATE (t);
15261 if (use_spec_table)
15263 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
15264 if (argvec == error_mark_node)
15265 RETURN (error_mark_node);
15266 gen_tmpl = most_general_template (tmpl);
15267 hash = spec_hasher::hash (gen_tmpl, argvec);
15268 spec = retrieve_specialization (gen_tmpl, argvec, hash);
15270 else
15271 argvec = args;
15274 else
15276 if (!(VAR_P (t) && DECL_LOCAL_DECL_P (t)))
15277 /* Subsequent calls to pushdecl will fill this in. */
15278 ctx = NULL_TREE;
15279 /* A local variable. */
15280 local_p = true;
15281 /* Unless this is a reference to a static variable from an
15282 enclosing function, in which case we need to fill it in now. */
15283 if (TREE_STATIC (t))
15285 tree fn = enclosing_instantiation_of (DECL_CONTEXT (t));
15286 if (fn != current_function_decl)
15287 ctx = fn;
15289 spec = retrieve_local_specialization (t);
15291 /* If we already have the specialization we need, there is
15292 nothing more to do. */
15293 if (spec)
15295 r = spec;
15296 break;
15299 /* Create a new node for the specialization we need. */
15300 if (type == NULL_TREE)
15302 if (is_typedef_decl (t))
15303 type = DECL_ORIGINAL_TYPE (t);
15304 else
15305 type = TREE_TYPE (t);
15306 if (VAR_P (t)
15307 && VAR_HAD_UNKNOWN_BOUND (t)
15308 && type != error_mark_node)
15309 type = strip_array_domain (type);
15310 tsubst_flags_t tcomplain = complain;
15311 if (VAR_P (t))
15312 tcomplain |= tf_tst_ok;
15313 type = tsubst (type, args, tcomplain, in_decl);
15314 /* Substituting the type might have recursively instantiated this
15315 same alias (c++/86171). */
15316 if (use_spec_table && gen_tmpl && DECL_ALIAS_TEMPLATE_P (gen_tmpl)
15317 && (spec = retrieve_specialization (gen_tmpl, argvec, hash)))
15319 r = spec;
15320 break;
15323 if (type == error_mark_node && !(complain & tf_error))
15324 RETURN (error_mark_node);
15325 r = copy_decl (t);
15326 if (VAR_P (r))
15328 DECL_INITIALIZED_P (r) = 0;
15329 DECL_TEMPLATE_INSTANTIATED (r) = 0;
15330 if (TREE_CODE (type) == FUNCTION_TYPE)
15332 /* It may seem that this case cannot occur, since:
15334 typedef void f();
15335 void g() { f x; }
15337 declares a function, not a variable. However:
15339 typedef void f();
15340 template <typename T> void g() { T t; }
15341 template void g<f>();
15343 is an attempt to declare a variable with function
15344 type. */
15345 error ("variable %qD has function type",
15346 /* R is not yet sufficiently initialized, so we
15347 just use its name. */
15348 DECL_NAME (r));
15349 RETURN (error_mark_node);
15351 type = complete_type (type);
15352 /* Wait until cp_finish_decl to set this again, to handle
15353 circular dependency (template/instantiate6.C). */
15354 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
15355 type = check_var_type (DECL_NAME (r), type,
15356 DECL_SOURCE_LOCATION (r));
15357 if (DECL_HAS_VALUE_EXPR_P (t))
15359 tree ve = DECL_VALUE_EXPR (t);
15360 /* If the DECL_VALUE_EXPR is converted to the declared type,
15361 preserve the identity so that gimplify_type_sizes works. */
15362 bool nop = (TREE_CODE (ve) == NOP_EXPR);
15363 if (nop)
15364 ve = TREE_OPERAND (ve, 0);
15365 ve = tsubst_expr (ve, args, complain, in_decl);
15366 if (REFERENCE_REF_P (ve))
15368 gcc_assert (TYPE_REF_P (type));
15369 ve = TREE_OPERAND (ve, 0);
15371 if (nop)
15372 ve = build_nop (type, ve);
15373 else if (DECL_LANG_SPECIFIC (t)
15374 && DECL_OMP_PRIVATIZED_MEMBER (t)
15375 && TREE_CODE (ve) == COMPONENT_REF
15376 && TREE_CODE (TREE_OPERAND (ve, 1)) == FIELD_DECL
15377 && DECL_BIT_FIELD_TYPE (TREE_OPERAND (ve, 1)) == type)
15378 type = TREE_TYPE (ve);
15379 else
15380 gcc_checking_assert (TYPE_MAIN_VARIANT (TREE_TYPE (ve))
15381 == TYPE_MAIN_VARIANT (type));
15382 SET_DECL_VALUE_EXPR (r, ve);
15384 if (CP_DECL_THREAD_LOCAL_P (r)
15385 && !processing_template_decl)
15386 set_decl_tls_model (r, decl_default_tls_model (r));
15388 else if (DECL_SELF_REFERENCE_P (t))
15389 SET_DECL_SELF_REFERENCE_P (r);
15390 TREE_TYPE (r) = type;
15391 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
15392 DECL_CONTEXT (r) = ctx;
15393 /* Clear out the mangled name and RTL for the instantiation. */
15394 SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
15395 if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
15396 SET_DECL_RTL (r, NULL);
15397 set_instantiating_module (r);
15399 /* The initializer must not be expanded until it is required;
15400 see [temp.inst]. */
15401 DECL_INITIAL (r) = NULL_TREE;
15402 DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
15403 if (VAR_P (r))
15405 if (DECL_LANG_SPECIFIC (r))
15406 SET_DECL_DEPENDENT_INIT_P (r, false);
15408 SET_DECL_MODE (r, VOIDmode);
15410 /* Possibly limit visibility based on template args. */
15411 DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
15412 if (DECL_VISIBILITY_SPECIFIED (t))
15414 DECL_VISIBILITY_SPECIFIED (r) = 0;
15415 DECL_ATTRIBUTES (r)
15416 = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
15418 determine_visibility (r);
15421 if (!local_p)
15423 /* A static data member declaration is always marked
15424 external when it is declared in-class, even if an
15425 initializer is present. We mimic the non-template
15426 processing here. */
15427 DECL_EXTERNAL (r) = 1;
15428 if (DECL_NAMESPACE_SCOPE_P (t))
15429 DECL_NOT_REALLY_EXTERN (r) = 1;
15431 DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
15432 SET_DECL_IMPLICIT_INSTANTIATION (r);
15433 if (use_spec_table)
15434 register_specialization (r, gen_tmpl, argvec, false, hash);
15436 else
15438 if (DECL_LANG_SPECIFIC (r))
15439 DECL_TEMPLATE_INFO (r) = NULL_TREE;
15440 if (!cp_unevaluated_operand)
15441 register_local_specialization (r, t);
15444 DECL_CHAIN (r) = NULL_TREE;
15446 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
15447 /*flags=*/0,
15448 args, complain, in_decl))
15449 return error_mark_node;
15451 /* Preserve a typedef that names a type. */
15452 if (is_typedef_decl (r) && type != error_mark_node)
15454 DECL_ORIGINAL_TYPE (r) = NULL_TREE;
15455 set_underlying_type (r);
15457 /* common_handle_aligned_attribute doesn't apply the alignment
15458 to DECL_ORIGINAL_TYPE. */
15459 if (TYPE_USER_ALIGN (TREE_TYPE (t)))
15460 TREE_TYPE (r) = build_aligned_type (TREE_TYPE (r),
15461 TYPE_ALIGN (TREE_TYPE (t)));
15464 layout_decl (r, 0);
15466 break;
15468 default:
15469 gcc_unreachable ();
15471 #undef RETURN
15473 out:
15474 /* Restore the file and line information. */
15475 input_location = saved_loc;
15477 return r;
15480 /* Substitute into the complete parameter type list PARMS. */
15482 tree
15483 tsubst_function_parms (tree parms,
15484 tree args,
15485 tsubst_flags_t complain,
15486 tree in_decl)
15488 return tsubst_arg_types (parms, args, NULL_TREE, complain, in_decl);
15491 /* Substitute into the ARG_TYPES of a function type.
15492 If END is a TREE_CHAIN, leave it and any following types
15493 un-substituted. */
15495 static tree
15496 tsubst_arg_types (tree arg_types,
15497 tree args,
15498 tree end,
15499 tsubst_flags_t complain,
15500 tree in_decl)
15502 tree type = NULL_TREE;
15503 int len = 1;
15504 tree expanded_args = NULL_TREE;
15506 if (!arg_types || arg_types == void_list_node || arg_types == end)
15507 return arg_types;
15509 if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
15511 /* For a pack expansion, perform substitution on the
15512 entire expression. Later on, we'll handle the arguments
15513 one-by-one. */
15514 expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
15515 args, complain, in_decl);
15517 if (TREE_CODE (expanded_args) == TREE_VEC)
15518 /* So that we'll spin through the parameters, one by one. */
15519 len = TREE_VEC_LENGTH (expanded_args);
15520 else
15522 /* We only partially substituted into the parameter
15523 pack. Our type is TYPE_PACK_EXPANSION. */
15524 type = expanded_args;
15525 expanded_args = NULL_TREE;
15528 else
15529 type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
15531 /* Check if a substituted type is erroneous before substituting into
15532 the rest of the chain. */
15533 for (int i = 0; i < len; i++)
15535 if (expanded_args)
15536 type = TREE_VEC_ELT (expanded_args, i);
15538 if (type == error_mark_node)
15539 return error_mark_node;
15540 if (VOID_TYPE_P (type))
15542 if (complain & tf_error)
15544 error ("invalid parameter type %qT", type);
15545 if (in_decl)
15546 error ("in declaration %q+D", in_decl);
15548 return error_mark_node;
15552 /* We do not substitute into default arguments here. The standard
15553 mandates that they be instantiated only when needed, which is
15554 done in build_over_call. */
15555 tree default_arg = TREE_PURPOSE (arg_types);
15557 /* Except that we do substitute default arguments under tsubst_lambda_expr,
15558 since the new op() won't have any associated template arguments for us
15559 to refer to later. */
15560 if (lambda_fn_in_template_p (in_decl)
15561 || (in_decl && TREE_CODE (in_decl) == FUNCTION_DECL
15562 && DECL_LOCAL_DECL_P (in_decl)))
15563 default_arg = tsubst_expr (default_arg, args, complain, in_decl);
15565 tree remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
15566 args, end, complain, in_decl);
15567 if (remaining_arg_types == error_mark_node)
15568 return error_mark_node;
15570 for (int i = len-1; i >= 0; i--)
15572 if (expanded_args)
15573 type = TREE_VEC_ELT (expanded_args, i);
15575 /* Do array-to-pointer, function-to-pointer conversion, and ignore
15576 top-level qualifiers as required. */
15577 type = cv_unqualified (type_decays_to (type));
15579 if (default_arg && TREE_CODE (default_arg) == DEFERRED_PARSE)
15581 /* We've instantiated a template before its default arguments
15582 have been parsed. This can happen for a nested template
15583 class, and is not an error unless we require the default
15584 argument in a call of this function. */
15585 remaining_arg_types
15586 = tree_cons (default_arg, type, remaining_arg_types);
15587 vec_safe_push (DEFPARSE_INSTANTIATIONS (default_arg),
15588 remaining_arg_types);
15590 else
15591 remaining_arg_types
15592 = hash_tree_cons (default_arg, type, remaining_arg_types);
15595 return remaining_arg_types;
15598 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE. This routine does
15599 *not* handle the exception-specification for FNTYPE, because the
15600 initial substitution of explicitly provided template parameters
15601 during argument deduction forbids substitution into the
15602 exception-specification:
15604 [temp.deduct]
15606 All references in the function type of the function template to the
15607 corresponding template parameters are replaced by the specified tem-
15608 plate argument values. If a substitution in a template parameter or
15609 in the function type of the function template results in an invalid
15610 type, type deduction fails. [Note: The equivalent substitution in
15611 exception specifications is done only when the function is instanti-
15612 ated, at which point a program is ill-formed if the substitution
15613 results in an invalid type.] */
15615 static tree
15616 tsubst_function_type (tree t,
15617 tree args,
15618 tsubst_flags_t complain,
15619 tree in_decl)
15621 tree return_type;
15622 tree arg_types = NULL_TREE;
15624 /* The TYPE_CONTEXT is not used for function/method types. */
15625 gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
15627 /* DR 1227: Mixing immediate and non-immediate contexts in deduction
15628 failure. */
15629 bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
15631 if (late_return_type_p)
15633 /* Substitute the argument types. */
15634 arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
15635 complain, in_decl);
15636 if (arg_types == error_mark_node)
15637 return error_mark_node;
15639 tree save_ccp = current_class_ptr;
15640 tree save_ccr = current_class_ref;
15641 tree this_type = (TREE_CODE (t) == METHOD_TYPE
15642 ? TREE_TYPE (TREE_VALUE (arg_types)) : NULL_TREE);
15643 bool do_inject = this_type && CLASS_TYPE_P (this_type);
15644 if (do_inject)
15646 /* DR 1207: 'this' is in scope in the trailing return type. */
15647 inject_this_parameter (this_type, cp_type_quals (this_type));
15650 /* Substitute the return type. */
15651 return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15653 if (do_inject)
15655 current_class_ptr = save_ccp;
15656 current_class_ref = save_ccr;
15659 else
15660 /* Substitute the return type. */
15661 return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15663 if (return_type == error_mark_node)
15664 return error_mark_node;
15665 /* DR 486 clarifies that creation of a function type with an
15666 invalid return type is a deduction failure. */
15667 if (TREE_CODE (return_type) == ARRAY_TYPE
15668 || TREE_CODE (return_type) == FUNCTION_TYPE)
15670 if (complain & tf_error)
15672 if (TREE_CODE (return_type) == ARRAY_TYPE)
15673 error ("function returning an array");
15674 else
15675 error ("function returning a function");
15677 return error_mark_node;
15680 if (!late_return_type_p)
15682 /* Substitute the argument types. */
15683 arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
15684 complain, in_decl);
15685 if (arg_types == error_mark_node)
15686 return error_mark_node;
15689 /* Construct a new type node and return it. */
15690 return rebuild_function_or_method_type (t, return_type, arg_types,
15691 /*raises=*/NULL_TREE, complain);
15694 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE. Substitute the template
15695 ARGS into that specification, and return the substituted
15696 specification. If there is no specification, return NULL_TREE. */
15698 static tree
15699 tsubst_exception_specification (tree fntype,
15700 tree args,
15701 tsubst_flags_t complain,
15702 tree in_decl,
15703 bool defer_ok)
15705 tree specs;
15706 tree new_specs;
15708 specs = TYPE_RAISES_EXCEPTIONS (fntype);
15709 new_specs = NULL_TREE;
15710 if (specs && TREE_PURPOSE (specs))
15712 /* A noexcept-specifier. */
15713 tree expr = TREE_PURPOSE (specs);
15714 if (TREE_CODE (expr) == INTEGER_CST)
15715 new_specs = expr;
15716 else if (defer_ok)
15718 /* Defer instantiation of noexcept-specifiers to avoid
15719 excessive instantiations (c++/49107). */
15720 new_specs = make_node (DEFERRED_NOEXCEPT);
15721 if (DEFERRED_NOEXCEPT_SPEC_P (specs))
15723 /* We already partially instantiated this member template,
15724 so combine the new args with the old. */
15725 DEFERRED_NOEXCEPT_PATTERN (new_specs)
15726 = DEFERRED_NOEXCEPT_PATTERN (expr);
15727 DEFERRED_NOEXCEPT_ARGS (new_specs)
15728 = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
15730 else
15732 DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
15733 DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
15736 else
15738 if (DEFERRED_NOEXCEPT_SPEC_P (specs))
15740 args = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr),
15741 args);
15742 expr = DEFERRED_NOEXCEPT_PATTERN (expr);
15744 new_specs = tsubst_expr (expr, args, complain, in_decl);
15746 new_specs = build_noexcept_spec (new_specs, complain);
15747 /* We've instantiated a template before a noexcept-specifier
15748 contained therein has been parsed. This can happen for
15749 a nested template class:
15751 struct S {
15752 template<typename> struct B { B() noexcept(...); };
15753 struct A : B<int> { ... use B() ... };
15756 where completing B<int> will trigger instantiating the
15757 noexcept, even though we only parse it at the end of S. */
15758 if (UNPARSED_NOEXCEPT_SPEC_P (specs))
15760 gcc_checking_assert (defer_ok);
15761 vec_safe_push (DEFPARSE_INSTANTIATIONS (expr), new_specs);
15764 else if (specs)
15766 if (! TREE_VALUE (specs))
15767 new_specs = specs;
15768 else
15769 while (specs)
15771 tree spec;
15772 int i, len = 1;
15773 tree expanded_specs = NULL_TREE;
15775 if (PACK_EXPANSION_P (TREE_VALUE (specs)))
15777 /* Expand the pack expansion type. */
15778 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
15779 args, complain,
15780 in_decl);
15782 if (expanded_specs == error_mark_node)
15783 return error_mark_node;
15784 else if (TREE_CODE (expanded_specs) == TREE_VEC)
15785 len = TREE_VEC_LENGTH (expanded_specs);
15786 else
15788 /* We're substituting into a member template, so
15789 we got a TYPE_PACK_EXPANSION back. Add that
15790 expansion and move on. */
15791 gcc_assert (TREE_CODE (expanded_specs)
15792 == TYPE_PACK_EXPANSION);
15793 new_specs = add_exception_specifier (new_specs,
15794 expanded_specs,
15795 complain);
15796 specs = TREE_CHAIN (specs);
15797 continue;
15801 for (i = 0; i < len; ++i)
15803 if (expanded_specs)
15804 spec = TREE_VEC_ELT (expanded_specs, i);
15805 else
15806 spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
15807 if (spec == error_mark_node)
15808 return spec;
15809 new_specs = add_exception_specifier (new_specs, spec,
15810 complain);
15813 specs = TREE_CHAIN (specs);
15816 return new_specs;
15819 /* Substitute through a TREE_LIST of types or expressions, handling pack
15820 expansions. */
15822 tree
15823 tsubst_tree_list (tree t, tree args, tsubst_flags_t complain, tree in_decl)
15825 if (t == void_list_node)
15826 return t;
15828 tree purpose = TREE_PURPOSE (t);
15829 tree purposevec = NULL_TREE;
15830 if (!purpose)
15832 else if (PACK_EXPANSION_P (purpose))
15834 purpose = tsubst_pack_expansion (purpose, args, complain, in_decl);
15835 if (TREE_CODE (purpose) == TREE_VEC)
15836 purposevec = purpose;
15838 else if (TYPE_P (purpose))
15839 purpose = tsubst (purpose, args, complain, in_decl);
15840 else
15841 purpose = tsubst_expr (purpose, args, complain, in_decl);
15842 if (purpose == error_mark_node || purposevec == error_mark_node)
15843 return error_mark_node;
15845 tree value = TREE_VALUE (t);
15846 tree valuevec = NULL_TREE;
15847 if (!value)
15849 else if (PACK_EXPANSION_P (value))
15851 value = tsubst_pack_expansion (value, args, complain, in_decl);
15852 if (TREE_CODE (value) == TREE_VEC)
15853 valuevec = value;
15855 else if (TYPE_P (value))
15856 value = tsubst (value, args, complain, in_decl);
15857 else
15858 value = tsubst_expr (value, args, complain, in_decl);
15859 if (value == error_mark_node || valuevec == error_mark_node)
15860 return error_mark_node;
15862 tree chain = TREE_CHAIN (t);
15863 if (!chain)
15865 else if (TREE_CODE (chain) == TREE_LIST)
15866 chain = tsubst_tree_list (chain, args, complain, in_decl);
15867 else if (TYPE_P (chain))
15868 chain = tsubst (chain, args, complain, in_decl);
15869 else
15870 chain = tsubst_expr (chain, args, complain, in_decl);
15871 if (chain == error_mark_node)
15872 return error_mark_node;
15874 if (purpose == TREE_PURPOSE (t)
15875 && value == TREE_VALUE (t)
15876 && chain == TREE_CHAIN (t))
15877 return t;
15879 int len;
15880 /* Determine the number of arguments. */
15881 if (purposevec)
15883 len = TREE_VEC_LENGTH (purposevec);
15884 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
15886 else if (valuevec)
15887 len = TREE_VEC_LENGTH (valuevec);
15888 else
15889 len = 1;
15891 for (int i = len; i-- > 0; )
15893 if (purposevec)
15894 purpose = TREE_VEC_ELT (purposevec, i);
15895 if (valuevec)
15896 value = TREE_VEC_ELT (valuevec, i);
15898 if (value && TYPE_P (value))
15899 chain = hash_tree_cons (purpose, value, chain);
15900 else
15901 chain = tree_cons (purpose, value, chain);
15904 return chain;
15907 /* Take the tree structure T and replace template parameters used
15908 therein with the argument vector ARGS. IN_DECL is an associated
15909 decl for diagnostics. If an error occurs, returns ERROR_MARK_NODE.
15910 Issue error and warning messages under control of COMPLAIN. Note
15911 that we must be relatively non-tolerant of extensions here, in
15912 order to preserve conformance; if we allow substitutions that
15913 should not be allowed, we may allow argument deductions that should
15914 not succeed, and therefore report ambiguous overload situations
15915 where there are none. In theory, we could allow the substitution,
15916 but indicate that it should have failed, and allow our caller to
15917 make sure that the right thing happens, but we don't try to do this
15918 yet.
15920 This function is used for dealing with types, decls and the like;
15921 for expressions, use tsubst_expr or tsubst_copy. */
15923 tree
15924 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
15926 enum tree_code code;
15927 tree type, r = NULL_TREE;
15929 if (t == NULL_TREE || t == error_mark_node
15930 || t == integer_type_node
15931 || t == void_type_node
15932 || t == char_type_node
15933 || t == unknown_type_node
15934 || TREE_CODE (t) == NAMESPACE_DECL
15935 || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
15936 return t;
15938 tsubst_flags_t tst_ok_flag = (complain & tf_tst_ok);
15939 complain &= ~tf_tst_ok;
15941 tsubst_flags_t qualifying_scope_flag = (complain & tf_qualifying_scope);
15942 complain &= ~tf_qualifying_scope;
15944 if (DECL_P (t))
15945 return tsubst_decl (t, args, complain);
15947 if (args == NULL_TREE)
15948 return t;
15950 code = TREE_CODE (t);
15952 gcc_assert (code != IDENTIFIER_NODE);
15953 type = TREE_TYPE (t);
15955 gcc_assert (type != unknown_type_node);
15957 if (tree d = maybe_dependent_member_ref (t, args, complain, in_decl))
15958 return d;
15960 /* Reuse typedefs. We need to do this to handle dependent attributes,
15961 such as attribute aligned. */
15962 if (TYPE_P (t)
15963 && typedef_variant_p (t))
15965 tree decl = TYPE_NAME (t);
15967 if (alias_template_specialization_p (t, nt_opaque))
15969 /* DECL represents an alias template and we want to
15970 instantiate it. */
15971 tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15972 tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
15973 r = instantiate_alias_template (tmpl, gen_args, complain);
15975 else if (DECL_CLASS_SCOPE_P (decl)
15976 && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
15977 && uses_template_parms (DECL_CONTEXT (decl)))
15979 tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15980 tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
15981 r = retrieve_specialization (tmpl, gen_args, 0);
15983 else if (DECL_FUNCTION_SCOPE_P (decl)
15984 && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
15985 && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
15986 r = retrieve_local_specialization (decl);
15987 else
15988 /* The typedef is from a non-template context. */
15989 return t;
15991 if (r)
15993 r = TREE_TYPE (r);
15994 r = cp_build_qualified_type
15995 (r, cp_type_quals (t) | cp_type_quals (r),
15996 complain | tf_ignore_bad_quals);
15997 return r;
15999 else
16001 /* We don't have an instantiation yet, so drop the typedef. */
16002 int quals = cp_type_quals (t);
16003 t = DECL_ORIGINAL_TYPE (decl);
16004 t = cp_build_qualified_type (t, quals,
16005 complain | tf_ignore_bad_quals);
16009 bool fndecl_type = (complain & tf_fndecl_type);
16010 complain &= ~tf_fndecl_type;
16012 if (type
16013 && code != TYPENAME_TYPE
16014 && code != TEMPLATE_TYPE_PARM
16015 && code != TEMPLATE_PARM_INDEX
16016 && code != IDENTIFIER_NODE
16017 && code != FUNCTION_TYPE
16018 && code != METHOD_TYPE)
16019 type = tsubst (type, args, complain, in_decl);
16020 if (type == error_mark_node)
16021 return error_mark_node;
16023 switch (code)
16025 case RECORD_TYPE:
16026 if (TYPE_PTRMEMFUNC_P (t))
16027 return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
16028 /* Fall through. */
16029 case UNION_TYPE:
16030 case ENUMERAL_TYPE:
16031 return tsubst_aggr_type_1 (t, args, complain, in_decl,
16032 /*entering_scope=*/0);
16034 case ERROR_MARK:
16035 case IDENTIFIER_NODE:
16036 case VOID_TYPE:
16037 case OPAQUE_TYPE:
16038 case REAL_TYPE:
16039 case COMPLEX_TYPE:
16040 case VECTOR_TYPE:
16041 case BOOLEAN_TYPE:
16042 case NULLPTR_TYPE:
16043 case LANG_TYPE:
16044 return t;
16046 case INTEGER_TYPE:
16047 if (t == integer_type_node)
16048 return t;
16050 if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
16051 && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
16052 return t;
16055 tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
16057 max = tsubst_expr (omax, args, complain, in_decl);
16059 /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
16060 needed. */
16061 if (TREE_CODE (max) == NOP_EXPR
16062 && TREE_SIDE_EFFECTS (omax)
16063 && !TREE_TYPE (max))
16064 TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
16066 /* If we're in a partial instantiation, preserve the magic NOP_EXPR
16067 with TREE_SIDE_EFFECTS that indicates this is not an integral
16068 constant expression. */
16069 if (processing_template_decl
16070 && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
16072 gcc_assert (TREE_CODE (max) == NOP_EXPR);
16073 TREE_SIDE_EFFECTS (max) = 1;
16076 return compute_array_index_type (NULL_TREE, max, complain);
16079 case TEMPLATE_TYPE_PARM:
16080 if (template_placeholder_p (t))
16082 tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (t);
16083 tmpl = tsubst_expr (tmpl, args, complain, in_decl);
16084 if (TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
16085 tmpl = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (tmpl);
16087 if (tmpl != CLASS_PLACEHOLDER_TEMPLATE (t))
16088 return make_template_placeholder (tmpl);
16089 else
16090 return t;
16092 /* Fall through. */
16093 case TEMPLATE_TEMPLATE_PARM:
16094 case BOUND_TEMPLATE_TEMPLATE_PARM:
16095 case TEMPLATE_PARM_INDEX:
16097 int idx;
16098 int level;
16099 int levels;
16100 tree arg = NULL_TREE;
16102 r = NULL_TREE;
16104 gcc_assert (TREE_VEC_LENGTH (args) > 0);
16105 template_parm_level_and_index (t, &level, &idx);
16107 levels = TMPL_ARGS_DEPTH (args);
16108 if (level <= levels
16109 && TREE_VEC_LENGTH (TMPL_ARGS_LEVEL (args, level)) > 0)
16111 arg = TMPL_ARG (args, level, idx);
16113 /* See through ARGUMENT_PACK_SELECT arguments. */
16114 if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
16115 arg = argument_pack_select_arg (arg);
16118 if (arg == error_mark_node)
16119 return error_mark_node;
16120 else if (arg != NULL_TREE)
16122 if (ARGUMENT_PACK_P (arg))
16123 /* If ARG is an argument pack, we don't actually want to
16124 perform a substitution here, because substitutions
16125 for argument packs are only done
16126 element-by-element. We can get to this point when
16127 substituting the type of a non-type template
16128 parameter pack, when that type actually contains
16129 template parameter packs from an outer template, e.g.,
16131 template<typename... Types> struct A {
16132 template<Types... Values> struct B { };
16133 }; */
16134 return t;
16136 if (code == TEMPLATE_TYPE_PARM)
16138 int quals;
16140 /* When building concept checks for the purpose of
16141 deducing placeholders, we can end up with wildcards
16142 where types are expected. Adjust this to the deduced
16143 value. */
16144 if (TREE_CODE (arg) == WILDCARD_DECL)
16145 arg = TREE_TYPE (TREE_TYPE (arg));
16147 gcc_assert (TYPE_P (arg));
16149 quals = cp_type_quals (arg) | cp_type_quals (t);
16151 return cp_build_qualified_type
16152 (arg, quals, complain | tf_ignore_bad_quals);
16154 else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
16156 /* We are processing a type constructed from a
16157 template template parameter. */
16158 tree argvec = tsubst (TYPE_TI_ARGS (t),
16159 args, complain, in_decl);
16160 if (argvec == error_mark_node)
16161 return error_mark_node;
16163 gcc_assert (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
16164 || TREE_CODE (arg) == TEMPLATE_DECL
16165 || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
16167 if (TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
16168 /* Consider this code:
16170 template <template <class> class Template>
16171 struct Internal {
16172 template <class Arg> using Bind = Template<Arg>;
16175 template <template <class> class Template, class Arg>
16176 using Instantiate = Template<Arg>; //#0
16178 template <template <class> class Template,
16179 class Argument>
16180 using Bind =
16181 Instantiate<Internal<Template>::template Bind,
16182 Argument>; //#1
16184 When #1 is parsed, the
16185 BOUND_TEMPLATE_TEMPLATE_PARM representing the
16186 parameter `Template' in #0 matches the
16187 UNBOUND_CLASS_TEMPLATE representing the argument
16188 `Internal<Template>::template Bind'; We then want
16189 to assemble the type `Bind<Argument>' that can't
16190 be fully created right now, because
16191 `Internal<Template>' not being complete, the Bind
16192 template cannot be looked up in that context. So
16193 we need to "store" `Bind<Argument>' for later
16194 when the context of Bind becomes complete. Let's
16195 store that in a TYPENAME_TYPE. */
16196 return make_typename_type (TYPE_CONTEXT (arg),
16197 build_nt (TEMPLATE_ID_EXPR,
16198 TYPE_IDENTIFIER (arg),
16199 argvec),
16200 typename_type,
16201 complain);
16203 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
16204 are resolving nested-types in the signature of a
16205 member function templates. Otherwise ARG is a
16206 TEMPLATE_DECL and is the real template to be
16207 instantiated. */
16208 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
16209 arg = TYPE_NAME (arg);
16211 r = lookup_template_class (arg,
16212 argvec, in_decl,
16213 DECL_CONTEXT (arg),
16214 /*entering_scope=*/0,
16215 complain);
16216 return cp_build_qualified_type
16217 (r, cp_type_quals (t) | cp_type_quals (r), complain);
16219 else if (code == TEMPLATE_TEMPLATE_PARM)
16220 return arg;
16221 else
16222 /* TEMPLATE_PARM_INDEX. */
16223 return convert_from_reference (unshare_expr (arg));
16226 if (level == 1)
16227 /* This can happen during the attempted tsubst'ing in
16228 unify. This means that we don't yet have any information
16229 about the template parameter in question. */
16230 return t;
16232 /* Early in template argument deduction substitution, we don't
16233 want to reduce the level of 'auto', or it will be confused
16234 with a normal template parm in subsequent deduction.
16235 Similarly, don't reduce the level of template parameters to
16236 avoid mismatches when deducing their types. */
16237 if (complain & tf_partial)
16238 return t;
16240 /* If we get here, we must have been looking at a parm for a
16241 more deeply nested template. Make a new version of this
16242 template parameter, but with a lower level. */
16243 int quals;
16244 switch (code)
16246 case TEMPLATE_TYPE_PARM:
16247 case TEMPLATE_TEMPLATE_PARM:
16248 quals = cp_type_quals (t);
16249 if (quals)
16251 gcc_checking_assert (code == TEMPLATE_TYPE_PARM);
16252 t = TYPE_MAIN_VARIANT (t);
16255 if (tree d = TEMPLATE_TYPE_DESCENDANTS (t))
16256 if (TEMPLATE_PARM_LEVEL (d) == TEMPLATE_TYPE_LEVEL (t) - levels
16257 && (code == TEMPLATE_TYPE_PARM
16258 || TEMPLATE_TEMPLATE_PARM_SIMPLE_P (t)))
16259 /* Cache lowering a type parameter or a simple template
16260 template parameter. */
16261 r = TREE_TYPE (d);
16263 if (!r)
16265 r = copy_type (t);
16266 TEMPLATE_TYPE_PARM_INDEX (r)
16267 = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
16268 r, levels, args, complain);
16269 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
16270 TYPE_MAIN_VARIANT (r) = r;
16271 TYPE_POINTER_TO (r) = NULL_TREE;
16272 TYPE_REFERENCE_TO (r) = NULL_TREE;
16274 if (code == TEMPLATE_TYPE_PARM)
16275 if (tree ci = PLACEHOLDER_TYPE_CONSTRAINTS_INFO (t))
16276 /* Propagate constraints on placeholders since they are
16277 only instantiated during satisfaction. */
16278 PLACEHOLDER_TYPE_CONSTRAINTS_INFO (r) = ci;
16280 if (TYPE_STRUCTURAL_EQUALITY_P (t))
16281 SET_TYPE_STRUCTURAL_EQUALITY (r);
16282 else
16283 TYPE_CANONICAL (r) = canonical_type_parameter (r);
16286 if (quals)
16287 r = cp_build_qualified_type (r, quals,
16288 complain | tf_ignore_bad_quals);
16289 break;
16291 case BOUND_TEMPLATE_TEMPLATE_PARM:
16293 tree tinfo = TYPE_TEMPLATE_INFO (t);
16294 /* We might need to substitute into the types of non-type
16295 template parameters. This also lowers the level of
16296 the ttp appropriately. */
16297 tree tmpl = tsubst (TI_TEMPLATE (tinfo), args,
16298 complain, in_decl);
16299 if (tmpl == error_mark_node)
16300 return error_mark_node;
16301 tree argvec = tsubst (TI_ARGS (tinfo), args,
16302 complain, in_decl);
16303 if (argvec == error_mark_node)
16304 return error_mark_node;
16305 r = lookup_template_class (tmpl, argvec, in_decl, NULL_TREE,
16306 /*entering_scope=*/false, complain);
16307 r = cp_build_qualified_type (r, cp_type_quals (t), complain);
16308 break;
16311 case TEMPLATE_PARM_INDEX:
16312 /* OK, now substitute the type of the non-type parameter. We
16313 couldn't do it earlier because it might be an auto parameter,
16314 and we wouldn't need to if we had an argument. */
16315 type = tsubst (type, args, complain, in_decl);
16316 if (type == error_mark_node)
16317 return error_mark_node;
16318 r = reduce_template_parm_level (t, type, levels, args, complain);
16319 break;
16321 default:
16322 gcc_unreachable ();
16325 return r;
16328 case TREE_LIST:
16329 return tsubst_tree_list (t, args, complain, in_decl);
16331 case TREE_BINFO:
16332 /* We should never be tsubsting a binfo. */
16333 gcc_unreachable ();
16335 case TREE_VEC:
16336 /* A vector of template arguments. */
16337 gcc_assert (!type);
16338 return tsubst_template_args (t, args, complain, in_decl);
16340 case POINTER_TYPE:
16341 case REFERENCE_TYPE:
16343 if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
16344 return t;
16346 /* [temp.deduct]
16348 Type deduction may fail for any of the following
16349 reasons:
16351 -- Attempting to create a pointer to reference type.
16352 -- Attempting to create a reference to a reference type or
16353 a reference to void.
16355 Core issue 106 says that creating a reference to a reference
16356 during instantiation is no longer a cause for failure. We
16357 only enforce this check in strict C++98 mode. */
16358 if ((TYPE_REF_P (type)
16359 && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
16360 || (code == REFERENCE_TYPE && VOID_TYPE_P (type)))
16362 static location_t last_loc;
16364 /* We keep track of the last time we issued this error
16365 message to avoid spewing a ton of messages during a
16366 single bad template instantiation. */
16367 if (complain & tf_error
16368 && last_loc != input_location)
16370 if (VOID_TYPE_P (type))
16371 error ("forming reference to void");
16372 else if (code == POINTER_TYPE)
16373 error ("forming pointer to reference type %qT", type);
16374 else
16375 error ("forming reference to reference type %qT", type);
16376 last_loc = input_location;
16379 return error_mark_node;
16381 else if (TREE_CODE (type) == FUNCTION_TYPE
16382 && (type_memfn_quals (type) != TYPE_UNQUALIFIED
16383 || type_memfn_rqual (type) != REF_QUAL_NONE))
16385 if (complain & tf_error)
16387 if (code == POINTER_TYPE)
16388 error ("forming pointer to qualified function type %qT",
16389 type);
16390 else
16391 error ("forming reference to qualified function type %qT",
16392 type);
16394 return error_mark_node;
16396 else if (code == POINTER_TYPE)
16398 r = build_pointer_type (type);
16399 if (TREE_CODE (type) == METHOD_TYPE)
16400 r = build_ptrmemfunc_type (r);
16402 else if (TYPE_REF_P (type))
16403 /* In C++0x, during template argument substitution, when there is an
16404 attempt to create a reference to a reference type, reference
16405 collapsing is applied as described in [14.3.1/4 temp.arg.type]:
16407 "If a template-argument for a template-parameter T names a type
16408 that is a reference to a type A, an attempt to create the type
16409 'lvalue reference to cv T' creates the type 'lvalue reference to
16410 A,' while an attempt to create the type type rvalue reference to
16411 cv T' creates the type T"
16413 r = cp_build_reference_type
16414 (TREE_TYPE (type),
16415 TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
16416 else
16417 r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
16418 r = cp_build_qualified_type (r, cp_type_quals (t), complain);
16420 if (r != error_mark_node)
16421 /* Will this ever be needed for TYPE_..._TO values? */
16422 layout_type (r);
16424 return r;
16426 case OFFSET_TYPE:
16428 r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
16429 if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
16431 /* [temp.deduct]
16433 Type deduction may fail for any of the following
16434 reasons:
16436 -- Attempting to create "pointer to member of T" when T
16437 is not a class type. */
16438 if (complain & tf_error)
16439 error ("creating pointer to member of non-class type %qT", r);
16440 return error_mark_node;
16442 if (TYPE_REF_P (type))
16444 if (complain & tf_error)
16445 error ("creating pointer to member reference type %qT", type);
16446 return error_mark_node;
16448 if (VOID_TYPE_P (type))
16450 if (complain & tf_error)
16451 error ("creating pointer to member of type void");
16452 return error_mark_node;
16454 gcc_assert (TREE_CODE (type) != METHOD_TYPE);
16455 if (TREE_CODE (type) == FUNCTION_TYPE)
16457 /* The type of the implicit object parameter gets its
16458 cv-qualifiers from the FUNCTION_TYPE. */
16459 tree memptr;
16460 tree method_type
16461 = build_memfn_type (type, r, type_memfn_quals (type),
16462 type_memfn_rqual (type));
16463 memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
16464 return cp_build_qualified_type (memptr, cp_type_quals (t),
16465 complain);
16467 else
16468 return cp_build_qualified_type (build_ptrmem_type (r, type),
16469 cp_type_quals (t),
16470 complain);
16472 case FUNCTION_TYPE:
16473 case METHOD_TYPE:
16475 tree fntype;
16476 tree specs;
16477 fntype = tsubst_function_type (t, args, complain, in_decl);
16478 if (fntype == error_mark_node)
16479 return error_mark_node;
16481 /* Substitute the exception specification. */
16482 specs = tsubst_exception_specification (t, args, complain, in_decl,
16483 /*defer_ok*/fndecl_type);
16484 if (specs == error_mark_node)
16485 return error_mark_node;
16486 if (specs)
16487 fntype = build_exception_variant (fntype, specs);
16488 return fntype;
16490 case ARRAY_TYPE:
16492 tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
16493 if (domain == error_mark_node)
16494 return error_mark_node;
16496 /* As an optimization, we avoid regenerating the array type if
16497 it will obviously be the same as T. */
16498 if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
16499 return t;
16501 /* These checks should match the ones in create_array_type_for_decl.
16503 [temp.deduct]
16505 The deduction may fail for any of the following reasons:
16507 -- Attempting to create an array with an element type that
16508 is void, a function type, or a reference type, or [DR337]
16509 an abstract class type. */
16510 if (VOID_TYPE_P (type)
16511 || TREE_CODE (type) == FUNCTION_TYPE
16512 || (TREE_CODE (type) == ARRAY_TYPE
16513 && TYPE_DOMAIN (type) == NULL_TREE)
16514 || TYPE_REF_P (type))
16516 if (complain & tf_error)
16517 error ("creating array of %qT", type);
16518 return error_mark_node;
16521 if (!verify_type_context (input_location, TCTX_ARRAY_ELEMENT, type,
16522 !(complain & tf_error)))
16523 return error_mark_node;
16525 r = build_cplus_array_type (type, domain);
16527 if (!valid_array_size_p (input_location, r, in_decl,
16528 (complain & tf_error)))
16529 return error_mark_node;
16531 if (TYPE_USER_ALIGN (t))
16533 SET_TYPE_ALIGN (r, TYPE_ALIGN (t));
16534 TYPE_USER_ALIGN (r) = 1;
16537 return r;
16540 case TYPENAME_TYPE:
16542 tree ctx = TYPE_CONTEXT (t);
16543 if (TREE_CODE (ctx) == TYPE_PACK_EXPANSION)
16545 ctx = tsubst_pack_expansion (ctx, args,
16546 complain | tf_qualifying_scope,
16547 in_decl);
16548 if (ctx == error_mark_node
16549 || TREE_VEC_LENGTH (ctx) > 1)
16550 return error_mark_node;
16551 if (TREE_VEC_LENGTH (ctx) == 0)
16553 if (complain & tf_error)
16554 error ("%qD is instantiated for an empty pack",
16555 TYPENAME_TYPE_FULLNAME (t));
16556 return error_mark_node;
16558 ctx = TREE_VEC_ELT (ctx, 0);
16560 else
16561 ctx = tsubst_aggr_type (ctx, args,
16562 complain | tf_qualifying_scope,
16563 in_decl, /*entering_scope=*/1);
16564 if (ctx == error_mark_node)
16565 return error_mark_node;
16567 tree f = tsubst_name (TYPENAME_TYPE_FULLNAME (t), args,
16568 complain, in_decl);
16569 if (f == error_mark_node)
16570 return error_mark_node;
16572 if (!MAYBE_CLASS_TYPE_P (ctx))
16574 if (complain & tf_error)
16575 error ("%qT is not a class, struct, or union type", ctx);
16576 return error_mark_node;
16578 else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
16580 /* Normally, make_typename_type does not require that the CTX
16581 have complete type in order to allow things like:
16583 template <class T> struct S { typename S<T>::X Y; };
16585 But, such constructs have already been resolved by this
16586 point, so here CTX really should have complete type, unless
16587 it's a partial instantiation. */
16588 if (!complete_type_or_maybe_complain (ctx, NULL_TREE, complain))
16589 return error_mark_node;
16592 /* FIXME: TYPENAME_IS_CLASS_P conflates 'class' vs 'struct' vs 'union'
16593 tags. TYPENAME_TYPE should probably remember the exact tag that
16594 was written. */
16595 enum tag_types tag_type
16596 = TYPENAME_IS_CLASS_P (t) ? class_type
16597 : TYPENAME_IS_ENUM_P (t) ? enum_type
16598 : typename_type;
16599 tsubst_flags_t tcomplain = complain | tf_keep_type_decl;
16600 tcomplain |= tst_ok_flag | qualifying_scope_flag;
16601 f = make_typename_type (ctx, f, tag_type, tcomplain);
16602 if (f == error_mark_node)
16603 return f;
16604 if (TREE_CODE (f) == TYPE_DECL)
16606 complain |= tf_ignore_bad_quals;
16607 f = TREE_TYPE (f);
16610 if (TREE_CODE (f) != TYPENAME_TYPE)
16612 if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
16614 if (complain & tf_error)
16615 error ("%qT resolves to %qT, which is not an enumeration type",
16616 t, f);
16617 else
16618 return error_mark_node;
16620 else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
16622 if (complain & tf_error)
16623 error ("%qT resolves to %qT, which is not a class type",
16624 t, f);
16625 else
16626 return error_mark_node;
16630 return cp_build_qualified_type
16631 (f, cp_type_quals (f) | cp_type_quals (t), complain);
16634 case UNBOUND_CLASS_TEMPLATE:
16636 tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
16637 in_decl, /*entering_scope=*/1);
16638 tree name = TYPE_IDENTIFIER (t);
16639 tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
16641 if (ctx == error_mark_node || name == error_mark_node)
16642 return error_mark_node;
16644 if (parm_list)
16645 parm_list = tsubst_template_parms (parm_list, args, complain);
16646 return make_unbound_class_template (ctx, name, parm_list, complain);
16649 case TYPEOF_TYPE:
16651 tree type;
16653 ++cp_unevaluated_operand;
16654 ++c_inhibit_evaluation_warnings;
16656 type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args, complain, in_decl);
16658 --cp_unevaluated_operand;
16659 --c_inhibit_evaluation_warnings;
16661 type = finish_typeof (type);
16662 return cp_build_qualified_type (type,
16663 cp_type_quals (t)
16664 | cp_type_quals (type),
16665 complain);
16668 case DECLTYPE_TYPE:
16670 tree type;
16672 ++cp_unevaluated_operand;
16673 ++c_inhibit_evaluation_warnings;
16675 type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
16676 complain|tf_decltype, in_decl);
16678 --cp_unevaluated_operand;
16679 --c_inhibit_evaluation_warnings;
16681 if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
16682 type = lambda_capture_field_type (type,
16683 false /*explicit_init*/,
16684 DECLTYPE_FOR_REF_CAPTURE (t));
16685 else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
16686 type = lambda_proxy_type (type);
16687 else
16689 bool id = DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t);
16690 if (id && TREE_CODE (DECLTYPE_TYPE_EXPR (t)) == BIT_NOT_EXPR
16691 && EXPR_P (type))
16692 /* In a template ~id could be either a complement expression
16693 or an unqualified-id naming a destructor; if instantiating
16694 it produces an expression, it's not an id-expression or
16695 member access. */
16696 id = false;
16697 type = finish_decltype_type (type, id, complain);
16699 return cp_build_qualified_type (type,
16700 cp_type_quals (t)
16701 | cp_type_quals (type),
16702 complain | tf_ignore_bad_quals);
16705 case TRAIT_TYPE:
16707 tree type1 = TRAIT_TYPE_TYPE1 (t);
16708 if (TYPE_P (type1))
16709 type1 = tsubst (type1, args, complain, in_decl);
16710 else
16711 type1 = tsubst_expr (type1, args, complain, in_decl);
16712 tree type2 = tsubst (TRAIT_TYPE_TYPE2 (t), args, complain, in_decl);
16713 type = finish_trait_type (TRAIT_TYPE_KIND (t), type1, type2, complain);
16714 return cp_build_qualified_type (type,
16715 cp_type_quals (t) | cp_type_quals (type),
16716 complain | tf_ignore_bad_quals);
16719 case TYPE_ARGUMENT_PACK:
16720 case NONTYPE_ARGUMENT_PACK:
16721 return tsubst_argument_pack (t, args, complain, in_decl);
16723 case VOID_CST:
16724 case INTEGER_CST:
16725 case REAL_CST:
16726 case STRING_CST:
16727 case PLUS_EXPR:
16728 case MINUS_EXPR:
16729 case NEGATE_EXPR:
16730 case NOP_EXPR:
16731 case INDIRECT_REF:
16732 case ADDR_EXPR:
16733 case CALL_EXPR:
16734 case ARRAY_REF:
16735 case SCOPE_REF:
16736 /* We should use one of the expression tsubsts for these codes. */
16737 gcc_unreachable ();
16739 default:
16740 sorry ("use of %qs in template", get_tree_code_name (code));
16741 return error_mark_node;
16745 /* Convenience wrapper over tsubst for substituting into the LHS
16746 of the :: scope resolution operator. */
16748 static tree
16749 tsubst_scope (tree t, tree args, tsubst_flags_t complain, tree in_decl)
16751 gcc_checking_assert (TYPE_P (t));
16752 return tsubst (t, args, complain | tf_qualifying_scope, in_decl);
16755 /* Convenience wrapper over tsubst for substituting into an id-expression
16756 without resolving its terminal name. */
16758 static tree
16759 tsubst_name (tree t, tree args, tsubst_flags_t complain, tree in_decl)
16761 return tsubst_expr (t, args, complain | tf_no_name_lookup, in_decl);
16764 /* OLDFNS is a lookup set of member functions from some class template, and
16765 NEWFNS is a lookup set of member functions from NEWTYPE, a specialization
16766 of that class template. Return the subset of NEWFNS which are
16767 specializations of a function from OLDFNS. */
16769 static tree
16770 filter_memfn_lookup (tree oldfns, tree newfns, tree newtype)
16772 /* Record all member functions from the old lookup set OLDFNS into
16773 VISIBLE_SET. */
16774 hash_set<tree> visible_set;
16775 bool seen_dep_using = false;
16776 for (tree fn : lkp_range (oldfns))
16778 if (TREE_CODE (fn) == USING_DECL)
16780 /* Imprecisely handle dependent using-decl by keeping all members
16781 in the new lookup set that are defined in a base class, i.e.
16782 members that could plausibly have been introduced by this
16783 dependent using-decl.
16784 FIXME: Track which members are introduced by a dependent
16785 using-decl precisely, perhaps by performing another lookup
16786 from the substituted USING_DECL_SCOPE. */
16787 gcc_checking_assert (DECL_DEPENDENT_P (fn));
16788 seen_dep_using = true;
16790 else
16791 visible_set.add (fn);
16794 /* Returns true iff (a less specialized version of) FN appeared in
16795 the old lookup set OLDFNS. */
16796 auto visible_p = [newtype, seen_dep_using, &visible_set] (tree fn) {
16797 if (DECL_CONTEXT (fn) != newtype)
16798 /* FN is a member function from a base class, introduced via a
16799 using-decl; if it might have been introduced by a dependent
16800 using-decl then just conservatively keep it, otherwise look
16801 in the old lookup set for FN exactly. */
16802 return seen_dep_using || visible_set.contains (fn);
16803 else if (TREE_CODE (fn) == TEMPLATE_DECL)
16804 /* FN is a member function template from the current class;
16805 look in the old lookup set for the TEMPLATE_DECL from which
16806 it was specialized. */
16807 return visible_set.contains (DECL_TI_TEMPLATE (fn));
16808 else
16809 /* FN is a non-template member function from the current class;
16810 look in the old lookup set for the FUNCTION_DECL from which
16811 it was specialized. */
16812 return visible_set.contains (DECL_TEMPLATE_RESULT
16813 (DECL_TI_TEMPLATE (fn)));
16816 bool lookup_changed_p = false;
16817 for (tree fn : lkp_range (newfns))
16818 if (!visible_p (fn))
16820 lookup_changed_p = true;
16821 break;
16823 if (!lookup_changed_p)
16824 return newfns;
16826 /* Filter out from NEWFNS the member functions that weren't
16827 previously visible according to OLDFNS. */
16828 tree filtered_fns = NULL_TREE;
16829 unsigned filtered_size = 0;
16830 for (tree fn : lkp_range (newfns))
16831 if (visible_p (fn))
16833 filtered_fns = lookup_add (fn, filtered_fns);
16834 filtered_size++;
16836 gcc_checking_assert (seen_dep_using
16837 ? filtered_size >= visible_set.elements ()
16838 : filtered_size == visible_set.elements ());
16840 return filtered_fns;
16843 /* tsubst a BASELINK. OBJECT_TYPE, if non-NULL, is the type of the
16844 expression on the left-hand side of the "." or "->" operator. We
16845 only do the lookup if we had a dependent BASELINK. Otherwise we
16846 adjust it onto the instantiated heirarchy. */
16848 static tree
16849 tsubst_baselink (tree baselink, tree object_type,
16850 tree args, tsubst_flags_t complain, tree in_decl)
16852 bool qualified_p = BASELINK_QUALIFIED_P (baselink);
16853 tree qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
16854 qualifying_scope = tsubst (qualifying_scope, args, complain, in_decl);
16856 tree optype = BASELINK_OPTYPE (baselink);
16857 optype = tsubst (optype, args, complain, in_decl);
16859 tree template_args = NULL_TREE;
16860 bool template_id_p = false;
16861 tree fns = BASELINK_FUNCTIONS (baselink);
16862 if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
16864 template_id_p = true;
16865 template_args = TREE_OPERAND (fns, 1);
16866 fns = TREE_OPERAND (fns, 0);
16867 if (template_args)
16868 template_args = tsubst_template_args (template_args, args,
16869 complain, in_decl);
16872 tree binfo_type = BINFO_TYPE (BASELINK_BINFO (baselink));
16873 binfo_type = tsubst (binfo_type, args, complain, in_decl);
16874 bool dependent_p = (binfo_type != BINFO_TYPE (BASELINK_BINFO (baselink))
16875 || optype != BASELINK_OPTYPE (baselink));
16877 if (dependent_p)
16879 tree name = OVL_NAME (fns);
16880 if (IDENTIFIER_CONV_OP_P (name))
16881 name = make_conv_op_name (optype);
16883 /* See maybe_dependent_member_ref. */
16884 if ((complain & tf_dguide) && dependent_scope_p (qualifying_scope))
16886 if (template_id_p)
16887 name = build2 (TEMPLATE_ID_EXPR, unknown_type_node, name,
16888 template_args);
16889 return build_qualified_name (NULL_TREE, qualifying_scope, name,
16890 /* ::template */false);
16893 if (name == complete_dtor_identifier)
16894 /* Treat as-if non-dependent below. */
16895 dependent_p = false;
16897 bool maybe_incomplete = BASELINK_FUNCTIONS_MAYBE_INCOMPLETE_P (baselink);
16898 baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1,
16899 complain);
16900 if (maybe_incomplete)
16902 /* Filter out from the new lookup set those functions which didn't
16903 appear in the original lookup set (in a less specialized form).
16904 This is needed to preserve the consistency of member lookup
16905 performed in an incomplete-class context, within which
16906 later-declared members ought to remain invisible. */
16907 BASELINK_FUNCTIONS (baselink)
16908 = filter_memfn_lookup (fns, BASELINK_FUNCTIONS (baselink),
16909 binfo_type);
16910 BASELINK_FUNCTIONS_MAYBE_INCOMPLETE_P (baselink) = true;
16913 if (!baselink)
16915 if ((complain & tf_error)
16916 && constructor_name_p (name, qualifying_scope))
16917 error ("cannot call constructor %<%T::%D%> directly",
16918 qualifying_scope, name);
16919 return error_mark_node;
16922 fns = BASELINK_FUNCTIONS (baselink);
16924 else
16926 /* We're going to overwrite pieces below, make a duplicate. */
16927 baselink = copy_node (baselink);
16929 if (qualifying_scope != BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink)))
16931 /* The decl we found was from non-dependent scope, but we still need
16932 to update the binfos for the instantiated qualifying_scope. */
16933 BASELINK_ACCESS_BINFO (baselink) = TYPE_BINFO (qualifying_scope);
16934 BASELINK_BINFO (baselink) = lookup_base (qualifying_scope, binfo_type,
16935 ba_unique, nullptr, complain);
16939 /* If lookup found a single function, mark it as used at this point.
16940 (If lookup found multiple functions the one selected later by
16941 overload resolution will be marked as used at that point.) */
16942 if (!template_id_p && !really_overloaded_fn (fns))
16944 tree fn = OVL_FIRST (fns);
16945 bool ok = mark_used (fn, complain);
16946 if (!ok && !(complain & tf_error))
16947 return error_mark_node;
16948 if (ok && BASELINK_P (baselink))
16949 /* We might have instantiated an auto function. */
16950 TREE_TYPE (baselink) = TREE_TYPE (fn);
16953 if (BASELINK_P (baselink))
16955 /* Add back the template arguments, if present. */
16956 if (template_id_p)
16957 BASELINK_FUNCTIONS (baselink)
16958 = build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, template_args);
16960 /* Update the conversion operator type. */
16961 BASELINK_OPTYPE (baselink) = optype;
16964 if (!object_type)
16965 object_type = current_class_type;
16967 if (qualified_p || !dependent_p)
16969 baselink = adjust_result_of_qualified_name_lookup (baselink,
16970 qualifying_scope,
16971 object_type);
16972 if (!qualified_p)
16973 /* We need to call adjust_result_of_qualified_name_lookup in case the
16974 destructor names a base class, but we unset BASELINK_QUALIFIED_P
16975 so that we still get virtual function binding. */
16976 BASELINK_QUALIFIED_P (baselink) = false;
16979 return baselink;
16982 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID. DONE is
16983 true if the qualified-id will be a postfix-expression in-and-of
16984 itself; false if more of the postfix-expression follows the
16985 QUALIFIED_ID. ADDRESS_P is true if the qualified-id is the operand
16986 of "&". */
16988 static tree
16989 tsubst_qualified_id (tree qualified_id, tree args,
16990 tsubst_flags_t complain, tree in_decl,
16991 bool done, bool address_p)
16993 tree expr;
16994 tree scope;
16995 tree name;
16996 bool is_template;
16997 tree template_args;
16998 location_t loc = EXPR_LOCATION (qualified_id);
17000 gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
17002 /* Figure out what name to look up. */
17003 name = TREE_OPERAND (qualified_id, 1);
17004 if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
17006 is_template = true;
17007 template_args = TREE_OPERAND (name, 1);
17008 if (template_args)
17009 template_args = tsubst_template_args (template_args, args,
17010 complain, in_decl);
17011 if (template_args == error_mark_node)
17012 return error_mark_node;
17013 name = TREE_OPERAND (name, 0);
17015 else
17017 is_template = false;
17018 template_args = NULL_TREE;
17021 /* Substitute into the qualifying scope. When there are no ARGS, we
17022 are just trying to simplify a non-dependent expression. In that
17023 case the qualifying scope may be dependent, and, in any case,
17024 substituting will not help. */
17025 scope = TREE_OPERAND (qualified_id, 0);
17026 if (args)
17028 scope = tsubst_scope (scope, args, complain, in_decl);
17029 expr = tsubst_name (name, args, complain, in_decl);
17031 else
17032 expr = name;
17034 if (dependent_scope_p (scope))
17036 if (TREE_CODE (expr) == SCOPE_REF)
17037 /* We built one in tsubst_baselink. */
17038 gcc_checking_assert (same_type_p (scope, TREE_OPERAND (expr, 0)));
17039 else
17041 if (is_template)
17042 expr = build_min_nt_loc (loc, TEMPLATE_ID_EXPR, expr,
17043 template_args);
17044 expr = build_qualified_name (NULL_TREE, scope, expr,
17045 QUALIFIED_NAME_IS_TEMPLATE
17046 (qualified_id));
17048 REF_PARENTHESIZED_P (expr) = REF_PARENTHESIZED_P (qualified_id);
17049 return expr;
17052 if (!BASELINK_P (name) && !DECL_P (expr))
17054 if (TREE_CODE (expr) == BIT_NOT_EXPR)
17056 /* A BIT_NOT_EXPR is used to represent a destructor. */
17057 if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
17059 error ("qualifying type %qT does not match destructor name ~%qT",
17060 scope, TREE_OPERAND (expr, 0));
17061 expr = error_mark_node;
17063 else
17064 expr = lookup_qualified_name (scope, complete_dtor_identifier,
17065 LOOK_want::NORMAL, false);
17067 else
17068 expr = lookup_qualified_name (scope, expr, LOOK_want::NORMAL, false);
17069 if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
17070 ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
17072 if (complain & tf_error)
17074 error ("dependent-name %qE is parsed as a non-type, but "
17075 "instantiation yields a type", qualified_id);
17076 inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
17078 return error_mark_node;
17082 if (DECL_P (expr))
17084 if (!check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
17085 scope, complain))
17086 return error_mark_node;
17087 /* Remember that there was a reference to this entity. */
17088 if (!mark_used (expr, complain) && !(complain & tf_error))
17089 return error_mark_node;
17092 if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
17094 if (complain & tf_error)
17095 qualified_name_lookup_error (scope,
17096 TREE_OPERAND (qualified_id, 1),
17097 expr, input_location);
17098 return error_mark_node;
17101 if (is_template)
17103 /* We may be repeating a check already done during parsing, but
17104 if it was well-formed and passed then, it will pass again
17105 now, and if it didn't, we wouldn't have got here. The case
17106 we want to catch is when we couldn't tell then, and can now,
17107 namely when templ prior to substitution was an
17108 identifier. */
17109 if (flag_concepts && check_auto_in_tmpl_args (expr, template_args))
17110 return error_mark_node;
17112 if (variable_template_p (expr))
17113 expr = lookup_and_finish_template_variable (expr, template_args,
17114 complain);
17115 else
17116 expr = lookup_template_function (expr, template_args);
17119 if (expr == error_mark_node && complain & tf_error)
17120 qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
17121 expr, input_location);
17122 else if (TYPE_P (scope))
17124 expr = (adjust_result_of_qualified_name_lookup
17125 (expr, scope, current_nonlambda_class_type ()));
17126 expr = (finish_qualified_id_expr
17127 (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
17128 QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
17129 /*template_arg_p=*/false, complain));
17132 /* Expressions do not generally have reference type. */
17133 if (TREE_CODE (expr) != SCOPE_REF
17134 /* However, if we're about to form a pointer-to-member, we just
17135 want the referenced member referenced. */
17136 && TREE_CODE (expr) != OFFSET_REF)
17137 expr = convert_from_reference (expr);
17139 if (REF_PARENTHESIZED_P (qualified_id))
17140 expr = force_paren_expr (expr);
17142 expr = maybe_wrap_with_location (expr, loc);
17144 return expr;
17147 /* tsubst the initializer for a VAR_DECL. INIT is the unsubstituted
17148 initializer, DECL is the substituted VAR_DECL. Other arguments are as
17149 for tsubst. */
17151 static tree
17152 tsubst_init (tree init, tree decl, tree args,
17153 tsubst_flags_t complain, tree in_decl)
17155 if (!init)
17156 return NULL_TREE;
17158 init = tsubst_expr (init, args, complain, in_decl);
17160 tree type = TREE_TYPE (decl);
17162 if (!init && type != error_mark_node)
17164 if (tree auto_node = type_uses_auto (type))
17166 if (!CLASS_PLACEHOLDER_TEMPLATE (auto_node))
17168 if (complain & tf_error)
17169 error ("initializer for %q#D expands to an empty list "
17170 "of expressions", decl);
17171 return error_mark_node;
17174 else if (!dependent_type_p (type))
17176 /* If we had an initializer but it
17177 instantiated to nothing,
17178 value-initialize the object. This will
17179 only occur when the initializer was a
17180 pack expansion where the parameter packs
17181 used in that expansion were of length
17182 zero. */
17183 init = build_value_init (type, complain);
17184 if (TREE_CODE (init) == AGGR_INIT_EXPR)
17185 init = get_target_expr (init, complain);
17186 if (TREE_CODE (init) == TARGET_EXPR)
17187 TARGET_EXPR_DIRECT_INIT_P (init) = true;
17191 return init;
17194 /* If T is a reference to a dependent member of the current instantiation C and
17195 we are trying to refer to that member in a partial instantiation of C,
17196 return a SCOPE_REF; otherwise, return NULL_TREE.
17198 This can happen when forming a C++17 deduction guide, as in PR96199. */
17200 static tree
17201 maybe_dependent_member_ref (tree t, tree args, tsubst_flags_t complain,
17202 tree in_decl)
17204 if (!(complain & tf_dguide))
17205 return NULL_TREE;
17207 tree decl = (t && TYPE_P (t)) ? TYPE_NAME (t) : t;
17208 if (!decl || !DECL_P (decl))
17209 return NULL_TREE;
17211 tree ctx = context_for_name_lookup (decl);
17212 if (!CLASS_TYPE_P (ctx))
17213 return NULL_TREE;
17215 ctx = tsubst (ctx, args, complain, in_decl);
17216 if (!dependent_scope_p (ctx))
17217 return NULL_TREE;
17219 if (TYPE_P (t))
17221 if (typedef_variant_p (t))
17222 t = strip_typedefs (t);
17223 tree decl = TYPE_NAME (t);
17224 if (decl)
17225 decl = maybe_dependent_member_ref (decl, args, complain, in_decl);
17226 if (!decl)
17227 return NULL_TREE;
17228 return cp_build_qualified_type (TREE_TYPE (decl), cp_type_quals (t),
17229 complain);
17232 tree name = DECL_NAME (t);
17233 tree fullname = name;
17234 if (instantiates_primary_template_p (t))
17236 tree tinfo = get_template_info (t);
17237 name = DECL_NAME (TI_TEMPLATE (tinfo));
17238 tree targs = INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo));
17239 targs = tsubst_template_args (targs, args, complain, in_decl);
17240 fullname = build_nt (TEMPLATE_ID_EXPR, name, targs);
17243 if (TREE_CODE (t) == TYPE_DECL)
17245 if (TREE_CODE (TREE_TYPE (t)) == TYPENAME_TYPE
17246 && TYPE_NAME (TREE_TYPE (t)) == t)
17247 /* The TYPE_DECL for a typename has DECL_CONTEXT of the typename
17248 scope, but it doesn't need to be rewritten again. */
17249 return NULL_TREE;
17250 tree type = build_typename_type (ctx, name, fullname, typename_type);
17251 return TYPE_NAME (type);
17253 else if (DECL_TYPE_TEMPLATE_P (t))
17254 return make_unbound_class_template (ctx, name,
17255 NULL_TREE, complain);
17256 else
17257 return build_qualified_name (NULL_TREE, ctx, fullname,
17258 TREE_CODE (t) == TEMPLATE_DECL);
17261 /* Helper function for tsubst_omp_clauses, used for instantiation of
17262 OMP_CLAUSE_DECL of clauses. */
17264 static tree
17265 tsubst_omp_clause_decl (tree decl, tree args, tsubst_flags_t complain,
17266 tree in_decl, tree *iterator_cache)
17268 if (decl == NULL_TREE || decl == ridpointers[RID_OMP_ALL_MEMORY])
17269 return decl;
17271 /* Handle OpenMP iterators. */
17272 if (TREE_CODE (decl) == TREE_LIST
17273 && TREE_PURPOSE (decl)
17274 && TREE_CODE (TREE_PURPOSE (decl)) == TREE_VEC)
17276 tree ret;
17277 if (iterator_cache[0] == TREE_PURPOSE (decl))
17278 ret = iterator_cache[1];
17279 else
17281 tree *tp = &ret;
17282 begin_scope (sk_omp, NULL);
17283 for (tree it = TREE_PURPOSE (decl); it; it = TREE_CHAIN (it))
17285 *tp = copy_node (it);
17286 TREE_VEC_ELT (*tp, 0)
17287 = tsubst_decl (TREE_VEC_ELT (it, 0), args, complain);
17288 DECL_CONTEXT (TREE_VEC_ELT (*tp, 0)) = current_function_decl;
17289 pushdecl (TREE_VEC_ELT (*tp, 0));
17290 TREE_VEC_ELT (*tp, 1)
17291 = tsubst_stmt (TREE_VEC_ELT (it, 1), args, complain, in_decl);
17292 TREE_VEC_ELT (*tp, 2)
17293 = tsubst_stmt (TREE_VEC_ELT (it, 2), args, complain, in_decl);
17294 TREE_VEC_ELT (*tp, 3)
17295 = tsubst_stmt (TREE_VEC_ELT (it, 3), args, complain, in_decl);
17296 TREE_CHAIN (*tp) = NULL_TREE;
17297 tp = &TREE_CHAIN (*tp);
17299 TREE_VEC_ELT (ret, 5) = poplevel (1, 1, 0);
17300 iterator_cache[0] = TREE_PURPOSE (decl);
17301 iterator_cache[1] = ret;
17303 return build_tree_list (ret, tsubst_omp_clause_decl (TREE_VALUE (decl),
17304 args, complain,
17305 in_decl, NULL));
17308 /* Handle an OpenMP array section represented as a TREE_LIST (or
17309 OMP_CLAUSE_DOACROSS_KIND). An OMP_CLAUSE_DOACROSS (with a depend
17310 kind of OMP_CLAUSE_DOACROSS_SINK) can also be represented as a
17311 TREE_LIST. We can handle it exactly the same as an array section
17312 (purpose, value, and a chain), even though the nomenclature
17313 (low_bound, length, etc) is different. */
17314 if (TREE_CODE (decl) == TREE_LIST)
17316 tree low_bound
17317 = tsubst_stmt (TREE_PURPOSE (decl), args, complain, in_decl);
17318 tree length = tsubst_stmt (TREE_VALUE (decl), args, complain, in_decl);
17319 tree chain = tsubst_omp_clause_decl (TREE_CHAIN (decl), args, complain,
17320 in_decl, NULL);
17321 if (TREE_PURPOSE (decl) == low_bound
17322 && TREE_VALUE (decl) == length
17323 && TREE_CHAIN (decl) == chain)
17324 return decl;
17325 tree ret = tree_cons (low_bound, length, chain);
17326 OMP_CLAUSE_DOACROSS_SINK_NEGATIVE (ret)
17327 = OMP_CLAUSE_DOACROSS_SINK_NEGATIVE (decl);
17328 return ret;
17330 tree ret = tsubst_stmt (decl, args, complain, in_decl);
17331 /* Undo convert_from_reference tsubst_expr could have called. */
17332 if (decl
17333 && REFERENCE_REF_P (ret)
17334 && !REFERENCE_REF_P (decl))
17335 ret = TREE_OPERAND (ret, 0);
17336 return ret;
17339 /* Like tsubst_copy, but specifically for OpenMP clauses. */
17341 static tree
17342 tsubst_omp_clauses (tree clauses, enum c_omp_region_type ort,
17343 tree args, tsubst_flags_t complain, tree in_decl)
17345 tree new_clauses = NULL_TREE, nc, oc;
17346 tree linear_no_step = NULL_TREE;
17347 tree iterator_cache[2] = { NULL_TREE, NULL_TREE };
17349 for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
17351 nc = copy_node (oc);
17352 OMP_CLAUSE_CHAIN (nc) = new_clauses;
17353 new_clauses = nc;
17355 switch (OMP_CLAUSE_CODE (nc))
17357 case OMP_CLAUSE_LASTPRIVATE:
17358 if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
17360 OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
17361 tsubst_stmt (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args,
17362 complain, in_decl);
17363 OMP_CLAUSE_LASTPRIVATE_STMT (nc)
17364 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
17366 /* FALLTHRU */
17367 case OMP_CLAUSE_PRIVATE:
17368 case OMP_CLAUSE_SHARED:
17369 case OMP_CLAUSE_FIRSTPRIVATE:
17370 case OMP_CLAUSE_COPYIN:
17371 case OMP_CLAUSE_COPYPRIVATE:
17372 case OMP_CLAUSE_UNIFORM:
17373 case OMP_CLAUSE_DEPEND:
17374 case OMP_CLAUSE_DOACROSS:
17375 case OMP_CLAUSE_AFFINITY:
17376 case OMP_CLAUSE_FROM:
17377 case OMP_CLAUSE_TO:
17378 case OMP_CLAUSE_MAP:
17379 case OMP_CLAUSE__CACHE_:
17380 case OMP_CLAUSE_NONTEMPORAL:
17381 case OMP_CLAUSE_USE_DEVICE_PTR:
17382 case OMP_CLAUSE_USE_DEVICE_ADDR:
17383 case OMP_CLAUSE_IS_DEVICE_PTR:
17384 case OMP_CLAUSE_HAS_DEVICE_ADDR:
17385 case OMP_CLAUSE_INCLUSIVE:
17386 case OMP_CLAUSE_EXCLUSIVE:
17387 OMP_CLAUSE_DECL (nc)
17388 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17389 in_decl, iterator_cache);
17390 break;
17391 case OMP_CLAUSE_NUM_TEAMS:
17392 if (OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (oc))
17393 OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (nc)
17394 = tsubst_stmt (OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (oc), args,
17395 complain, in_decl);
17396 /* FALLTHRU */
17397 case OMP_CLAUSE_TILE:
17398 case OMP_CLAUSE_IF:
17399 case OMP_CLAUSE_SELF:
17400 case OMP_CLAUSE_NUM_THREADS:
17401 case OMP_CLAUSE_SCHEDULE:
17402 case OMP_CLAUSE_COLLAPSE:
17403 case OMP_CLAUSE_FINAL:
17404 case OMP_CLAUSE_DEVICE:
17405 case OMP_CLAUSE_DIST_SCHEDULE:
17406 case OMP_CLAUSE_THREAD_LIMIT:
17407 case OMP_CLAUSE_SAFELEN:
17408 case OMP_CLAUSE_SIMDLEN:
17409 case OMP_CLAUSE_NUM_TASKS:
17410 case OMP_CLAUSE_GRAINSIZE:
17411 case OMP_CLAUSE_PRIORITY:
17412 case OMP_CLAUSE_ORDERED:
17413 case OMP_CLAUSE_HINT:
17414 case OMP_CLAUSE_FILTER:
17415 case OMP_CLAUSE_NUM_GANGS:
17416 case OMP_CLAUSE_NUM_WORKERS:
17417 case OMP_CLAUSE_VECTOR_LENGTH:
17418 case OMP_CLAUSE_WORKER:
17419 case OMP_CLAUSE_VECTOR:
17420 case OMP_CLAUSE_ASYNC:
17421 case OMP_CLAUSE_WAIT:
17422 case OMP_CLAUSE_DETACH:
17423 OMP_CLAUSE_OPERAND (nc, 0)
17424 = tsubst_stmt (OMP_CLAUSE_OPERAND (oc, 0), args, complain, in_decl);
17425 break;
17426 case OMP_CLAUSE_REDUCTION:
17427 case OMP_CLAUSE_IN_REDUCTION:
17428 case OMP_CLAUSE_TASK_REDUCTION:
17429 if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc))
17431 tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc);
17432 if (TREE_CODE (placeholder) == SCOPE_REF)
17434 tree scope = tsubst (TREE_OPERAND (placeholder, 0), args,
17435 complain, in_decl);
17436 OMP_CLAUSE_REDUCTION_PLACEHOLDER (nc)
17437 = build_qualified_name (NULL_TREE, scope,
17438 TREE_OPERAND (placeholder, 1),
17439 false);
17441 else
17442 gcc_assert (identifier_p (placeholder));
17444 OMP_CLAUSE_DECL (nc)
17445 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17446 in_decl, NULL);
17447 break;
17448 case OMP_CLAUSE_GANG:
17449 case OMP_CLAUSE_ALIGNED:
17450 OMP_CLAUSE_DECL (nc)
17451 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17452 in_decl, NULL);
17453 OMP_CLAUSE_OPERAND (nc, 1)
17454 = tsubst_stmt (OMP_CLAUSE_OPERAND (oc, 1), args, complain, in_decl);
17455 break;
17456 case OMP_CLAUSE_ALLOCATE:
17457 OMP_CLAUSE_DECL (nc)
17458 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17459 in_decl, NULL);
17460 OMP_CLAUSE_OPERAND (nc, 1)
17461 = tsubst_stmt (OMP_CLAUSE_OPERAND (oc, 1), args, complain, in_decl);
17462 OMP_CLAUSE_OPERAND (nc, 2)
17463 = tsubst_stmt (OMP_CLAUSE_OPERAND (oc, 2), args, complain, in_decl);
17464 break;
17465 case OMP_CLAUSE_LINEAR:
17466 OMP_CLAUSE_DECL (nc)
17467 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17468 in_decl, NULL);
17469 if (OMP_CLAUSE_LINEAR_STEP (oc) == NULL_TREE)
17471 gcc_assert (!linear_no_step);
17472 linear_no_step = nc;
17474 else if (OMP_CLAUSE_LINEAR_VARIABLE_STRIDE (oc))
17475 OMP_CLAUSE_LINEAR_STEP (nc)
17476 = tsubst_omp_clause_decl (OMP_CLAUSE_LINEAR_STEP (oc), args,
17477 complain, in_decl, NULL);
17478 else
17479 OMP_CLAUSE_LINEAR_STEP (nc)
17480 = tsubst_stmt (OMP_CLAUSE_LINEAR_STEP (oc), args,
17481 complain, in_decl);
17482 break;
17483 case OMP_CLAUSE_NOWAIT:
17484 case OMP_CLAUSE_DEFAULT:
17485 case OMP_CLAUSE_UNTIED:
17486 case OMP_CLAUSE_MERGEABLE:
17487 case OMP_CLAUSE_INBRANCH:
17488 case OMP_CLAUSE_NOTINBRANCH:
17489 case OMP_CLAUSE_PROC_BIND:
17490 case OMP_CLAUSE_FOR:
17491 case OMP_CLAUSE_PARALLEL:
17492 case OMP_CLAUSE_SECTIONS:
17493 case OMP_CLAUSE_TASKGROUP:
17494 case OMP_CLAUSE_NOGROUP:
17495 case OMP_CLAUSE_THREADS:
17496 case OMP_CLAUSE_SIMD:
17497 case OMP_CLAUSE_DEFAULTMAP:
17498 case OMP_CLAUSE_ORDER:
17499 case OMP_CLAUSE_BIND:
17500 case OMP_CLAUSE_INDEPENDENT:
17501 case OMP_CLAUSE_AUTO:
17502 case OMP_CLAUSE_SEQ:
17503 case OMP_CLAUSE_IF_PRESENT:
17504 case OMP_CLAUSE_FINALIZE:
17505 case OMP_CLAUSE_NOHOST:
17506 break;
17507 default:
17508 gcc_unreachable ();
17510 if ((ort & C_ORT_OMP_DECLARE_SIMD) == C_ORT_OMP)
17511 switch (OMP_CLAUSE_CODE (nc))
17513 case OMP_CLAUSE_SHARED:
17514 case OMP_CLAUSE_PRIVATE:
17515 case OMP_CLAUSE_FIRSTPRIVATE:
17516 case OMP_CLAUSE_LASTPRIVATE:
17517 case OMP_CLAUSE_COPYPRIVATE:
17518 case OMP_CLAUSE_LINEAR:
17519 case OMP_CLAUSE_REDUCTION:
17520 case OMP_CLAUSE_IN_REDUCTION:
17521 case OMP_CLAUSE_TASK_REDUCTION:
17522 case OMP_CLAUSE_USE_DEVICE_PTR:
17523 case OMP_CLAUSE_USE_DEVICE_ADDR:
17524 case OMP_CLAUSE_IS_DEVICE_PTR:
17525 case OMP_CLAUSE_HAS_DEVICE_ADDR:
17526 case OMP_CLAUSE_INCLUSIVE:
17527 case OMP_CLAUSE_EXCLUSIVE:
17528 case OMP_CLAUSE_ALLOCATE:
17529 /* tsubst_expr on SCOPE_REF results in returning
17530 finish_non_static_data_member result. Undo that here. */
17531 if (TREE_CODE (OMP_CLAUSE_DECL (oc)) == SCOPE_REF
17532 && (TREE_CODE (TREE_OPERAND (OMP_CLAUSE_DECL (oc), 1))
17533 == IDENTIFIER_NODE))
17535 tree t = OMP_CLAUSE_DECL (nc);
17536 tree v = t;
17537 while (v)
17538 switch (TREE_CODE (v))
17540 case COMPONENT_REF:
17541 case MEM_REF:
17542 case INDIRECT_REF:
17543 CASE_CONVERT:
17544 case POINTER_PLUS_EXPR:
17545 v = TREE_OPERAND (v, 0);
17546 continue;
17547 case PARM_DECL:
17548 if (DECL_CONTEXT (v) == current_function_decl
17549 && DECL_ARTIFICIAL (v)
17550 && DECL_NAME (v) == this_identifier)
17551 OMP_CLAUSE_DECL (nc) = TREE_OPERAND (t, 1);
17552 /* FALLTHRU */
17553 default:
17554 v = NULL_TREE;
17555 break;
17558 else if (VAR_P (OMP_CLAUSE_DECL (oc))
17559 && DECL_HAS_VALUE_EXPR_P (OMP_CLAUSE_DECL (oc))
17560 && DECL_ARTIFICIAL (OMP_CLAUSE_DECL (oc))
17561 && DECL_LANG_SPECIFIC (OMP_CLAUSE_DECL (oc))
17562 && DECL_OMP_PRIVATIZED_MEMBER (OMP_CLAUSE_DECL (oc)))
17564 tree decl = OMP_CLAUSE_DECL (nc);
17565 if (VAR_P (decl))
17567 retrofit_lang_decl (decl);
17568 DECL_OMP_PRIVATIZED_MEMBER (decl) = 1;
17571 break;
17572 default:
17573 break;
17577 new_clauses = nreverse (new_clauses);
17578 if (ort != C_ORT_OMP_DECLARE_SIMD)
17580 new_clauses = finish_omp_clauses (new_clauses, ort);
17581 if (linear_no_step)
17582 for (nc = new_clauses; nc; nc = OMP_CLAUSE_CHAIN (nc))
17583 if (nc == linear_no_step)
17585 OMP_CLAUSE_LINEAR_STEP (nc) = NULL_TREE;
17586 break;
17589 return new_clauses;
17592 /* Like tsubst_expr, but unshare TREE_LIST nodes. */
17594 static tree
17595 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
17596 tree in_decl)
17598 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
17600 tree purpose, value, chain;
17602 if (t == NULL)
17603 return t;
17605 if (TREE_CODE (t) != TREE_LIST)
17606 return tsubst_expr (t, args, complain, in_decl);
17608 if (t == void_list_node)
17609 return t;
17611 purpose = TREE_PURPOSE (t);
17612 if (purpose)
17613 purpose = RECUR (purpose);
17614 value = TREE_VALUE (t);
17615 if (value)
17617 if (TREE_CODE (value) != LABEL_DECL)
17618 value = RECUR (value);
17619 else
17621 value = lookup_label (DECL_NAME (value));
17622 gcc_assert (TREE_CODE (value) == LABEL_DECL);
17623 TREE_USED (value) = 1;
17626 chain = TREE_CHAIN (t);
17627 if (chain && chain != void_type_node)
17628 chain = RECUR (chain);
17629 return tree_cons (purpose, value, chain);
17630 #undef RECUR
17633 /* Used to temporarily communicate the list of #pragma omp parallel
17634 clauses to #pragma omp for instantiation if they are combined
17635 together. */
17637 static tree *omp_parallel_combined_clauses;
17639 static tree tsubst_decomp_names (tree, tree, tree, tsubst_flags_t, tree,
17640 cp_decomp *);
17642 /* Substitute one OMP_FOR iterator. */
17644 static bool
17645 tsubst_omp_for_iterator (tree t, int i, tree declv, tree &orig_declv,
17646 tree initv, tree condv, tree incrv, tree *clauses,
17647 tree args, tsubst_flags_t complain, tree in_decl)
17649 #define RECUR(NODE) \
17650 tsubst_stmt ((NODE), args, complain, in_decl)
17651 tree decl, init, cond = NULL_TREE, incr = NULL_TREE;
17652 bool ret = false;
17654 init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
17655 gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
17657 decl = TREE_OPERAND (init, 0);
17658 init = TREE_OPERAND (init, 1);
17659 tree decl_expr = NULL_TREE;
17660 bool range_for = TREE_VEC_ELT (OMP_FOR_COND (t), i) == global_namespace;
17661 if (range_for)
17663 bool decomp = false;
17664 if (decl != error_mark_node && DECL_HAS_VALUE_EXPR_P (decl))
17666 tree v = DECL_VALUE_EXPR (decl);
17667 if (TREE_CODE (v) == ARRAY_REF
17668 && VAR_P (TREE_OPERAND (v, 0))
17669 && DECL_DECOMPOSITION_P (TREE_OPERAND (v, 0)))
17671 cp_decomp decomp_d = { NULL_TREE, 0 };
17672 tree d = tsubst_decl (TREE_OPERAND (v, 0), args, complain);
17673 maybe_push_decl (d);
17674 d = tsubst_decomp_names (d, TREE_OPERAND (v, 0), args, complain,
17675 in_decl, &decomp_d);
17676 decomp = true;
17677 if (d == error_mark_node)
17678 decl = error_mark_node;
17679 else
17680 for (unsigned int i = 0; i < decomp_d.count; i++)
17682 if (!DECL_HAS_VALUE_EXPR_P (decomp_d.decl))
17684 tree v = build_nt (ARRAY_REF, d,
17685 size_int (decomp_d.count - i - 1),
17686 NULL_TREE, NULL_TREE);
17687 SET_DECL_VALUE_EXPR (decomp_d.decl, v);
17688 DECL_HAS_VALUE_EXPR_P (decomp_d.decl) = 1;
17690 fit_decomposition_lang_decl (decomp_d.decl, d);
17691 decomp_d.decl = DECL_CHAIN (decomp_d.decl);
17695 decl = tsubst_decl (decl, args, complain);
17696 if (!decomp)
17697 maybe_push_decl (decl);
17699 else if (init && TREE_CODE (init) == DECL_EXPR)
17701 /* We need to jump through some hoops to handle declarations in the
17702 init-statement, since we might need to handle auto deduction,
17703 but we need to keep control of initialization. */
17704 decl_expr = init;
17705 init = DECL_INITIAL (DECL_EXPR_DECL (init));
17706 decl = tsubst_decl (decl, args, complain);
17708 else
17710 if (TREE_CODE (decl) == SCOPE_REF)
17712 decl = RECUR (decl);
17713 if (TREE_CODE (decl) == COMPONENT_REF)
17715 tree v = decl;
17716 while (v)
17717 switch (TREE_CODE (v))
17719 case COMPONENT_REF:
17720 case MEM_REF:
17721 case INDIRECT_REF:
17722 CASE_CONVERT:
17723 case POINTER_PLUS_EXPR:
17724 v = TREE_OPERAND (v, 0);
17725 continue;
17726 case PARM_DECL:
17727 if (DECL_CONTEXT (v) == current_function_decl
17728 && DECL_ARTIFICIAL (v)
17729 && DECL_NAME (v) == this_identifier)
17731 decl = TREE_OPERAND (decl, 1);
17732 decl = omp_privatize_field (decl, false);
17734 /* FALLTHRU */
17735 default:
17736 v = NULL_TREE;
17737 break;
17741 else
17742 decl = RECUR (decl);
17744 if (init && TREE_CODE (init) == TREE_VEC)
17746 init = copy_node (init);
17747 TREE_VEC_ELT (init, 0)
17748 = tsubst_decl (TREE_VEC_ELT (init, 0), args, complain);
17749 TREE_VEC_ELT (init, 1) = RECUR (TREE_VEC_ELT (init, 1));
17750 TREE_VEC_ELT (init, 2) = RECUR (TREE_VEC_ELT (init, 2));
17752 else
17753 init = RECUR (init);
17755 if (orig_declv && OMP_FOR_ORIG_DECLS (t))
17757 tree o = TREE_VEC_ELT (OMP_FOR_ORIG_DECLS (t), i);
17758 if (TREE_CODE (o) == TREE_LIST)
17759 TREE_VEC_ELT (orig_declv, i)
17760 = tree_cons (RECUR (TREE_PURPOSE (o)),
17761 RECUR (TREE_VALUE (o)),
17762 NULL_TREE);
17763 else
17764 TREE_VEC_ELT (orig_declv, i) = RECUR (o);
17767 if (range_for)
17769 tree this_pre_body = NULL_TREE;
17770 tree orig_init = NULL_TREE;
17771 tree orig_decl = NULL_TREE;
17772 tree init_sl = NULL_TREE;
17773 cp_convert_omp_range_for (this_pre_body, init_sl, decl, orig_decl, init,
17774 orig_init, cond, incr);
17775 if (orig_decl)
17777 if (orig_declv == NULL_TREE)
17778 orig_declv = copy_node (declv);
17779 TREE_VEC_ELT (orig_declv, i) = orig_decl;
17780 ret = true;
17782 else if (orig_declv)
17783 TREE_VEC_ELT (orig_declv, i) = decl;
17786 tree auto_node = type_uses_auto (TREE_TYPE (decl));
17787 if (!range_for && auto_node && init)
17788 TREE_TYPE (decl)
17789 = do_auto_deduction (TREE_TYPE (decl), init, auto_node, complain);
17791 gcc_assert (!type_dependent_expression_p (decl));
17793 if (!CLASS_TYPE_P (TREE_TYPE (decl)) || range_for)
17795 if (decl_expr)
17797 /* Declare the variable, but don't let that initialize it. */
17798 tree init_sav = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
17799 DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL_TREE;
17800 RECUR (decl_expr);
17801 DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init_sav;
17804 if (!range_for)
17806 cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
17807 if (COMPARISON_CLASS_P (cond)
17808 && TREE_CODE (TREE_OPERAND (cond, 1)) == TREE_VEC)
17810 tree lhs = RECUR (TREE_OPERAND (cond, 0));
17811 tree rhs = copy_node (TREE_OPERAND (cond, 1));
17812 TREE_VEC_ELT (rhs, 0)
17813 = tsubst_decl (TREE_VEC_ELT (rhs, 0), args, complain);
17814 TREE_VEC_ELT (rhs, 1) = RECUR (TREE_VEC_ELT (rhs, 1));
17815 TREE_VEC_ELT (rhs, 2) = RECUR (TREE_VEC_ELT (rhs, 2));
17816 cond = build2 (TREE_CODE (cond), TREE_TYPE (cond),
17817 lhs, rhs);
17819 else
17820 cond = RECUR (cond);
17821 incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
17822 if (TREE_CODE (incr) == MODIFY_EXPR)
17824 tree lhs = RECUR (TREE_OPERAND (incr, 0));
17825 tree rhs = RECUR (TREE_OPERAND (incr, 1));
17826 incr = build_x_modify_expr (EXPR_LOCATION (incr), lhs,
17827 NOP_EXPR, rhs, NULL_TREE, complain);
17829 else
17830 incr = RECUR (incr);
17831 if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
17832 TREE_VEC_ELT (orig_declv, i) = decl;
17834 TREE_VEC_ELT (declv, i) = decl;
17835 TREE_VEC_ELT (initv, i) = init;
17836 TREE_VEC_ELT (condv, i) = cond;
17837 TREE_VEC_ELT (incrv, i) = incr;
17838 return ret;
17841 if (decl_expr)
17843 /* Declare and initialize the variable. */
17844 RECUR (decl_expr);
17845 init = NULL_TREE;
17847 else if (init)
17849 tree *pc;
17850 int j;
17851 for (j = ((omp_parallel_combined_clauses == NULL
17852 || TREE_CODE (t) == OMP_LOOP) ? 1 : 0); j < 2; j++)
17854 for (pc = j ? clauses : omp_parallel_combined_clauses; *pc; )
17856 if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_PRIVATE
17857 && OMP_CLAUSE_DECL (*pc) == decl)
17858 break;
17859 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_LASTPRIVATE
17860 && OMP_CLAUSE_DECL (*pc) == decl)
17862 if (j)
17863 break;
17864 /* Move lastprivate (decl) clause to OMP_FOR_CLAUSES. */
17865 tree c = *pc;
17866 *pc = OMP_CLAUSE_CHAIN (c);
17867 OMP_CLAUSE_CHAIN (c) = *clauses;
17868 *clauses = c;
17870 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_FIRSTPRIVATE
17871 && OMP_CLAUSE_DECL (*pc) == decl)
17873 error ("iteration variable %qD should not be firstprivate",
17874 decl);
17875 *pc = OMP_CLAUSE_CHAIN (*pc);
17877 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_REDUCTION
17878 && OMP_CLAUSE_DECL (*pc) == decl)
17880 error ("iteration variable %qD should not be reduction",
17881 decl);
17882 *pc = OMP_CLAUSE_CHAIN (*pc);
17884 else
17885 pc = &OMP_CLAUSE_CHAIN (*pc);
17887 if (*pc)
17888 break;
17890 if (*pc == NULL_TREE)
17892 tree c = build_omp_clause (input_location,
17893 TREE_CODE (t) == OMP_LOOP
17894 ? OMP_CLAUSE_LASTPRIVATE
17895 : OMP_CLAUSE_PRIVATE);
17896 OMP_CLAUSE_DECL (c) = decl;
17897 c = finish_omp_clauses (c, C_ORT_OMP);
17898 if (c)
17900 OMP_CLAUSE_CHAIN (c) = *clauses;
17901 *clauses = c;
17905 cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
17906 if (COMPARISON_CLASS_P (cond))
17908 tree op0 = RECUR (TREE_OPERAND (cond, 0));
17909 tree op1 = RECUR (TREE_OPERAND (cond, 1));
17910 cond = build2 (TREE_CODE (cond), boolean_type_node, op0, op1);
17912 else
17913 cond = RECUR (cond);
17914 incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
17915 switch (TREE_CODE (incr))
17917 case PREINCREMENT_EXPR:
17918 case PREDECREMENT_EXPR:
17919 case POSTINCREMENT_EXPR:
17920 case POSTDECREMENT_EXPR:
17921 incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
17922 RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
17923 break;
17924 case MODIFY_EXPR:
17925 if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
17926 || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
17928 tree rhs = TREE_OPERAND (incr, 1);
17929 tree lhs = RECUR (TREE_OPERAND (incr, 0));
17930 tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
17931 tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
17932 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
17933 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
17934 rhs0, rhs1));
17936 else
17937 incr = RECUR (incr);
17938 break;
17939 case MODOP_EXPR:
17940 if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
17941 || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
17943 tree lhs = RECUR (TREE_OPERAND (incr, 0));
17944 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
17945 build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
17946 TREE_TYPE (decl), lhs,
17947 RECUR (TREE_OPERAND (incr, 2))));
17949 else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
17950 && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
17951 || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
17953 tree rhs = TREE_OPERAND (incr, 2);
17954 tree lhs = RECUR (TREE_OPERAND (incr, 0));
17955 tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
17956 tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
17957 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
17958 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
17959 rhs0, rhs1));
17961 else
17962 incr = RECUR (incr);
17963 break;
17964 default:
17965 incr = RECUR (incr);
17966 break;
17969 if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
17970 TREE_VEC_ELT (orig_declv, i) = decl;
17971 TREE_VEC_ELT (declv, i) = decl;
17972 TREE_VEC_ELT (initv, i) = init;
17973 TREE_VEC_ELT (condv, i) = cond;
17974 TREE_VEC_ELT (incrv, i) = incr;
17975 return false;
17976 #undef RECUR
17979 /* Helper function of tsubst_expr, find OMP_TEAMS inside
17980 of OMP_TARGET's body. */
17982 static tree
17983 tsubst_find_omp_teams (tree *tp, int *walk_subtrees, void *)
17985 *walk_subtrees = 0;
17986 switch (TREE_CODE (*tp))
17988 case OMP_TEAMS:
17989 return *tp;
17990 case BIND_EXPR:
17991 case STATEMENT_LIST:
17992 *walk_subtrees = 1;
17993 break;
17994 default:
17995 break;
17997 return NULL_TREE;
18000 /* Helper function for tsubst_expr. For decomposition declaration
18001 artificial base DECL, which is tsubsted PATTERN_DECL, tsubst
18002 also the corresponding decls representing the identifiers
18003 of the decomposition declaration. Return DECL if successful
18004 or error_mark_node otherwise, set *FIRST to the first decl
18005 in the list chained through DECL_CHAIN and *CNT to the number
18006 of such decls. */
18008 static tree
18009 tsubst_decomp_names (tree decl, tree pattern_decl, tree args,
18010 tsubst_flags_t complain, tree in_decl, cp_decomp *decomp)
18012 tree decl2, decl3, prev = decl;
18013 decomp->count = 0;
18014 gcc_assert (DECL_NAME (decl) == NULL_TREE);
18015 for (decl2 = DECL_CHAIN (pattern_decl);
18016 decl2
18017 && VAR_P (decl2)
18018 && DECL_DECOMPOSITION_P (decl2)
18019 && DECL_NAME (decl2);
18020 decl2 = DECL_CHAIN (decl2))
18022 if (TREE_TYPE (decl2) == error_mark_node && decomp->count == 0)
18024 gcc_assert (errorcount);
18025 return error_mark_node;
18027 decomp->count++;
18028 gcc_assert (DECL_DECOMP_BASE (decl2) == pattern_decl);
18029 gcc_assert (DECL_HAS_VALUE_EXPR_P (decl2));
18030 tree v = DECL_VALUE_EXPR (decl2);
18031 DECL_HAS_VALUE_EXPR_P (decl2) = 0;
18032 SET_DECL_VALUE_EXPR (decl2, NULL_TREE);
18033 decl3 = tsubst (decl2, args, complain, in_decl);
18034 SET_DECL_VALUE_EXPR (decl2, v);
18035 DECL_HAS_VALUE_EXPR_P (decl2) = 1;
18036 if (VAR_P (decl3))
18037 DECL_TEMPLATE_INSTANTIATED (decl3) = 1;
18038 else
18040 gcc_assert (errorcount);
18041 decl = error_mark_node;
18042 continue;
18044 maybe_push_decl (decl3);
18045 if (error_operand_p (decl3))
18046 decl = error_mark_node;
18047 else if (decl != error_mark_node
18048 && DECL_CHAIN (decl3) != prev
18049 && decl != prev)
18051 gcc_assert (errorcount);
18052 decl = error_mark_node;
18054 else
18055 prev = decl3;
18057 decomp->decl = prev;
18058 return decl;
18061 /* Return the proper local_specialization for init-capture pack DECL. */
18063 static tree
18064 lookup_init_capture_pack (tree decl)
18066 /* We handle normal pack captures by forwarding to the specialization of the
18067 captured parameter. We can't do that for pack init-captures; we need them
18068 to have their own local_specialization. We created the individual
18069 VAR_DECLs (if any) under build_capture_proxy, and we need to collect them
18070 when we process the DECL_EXPR for the pack init-capture in the template.
18071 So, how do we find them? We don't know the capture proxy pack when
18072 building the individual resulting proxies, and we don't know the
18073 individual proxies when instantiating the pack. What we have in common is
18074 the FIELD_DECL.
18076 So...when we instantiate the FIELD_DECL, we stick the result in
18077 local_specializations. Then at the DECL_EXPR we look up that result, see
18078 how many elements it has, synthesize the names, and look them up. */
18080 tree cname = DECL_NAME (decl);
18081 tree val = DECL_VALUE_EXPR (decl);
18082 tree field = TREE_OPERAND (val, 1);
18083 gcc_assert (TREE_CODE (field) == FIELD_DECL);
18084 tree fpack = retrieve_local_specialization (field);
18085 if (fpack == error_mark_node)
18086 return error_mark_node;
18088 int len = 1;
18089 tree vec = NULL_TREE;
18090 tree r = NULL_TREE;
18091 if (TREE_CODE (fpack) == TREE_VEC)
18093 len = TREE_VEC_LENGTH (fpack);
18094 vec = make_tree_vec (len);
18095 r = make_node (NONTYPE_ARGUMENT_PACK);
18096 ARGUMENT_PACK_ARGS (r) = vec;
18098 for (int i = 0; i < len; ++i)
18100 tree ename = vec ? make_ith_pack_parameter_name (cname, i) : cname;
18101 tree elt = lookup_name (ename);
18102 if (vec)
18103 TREE_VEC_ELT (vec, i) = elt;
18104 else
18105 r = elt;
18107 return r;
18110 /* T is an operand of a template tree being substituted. Return whether
18111 T is dependent such that we should suppress some warnings that would
18112 make sense if the substituted expression were written directly, like
18113 template <int I> bool f() { return I == 2; }
18114 We don't want to warn when instantiating f that comparing two constants
18115 always has the same value.
18117 This is a more limited concept of dependence than instantiation-dependent;
18118 here we don't care whether substitution could fail. */
18120 static bool
18121 dependent_operand_p (tree t)
18123 while (TREE_CODE (t) == IMPLICIT_CONV_EXPR)
18124 t = TREE_OPERAND (t, 0);
18125 ++processing_template_decl;
18126 bool r = (potential_constant_expression (t)
18127 ? value_dependent_expression_p (t)
18128 : type_dependent_expression_p (t));
18129 --processing_template_decl;
18130 return r;
18133 /* A superset of tsubst_expr that also handles statement trees. */
18135 static tree
18136 tsubst_stmt (tree t, tree args, tsubst_flags_t complain, tree in_decl)
18138 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
18139 #define RECUR(NODE) \
18140 tsubst_stmt ((NODE), args, complain, in_decl)
18142 tree stmt, tmp;
18143 tree r;
18144 location_t loc;
18146 if (t == NULL_TREE || t == error_mark_node)
18147 return t;
18149 loc = input_location;
18150 if (location_t eloc = cp_expr_location (t))
18151 input_location = eloc;
18152 if (STATEMENT_CODE_P (TREE_CODE (t)))
18153 current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
18155 switch (TREE_CODE (t))
18157 case STATEMENT_LIST:
18159 for (tree stmt : tsi_range (t))
18160 RECUR (stmt);
18161 break;
18164 case CTOR_INITIALIZER:
18165 finish_mem_initializers (tsubst_initializer_list
18166 (TREE_OPERAND (t, 0), args));
18167 break;
18169 case RETURN_EXPR:
18170 finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
18171 break;
18173 case CO_RETURN_EXPR:
18174 finish_co_return_stmt (input_location, RECUR (TREE_OPERAND (t, 0)));
18175 break;
18177 case EXPR_STMT:
18178 tmp = RECUR (EXPR_STMT_EXPR (t));
18179 if (EXPR_STMT_STMT_EXPR_RESULT (t))
18180 finish_stmt_expr_expr (tmp, cur_stmt_expr);
18181 else
18182 finish_expr_stmt (tmp);
18183 break;
18185 case USING_STMT:
18186 finish_using_directive (USING_STMT_NAMESPACE (t), /*attribs=*/NULL_TREE);
18187 break;
18189 case PRECONDITION_STMT:
18190 case POSTCONDITION_STMT:
18191 gcc_unreachable ();
18193 case ASSERTION_STMT:
18195 r = tsubst_contract (NULL_TREE, t, args, complain, in_decl);
18196 if (r != error_mark_node)
18197 add_stmt (r);
18198 RETURN (r);
18200 break;
18202 case DECL_EXPR:
18204 tree decl, pattern_decl;
18205 tree init;
18207 pattern_decl = decl = DECL_EXPR_DECL (t);
18208 if (TREE_CODE (decl) == LABEL_DECL)
18209 finish_label_decl (DECL_NAME (decl));
18210 else if (TREE_CODE (decl) == USING_DECL)
18212 tree scope = USING_DECL_SCOPE (decl);
18213 if (DECL_DEPENDENT_P (decl))
18215 scope = tsubst (scope, args, complain, in_decl);
18216 if (!MAYBE_CLASS_TYPE_P (scope)
18217 && TREE_CODE (scope) != ENUMERAL_TYPE)
18219 if (complain & tf_error)
18220 error_at (DECL_SOURCE_LOCATION (decl), "%qT is not a "
18221 "class, namespace, or enumeration", scope);
18222 return error_mark_node;
18224 finish_nonmember_using_decl (scope, DECL_NAME (decl));
18226 else
18228 /* This is a non-dependent using-decl, and we'll have
18229 used the names it found during template parsing. We do
18230 not want to do the lookup again, because we might not
18231 find the things we found then. */
18232 gcc_checking_assert (scope == tsubst (scope, args,
18233 complain, in_decl));
18234 /* We still need to push the bindings so that we can look up
18235 this name later. */
18236 push_using_decl_bindings (DECL_NAME (decl),
18237 USING_DECL_DECLS (decl));
18240 else if (is_capture_proxy (decl)
18241 && !DECL_TEMPLATE_INSTANTIATION (current_function_decl))
18243 /* We're in tsubst_lambda_expr, we've already inserted a new
18244 capture proxy, so look it up and register it. */
18245 tree inst;
18246 if (!DECL_PACK_P (decl))
18248 inst = lookup_name (DECL_NAME (decl), LOOK_where::BLOCK,
18249 LOOK_want::HIDDEN_LAMBDA);
18250 gcc_assert (inst != decl && is_capture_proxy (inst));
18252 else if (is_normal_capture_proxy (decl))
18254 inst = (retrieve_local_specialization
18255 (DECL_CAPTURED_VARIABLE (decl)));
18256 gcc_assert (TREE_CODE (inst) == NONTYPE_ARGUMENT_PACK
18257 || DECL_PACK_P (inst));
18259 else
18260 inst = lookup_init_capture_pack (decl);
18262 register_local_specialization (inst, decl);
18263 break;
18265 else if (DECL_PRETTY_FUNCTION_P (decl))
18266 decl = make_fname_decl (DECL_SOURCE_LOCATION (decl),
18267 DECL_NAME (decl),
18268 true/*DECL_PRETTY_FUNCTION_P (decl)*/);
18269 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
18270 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
18271 /* Don't copy the old closure; we'll create a new one in
18272 tsubst_lambda_expr. */
18273 break;
18274 else
18276 init = DECL_INITIAL (decl);
18277 decl = tsubst (decl, args, complain, in_decl);
18278 if (decl != error_mark_node)
18280 /* By marking the declaration as instantiated, we avoid
18281 trying to instantiate it. Since instantiate_decl can't
18282 handle local variables, and since we've already done
18283 all that needs to be done, that's the right thing to
18284 do. */
18285 if (VAR_P (decl))
18286 DECL_TEMPLATE_INSTANTIATED (decl) = 1;
18287 if (VAR_P (decl) && !DECL_NAME (decl)
18288 && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
18289 /* Anonymous aggregates are a special case. */
18290 finish_anon_union (decl);
18291 else if (is_capture_proxy (DECL_EXPR_DECL (t)))
18293 DECL_CONTEXT (decl) = current_function_decl;
18294 if (DECL_NAME (decl) == this_identifier)
18296 tree lam = DECL_CONTEXT (current_function_decl);
18297 lam = CLASSTYPE_LAMBDA_EXPR (lam);
18298 LAMBDA_EXPR_THIS_CAPTURE (lam) = decl;
18300 insert_capture_proxy (decl);
18302 else if (DECL_IMPLICIT_TYPEDEF_P (t))
18303 /* We already did a pushtag. */;
18304 else if (VAR_OR_FUNCTION_DECL_P (decl)
18305 && DECL_LOCAL_DECL_P (decl))
18307 if (TREE_CODE (DECL_CONTEXT (decl)) == FUNCTION_DECL)
18308 DECL_CONTEXT (decl) = NULL_TREE;
18309 decl = pushdecl (decl);
18310 if (TREE_CODE (decl) == FUNCTION_DECL
18311 && DECL_OMP_DECLARE_REDUCTION_P (decl)
18312 && cp_check_omp_declare_reduction (decl))
18313 instantiate_body (pattern_decl, args, decl, true);
18315 else
18317 bool const_init = false;
18318 cp_decomp decomp_d, *decomp = NULL;
18319 tree ndecl = error_mark_node;
18320 tree asmspec_tree = NULL_TREE;
18321 maybe_push_decl (decl);
18323 if (VAR_P (decl)
18324 && DECL_LANG_SPECIFIC (decl)
18325 && DECL_OMP_PRIVATIZED_MEMBER (decl))
18326 break;
18328 if (VAR_P (decl)
18329 && DECL_DECOMPOSITION_P (decl)
18330 && TREE_TYPE (pattern_decl) != error_mark_node)
18332 decomp = &decomp_d;
18333 ndecl = tsubst_decomp_names (decl, pattern_decl, args,
18334 complain, in_decl, decomp);
18337 init = tsubst_init (init, decl, args, complain, in_decl);
18339 if (VAR_P (decl))
18340 const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
18341 (pattern_decl));
18343 /* In a non-template function, VLA type declarations are
18344 handled in grokdeclarator; for templates, handle them
18345 now. */
18346 predeclare_vla (decl);
18348 if (VAR_P (decl) && DECL_HARD_REGISTER (pattern_decl))
18350 tree id = DECL_ASSEMBLER_NAME (pattern_decl);
18351 const char *asmspec = IDENTIFIER_POINTER (id);
18352 gcc_assert (asmspec[0] == '*');
18353 asmspec_tree
18354 = build_string (IDENTIFIER_LENGTH (id) - 1,
18355 asmspec + 1);
18356 TREE_TYPE (asmspec_tree) = char_array_type_node;
18359 cp_finish_decl (decl, init, const_init, asmspec_tree, 0,
18360 decomp);
18362 if (ndecl != error_mark_node)
18363 cp_finish_decomp (ndecl, decomp);
18368 break;
18371 case FOR_STMT:
18372 stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
18373 RECUR (FOR_INIT_STMT (t));
18374 finish_init_stmt (stmt);
18375 tmp = RECUR (FOR_COND (t));
18376 finish_for_cond (tmp, stmt, false, 0, false);
18377 tmp = RECUR (FOR_EXPR (t));
18378 finish_for_expr (tmp, stmt);
18380 bool prev = note_iteration_stmt_body_start ();
18381 RECUR (FOR_BODY (t));
18382 note_iteration_stmt_body_end (prev);
18384 finish_for_stmt (stmt);
18385 break;
18387 case RANGE_FOR_STMT:
18389 /* Construct another range_for, if this is not a final
18390 substitution (for inside a generic lambda of a
18391 template). Otherwise convert to a regular for. */
18392 tree decl, expr;
18393 stmt = (processing_template_decl
18394 ? begin_range_for_stmt (NULL_TREE, NULL_TREE)
18395 : begin_for_stmt (NULL_TREE, NULL_TREE));
18396 RECUR (RANGE_FOR_INIT_STMT (t));
18397 decl = RANGE_FOR_DECL (t);
18398 decl = tsubst (decl, args, complain, in_decl);
18399 maybe_push_decl (decl);
18400 expr = RECUR (RANGE_FOR_EXPR (t));
18402 cp_decomp decomp_d, *decomp = NULL;
18403 if (VAR_P (decl) && DECL_DECOMPOSITION_P (decl))
18405 decomp = &decomp_d;
18406 decl = tsubst_decomp_names (decl, RANGE_FOR_DECL (t), args,
18407 complain, in_decl, decomp);
18410 if (processing_template_decl)
18412 RANGE_FOR_IVDEP (stmt) = RANGE_FOR_IVDEP (t);
18413 RANGE_FOR_UNROLL (stmt) = RANGE_FOR_UNROLL (t);
18414 RANGE_FOR_NOVECTOR (stmt) = RANGE_FOR_NOVECTOR (t);
18415 finish_range_for_decl (stmt, decl, expr);
18416 if (decomp && decl != error_mark_node)
18417 cp_finish_decomp (decl, decomp);
18419 else
18421 unsigned short unroll = (RANGE_FOR_UNROLL (t)
18422 ? tree_to_uhwi (RANGE_FOR_UNROLL (t)) : 0);
18423 stmt = cp_convert_range_for (stmt, decl, expr, decomp,
18424 RANGE_FOR_IVDEP (t), unroll,
18425 RANGE_FOR_NOVECTOR (t));
18428 bool prev = note_iteration_stmt_body_start ();
18429 RECUR (RANGE_FOR_BODY (t));
18430 note_iteration_stmt_body_end (prev);
18431 finish_for_stmt (stmt);
18433 break;
18435 case WHILE_STMT:
18436 stmt = begin_while_stmt ();
18437 tmp = RECUR (WHILE_COND (t));
18438 finish_while_stmt_cond (tmp, stmt, false, 0, false);
18440 bool prev = note_iteration_stmt_body_start ();
18441 RECUR (WHILE_BODY (t));
18442 note_iteration_stmt_body_end (prev);
18444 finish_while_stmt (stmt);
18445 break;
18447 case DO_STMT:
18448 stmt = begin_do_stmt ();
18450 bool prev = note_iteration_stmt_body_start ();
18451 RECUR (DO_BODY (t));
18452 note_iteration_stmt_body_end (prev);
18454 finish_do_body (stmt);
18455 tmp = RECUR (DO_COND (t));
18456 finish_do_stmt (tmp, stmt, false, 0, false);
18457 break;
18459 case IF_STMT:
18460 stmt = begin_if_stmt ();
18461 IF_STMT_CONSTEXPR_P (stmt) = IF_STMT_CONSTEXPR_P (t);
18462 IF_STMT_CONSTEVAL_P (stmt) = IF_STMT_CONSTEVAL_P (t);
18463 if (IF_STMT_CONSTEXPR_P (t))
18464 args = add_extra_args (IF_STMT_EXTRA_ARGS (t), args, complain, in_decl);
18466 tree cond = IF_COND (t);
18467 bool was_dep = dependent_operand_p (cond);
18468 cond = RECUR (cond);
18469 warning_sentinel s1(warn_address, was_dep);
18470 tmp = finish_if_stmt_cond (cond, stmt);
18472 if (IF_STMT_CONSTEXPR_P (t)
18473 && instantiation_dependent_expression_p (tmp))
18475 /* We're partially instantiating a generic lambda, but the condition
18476 of the constexpr if is still dependent. Don't substitute into the
18477 branches now, just remember the template arguments. */
18478 do_poplevel (IF_SCOPE (stmt));
18479 IF_COND (stmt) = IF_COND (t);
18480 THEN_CLAUSE (stmt) = THEN_CLAUSE (t);
18481 ELSE_CLAUSE (stmt) = ELSE_CLAUSE (t);
18482 IF_STMT_EXTRA_ARGS (stmt) = build_extra_args (t, args, complain);
18483 add_stmt (stmt);
18484 break;
18486 if (IF_STMT_CONSTEXPR_P (t) && integer_zerop (tmp))
18487 /* Don't instantiate the THEN_CLAUSE. */;
18488 else if (IF_STMT_CONSTEVAL_P (t))
18490 bool save_in_consteval_if_p = in_consteval_if_p;
18491 in_consteval_if_p = true;
18492 RECUR (THEN_CLAUSE (t));
18493 in_consteval_if_p = save_in_consteval_if_p;
18495 else
18497 tree folded = fold_non_dependent_expr (tmp, complain);
18498 bool inhibit = integer_zerop (folded);
18499 if (inhibit)
18500 ++c_inhibit_evaluation_warnings;
18501 RECUR (THEN_CLAUSE (t));
18502 if (inhibit)
18503 --c_inhibit_evaluation_warnings;
18505 finish_then_clause (stmt);
18507 if (IF_STMT_CONSTEXPR_P (t) && integer_nonzerop (tmp))
18508 /* Don't instantiate the ELSE_CLAUSE. */;
18509 else if (ELSE_CLAUSE (t))
18511 tree folded = fold_non_dependent_expr (tmp, complain);
18512 bool inhibit = integer_nonzerop (folded);
18513 begin_else_clause (stmt);
18514 if (inhibit)
18515 ++c_inhibit_evaluation_warnings;
18516 RECUR (ELSE_CLAUSE (t));
18517 if (inhibit)
18518 --c_inhibit_evaluation_warnings;
18519 finish_else_clause (stmt);
18522 finish_if_stmt (stmt);
18523 break;
18525 case BIND_EXPR:
18526 if (BIND_EXPR_BODY_BLOCK (t))
18527 stmt = begin_function_body ();
18528 else
18529 stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
18530 ? BCS_TRY_BLOCK : 0);
18532 RECUR (BIND_EXPR_BODY (t));
18534 if (BIND_EXPR_BODY_BLOCK (t))
18535 finish_function_body (stmt);
18536 else
18537 finish_compound_stmt (stmt);
18538 break;
18540 case BREAK_STMT:
18541 finish_break_stmt ();
18542 break;
18544 case CONTINUE_STMT:
18545 finish_continue_stmt ();
18546 break;
18548 case SWITCH_STMT:
18549 stmt = begin_switch_stmt ();
18550 tmp = RECUR (SWITCH_STMT_COND (t));
18551 finish_switch_cond (tmp, stmt);
18552 RECUR (SWITCH_STMT_BODY (t));
18553 finish_switch_stmt (stmt);
18554 break;
18556 case CASE_LABEL_EXPR:
18558 tree decl = CASE_LABEL (t);
18559 tree low = RECUR (CASE_LOW (t));
18560 tree high = RECUR (CASE_HIGH (t));
18561 tree l = finish_case_label (EXPR_LOCATION (t), low, high);
18562 if (l && TREE_CODE (l) == CASE_LABEL_EXPR)
18564 tree label = CASE_LABEL (l);
18565 FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
18566 if (DECL_ATTRIBUTES (decl) != NULL_TREE)
18567 cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
18570 break;
18572 case LABEL_EXPR:
18574 tree decl = LABEL_EXPR_LABEL (t);
18575 tree label;
18577 label = finish_label_stmt (DECL_NAME (decl));
18578 if (TREE_CODE (label) == LABEL_DECL)
18579 FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
18580 if (DECL_ATTRIBUTES (decl) != NULL_TREE)
18581 cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
18583 break;
18585 case GOTO_EXPR:
18586 tmp = GOTO_DESTINATION (t);
18587 if (TREE_CODE (tmp) != LABEL_DECL)
18588 /* Computed goto's must be tsubst'd into. On the other hand,
18589 non-computed gotos must not be; the identifier in question
18590 will have no binding. */
18591 tmp = RECUR (tmp);
18592 else
18593 tmp = DECL_NAME (tmp);
18594 finish_goto_stmt (tmp);
18595 break;
18597 case ASM_EXPR:
18599 tree string = RECUR (ASM_STRING (t));
18600 tree outputs = tsubst_copy_asm_operands (ASM_OUTPUTS (t), args,
18601 complain, in_decl);
18602 tree inputs = tsubst_copy_asm_operands (ASM_INPUTS (t), args,
18603 complain, in_decl);
18604 tree clobbers = tsubst_copy_asm_operands (ASM_CLOBBERS (t), args,
18605 complain, in_decl);
18606 tree labels = tsubst_copy_asm_operands (ASM_LABELS (t), args,
18607 complain, in_decl);
18608 tmp = finish_asm_stmt (EXPR_LOCATION (t), ASM_VOLATILE_P (t), string,
18609 outputs, inputs, clobbers, labels,
18610 ASM_INLINE_P (t));
18611 tree asm_expr = tmp;
18612 if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
18613 asm_expr = TREE_OPERAND (asm_expr, 0);
18614 ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
18616 break;
18618 case TRY_BLOCK:
18619 if (CLEANUP_P (t))
18621 stmt = begin_try_block ();
18622 RECUR (TRY_STMTS (t));
18623 finish_cleanup_try_block (stmt);
18624 finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
18626 else
18628 tree compound_stmt = NULL_TREE;
18630 if (FN_TRY_BLOCK_P (t))
18631 stmt = begin_function_try_block (&compound_stmt);
18632 else
18633 stmt = begin_try_block ();
18635 RECUR (TRY_STMTS (t));
18637 if (FN_TRY_BLOCK_P (t))
18638 finish_function_try_block (stmt);
18639 else
18640 finish_try_block (stmt);
18642 RECUR (TRY_HANDLERS (t));
18643 if (FN_TRY_BLOCK_P (t))
18644 finish_function_handler_sequence (stmt, compound_stmt);
18645 else
18646 finish_handler_sequence (stmt);
18648 break;
18650 case HANDLER:
18652 tree decl = HANDLER_PARMS (t);
18654 if (decl)
18656 decl = tsubst (decl, args, complain, in_decl);
18657 /* Prevent instantiate_decl from trying to instantiate
18658 this variable. We've already done all that needs to be
18659 done. */
18660 if (decl != error_mark_node)
18661 DECL_TEMPLATE_INSTANTIATED (decl) = 1;
18663 stmt = begin_handler ();
18664 finish_handler_parms (decl, stmt);
18665 RECUR (HANDLER_BODY (t));
18666 finish_handler (stmt);
18668 break;
18670 case TAG_DEFN:
18671 tmp = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
18672 if (CLASS_TYPE_P (tmp))
18674 /* Local classes are not independent templates; they are
18675 instantiated along with their containing function. And this
18676 way we don't have to deal with pushing out of one local class
18677 to instantiate a member of another local class. */
18678 /* Closures are handled by the LAMBDA_EXPR. */
18679 gcc_assert (!LAMBDA_TYPE_P (TREE_TYPE (t)));
18680 complete_type (tmp);
18681 if (dependent_type_p (tmp))
18683 /* This is a partial instantiation, try again when full. */
18684 add_stmt (build_min (TAG_DEFN, tmp));
18685 break;
18687 tree save_ccp = current_class_ptr;
18688 tree save_ccr = current_class_ref;
18689 for (tree fld = TYPE_FIELDS (tmp); fld; fld = DECL_CHAIN (fld))
18690 if ((VAR_P (fld)
18691 || (TREE_CODE (fld) == FUNCTION_DECL
18692 && !DECL_ARTIFICIAL (fld)))
18693 && DECL_TEMPLATE_INSTANTIATION (fld))
18694 instantiate_decl (fld, /*defer_ok=*/false,
18695 /*expl_inst_class=*/false);
18696 else if (TREE_CODE (fld) == FIELD_DECL)
18697 maybe_instantiate_nsdmi_init (fld, tf_warning_or_error);
18698 current_class_ptr = save_ccp;
18699 current_class_ref = save_ccr;
18701 break;
18703 case STATIC_ASSERT:
18705 tree condition;
18707 ++c_inhibit_evaluation_warnings;
18708 condition = tsubst_expr (STATIC_ASSERT_CONDITION (t), args,
18709 complain, in_decl);
18710 --c_inhibit_evaluation_warnings;
18712 finish_static_assert (condition,
18713 STATIC_ASSERT_MESSAGE (t),
18714 STATIC_ASSERT_SOURCE_LOCATION (t),
18715 /*member_p=*/false, /*show_expr_p=*/true);
18717 break;
18719 case OACC_KERNELS:
18720 case OACC_PARALLEL:
18721 case OACC_SERIAL:
18722 tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_ACC, args, complain,
18723 in_decl);
18724 stmt = begin_omp_parallel ();
18725 RECUR (OMP_BODY (t));
18726 finish_omp_construct (TREE_CODE (t), stmt, tmp);
18727 break;
18729 case OMP_PARALLEL:
18730 r = push_omp_privatization_clauses (OMP_PARALLEL_COMBINED (t));
18731 tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t), C_ORT_OMP, args,
18732 complain, in_decl);
18733 if (OMP_PARALLEL_COMBINED (t))
18734 omp_parallel_combined_clauses = &tmp;
18735 stmt = begin_omp_parallel ();
18736 RECUR (OMP_PARALLEL_BODY (t));
18737 gcc_assert (omp_parallel_combined_clauses == NULL);
18738 OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
18739 = OMP_PARALLEL_COMBINED (t);
18740 pop_omp_privatization_clauses (r);
18741 break;
18743 case OMP_TASK:
18744 if (OMP_TASK_BODY (t) == NULL_TREE)
18746 tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
18747 complain, in_decl);
18748 t = copy_node (t);
18749 OMP_TASK_CLAUSES (t) = tmp;
18750 add_stmt (t);
18751 break;
18753 r = push_omp_privatization_clauses (false);
18754 tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
18755 complain, in_decl);
18756 stmt = begin_omp_task ();
18757 RECUR (OMP_TASK_BODY (t));
18758 finish_omp_task (tmp, stmt);
18759 pop_omp_privatization_clauses (r);
18760 break;
18762 case OMP_FOR:
18763 case OMP_LOOP:
18764 case OMP_SIMD:
18765 case OMP_DISTRIBUTE:
18766 case OMP_TASKLOOP:
18767 case OACC_LOOP:
18769 tree clauses, body, pre_body;
18770 tree declv = NULL_TREE, initv = NULL_TREE, condv = NULL_TREE;
18771 tree orig_declv = NULL_TREE;
18772 tree incrv = NULL_TREE;
18773 enum c_omp_region_type ort = C_ORT_OMP;
18774 bool any_range_for = false;
18775 int i;
18777 if (TREE_CODE (t) == OACC_LOOP)
18778 ort = C_ORT_ACC;
18780 r = push_omp_privatization_clauses (OMP_FOR_INIT (t) == NULL_TREE);
18781 clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t), ort, args, complain,
18782 in_decl);
18783 if (OMP_FOR_INIT (t) != NULL_TREE)
18785 declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
18786 if (OMP_FOR_ORIG_DECLS (t))
18787 orig_declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
18788 initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
18789 condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
18790 incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
18793 keep_next_level (true);
18794 stmt = begin_omp_structured_block ();
18796 pre_body = push_stmt_list ();
18797 RECUR (OMP_FOR_PRE_BODY (t));
18798 pre_body = pop_stmt_list (pre_body);
18800 if (OMP_FOR_INIT (t) != NULL_TREE)
18801 for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
18802 any_range_for
18803 |= tsubst_omp_for_iterator (t, i, declv, orig_declv, initv,
18804 condv, incrv, &clauses, args,
18805 complain, in_decl);
18806 omp_parallel_combined_clauses = NULL;
18808 if (any_range_for)
18810 gcc_assert (orig_declv);
18811 body = begin_omp_structured_block ();
18812 for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
18813 if (TREE_VEC_ELT (orig_declv, i) != TREE_VEC_ELT (declv, i)
18814 && TREE_CODE (TREE_VEC_ELT (orig_declv, i)) == TREE_LIST
18815 && TREE_CHAIN (TREE_VEC_ELT (orig_declv, i)))
18816 cp_finish_omp_range_for (TREE_VEC_ELT (orig_declv, i),
18817 TREE_VEC_ELT (declv, i));
18819 else
18820 body = push_stmt_list ();
18821 RECUR (OMP_FOR_BODY (t));
18822 if (any_range_for)
18823 body = finish_omp_structured_block (body);
18824 else
18825 body = pop_stmt_list (body);
18827 if (OMP_FOR_INIT (t) != NULL_TREE)
18828 t = finish_omp_for (EXPR_LOCATION (t), TREE_CODE (t), declv,
18829 orig_declv, initv, condv, incrv, body, pre_body,
18830 NULL, clauses);
18831 else
18833 t = make_node (TREE_CODE (t));
18834 TREE_TYPE (t) = void_type_node;
18835 OMP_FOR_BODY (t) = body;
18836 OMP_FOR_PRE_BODY (t) = pre_body;
18837 OMP_FOR_CLAUSES (t) = clauses;
18838 SET_EXPR_LOCATION (t, EXPR_LOCATION (t));
18839 add_stmt (t);
18842 add_stmt (finish_omp_for_block (finish_omp_structured_block (stmt),
18843 t));
18844 pop_omp_privatization_clauses (r);
18846 break;
18848 case OMP_SECTIONS:
18849 case OMP_MASKED:
18850 omp_parallel_combined_clauses = NULL;
18851 /* FALLTHRU */
18852 case OMP_SINGLE:
18853 case OMP_SCOPE:
18854 case OMP_TEAMS:
18855 case OMP_CRITICAL:
18856 case OMP_TASKGROUP:
18857 case OMP_SCAN:
18858 r = push_omp_privatization_clauses (TREE_CODE (t) == OMP_TEAMS
18859 && OMP_TEAMS_COMBINED (t));
18860 tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_OMP, args, complain,
18861 in_decl);
18862 if (TREE_CODE (t) == OMP_TEAMS)
18864 keep_next_level (true);
18865 stmt = begin_omp_structured_block ();
18866 RECUR (OMP_BODY (t));
18867 stmt = finish_omp_structured_block (stmt);
18869 else
18871 stmt = push_stmt_list ();
18872 RECUR (OMP_BODY (t));
18873 stmt = pop_stmt_list (stmt);
18876 if (TREE_CODE (t) == OMP_CRITICAL
18877 && tmp != NULL_TREE
18878 && integer_nonzerop (OMP_CLAUSE_HINT_EXPR (tmp)))
18880 error_at (OMP_CLAUSE_LOCATION (tmp),
18881 "%<#pragma omp critical%> with %<hint%> clause requires "
18882 "a name, except when %<omp_sync_hint_none%> is used");
18883 RETURN (error_mark_node);
18885 t = copy_node (t);
18886 OMP_BODY (t) = stmt;
18887 OMP_CLAUSES (t) = tmp;
18888 add_stmt (t);
18889 pop_omp_privatization_clauses (r);
18890 break;
18892 case OMP_DEPOBJ:
18893 r = RECUR (OMP_DEPOBJ_DEPOBJ (t));
18894 if (OMP_DEPOBJ_CLAUSES (t) && OMP_DEPOBJ_CLAUSES (t) != error_mark_node)
18896 enum omp_clause_depend_kind kind = OMP_CLAUSE_DEPEND_INVALID;
18897 if (TREE_CODE (OMP_DEPOBJ_CLAUSES (t)) == OMP_CLAUSE)
18899 tmp = tsubst_omp_clauses (OMP_DEPOBJ_CLAUSES (t), C_ORT_OMP,
18900 args, complain, in_decl);
18901 if (tmp == NULL_TREE)
18902 tmp = error_mark_node;
18904 else
18906 kind = (enum omp_clause_depend_kind)
18907 tree_to_uhwi (OMP_DEPOBJ_CLAUSES (t));
18908 tmp = NULL_TREE;
18910 finish_omp_depobj (EXPR_LOCATION (t), r, kind, tmp);
18912 else
18913 finish_omp_depobj (EXPR_LOCATION (t), r,
18914 OMP_CLAUSE_DEPEND_INVALID,
18915 OMP_DEPOBJ_CLAUSES (t));
18916 break;
18918 case OACC_DATA:
18919 case OMP_TARGET_DATA:
18920 case OMP_TARGET:
18921 tmp = tsubst_omp_clauses (OMP_CLAUSES (t),
18922 TREE_CODE (t) == OACC_DATA
18923 ? C_ORT_ACC
18924 : TREE_CODE (t) == OMP_TARGET
18925 ? C_ORT_OMP_TARGET : C_ORT_OMP,
18926 args, complain, in_decl);
18927 keep_next_level (true);
18928 stmt = begin_omp_structured_block ();
18930 RECUR (OMP_BODY (t));
18931 stmt = finish_omp_structured_block (stmt);
18933 t = copy_node (t);
18934 OMP_BODY (t) = stmt;
18935 OMP_CLAUSES (t) = tmp;
18937 if (TREE_CODE (t) == OMP_TARGET)
18938 finish_omp_target_clauses (EXPR_LOCATION (t), OMP_BODY (t),
18939 &OMP_CLAUSES (t));
18941 if (TREE_CODE (t) == OMP_TARGET && OMP_TARGET_COMBINED (t))
18943 tree teams = cp_walk_tree (&stmt, tsubst_find_omp_teams, NULL, NULL);
18944 if (teams)
18945 /* For combined target teams, ensure the num_teams and
18946 thread_limit clause expressions are evaluated on the host,
18947 before entering the target construct. */
18948 for (tree c = OMP_TEAMS_CLAUSES (teams);
18949 c; c = OMP_CLAUSE_CHAIN (c))
18950 if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS
18951 || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_THREAD_LIMIT)
18952 for (int i = 0;
18953 i <= (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS); ++i)
18954 if (OMP_CLAUSE_OPERAND (c, i)
18955 && TREE_CODE (OMP_CLAUSE_OPERAND (c, i)) != INTEGER_CST)
18957 tree expr = OMP_CLAUSE_OPERAND (c, i);
18958 expr = force_target_expr (TREE_TYPE (expr), expr,
18959 tf_none);
18960 if (expr == error_mark_node)
18961 continue;
18962 tmp = TARGET_EXPR_SLOT (expr);
18963 add_stmt (expr);
18964 OMP_CLAUSE_OPERAND (c, i) = expr;
18965 tree tc = build_omp_clause (OMP_CLAUSE_LOCATION (c),
18966 OMP_CLAUSE_FIRSTPRIVATE);
18967 OMP_CLAUSE_DECL (tc) = tmp;
18968 OMP_CLAUSE_CHAIN (tc) = OMP_TARGET_CLAUSES (t);
18969 OMP_TARGET_CLAUSES (t) = tc;
18972 add_stmt (t);
18973 break;
18975 case OACC_DECLARE:
18976 t = copy_node (t);
18977 tmp = tsubst_omp_clauses (OACC_DECLARE_CLAUSES (t), C_ORT_ACC, args,
18978 complain, in_decl);
18979 OACC_DECLARE_CLAUSES (t) = tmp;
18980 add_stmt (t);
18981 break;
18983 case OMP_TARGET_UPDATE:
18984 case OMP_TARGET_ENTER_DATA:
18985 case OMP_TARGET_EXIT_DATA:
18986 tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_OMP, args,
18987 complain, in_decl);
18988 t = copy_node (t);
18989 OMP_STANDALONE_CLAUSES (t) = tmp;
18990 add_stmt (t);
18991 break;
18993 case OACC_CACHE:
18994 case OACC_ENTER_DATA:
18995 case OACC_EXIT_DATA:
18996 case OACC_UPDATE:
18997 tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_ACC, args,
18998 complain, in_decl);
18999 t = copy_node (t);
19000 OMP_STANDALONE_CLAUSES (t) = tmp;
19001 add_stmt (t);
19002 break;
19004 case OMP_ORDERED:
19005 tmp = tsubst_omp_clauses (OMP_ORDERED_CLAUSES (t), C_ORT_OMP, args,
19006 complain, in_decl);
19007 if (OMP_BODY (t))
19009 stmt = push_stmt_list ();
19010 RECUR (OMP_BODY (t));
19011 stmt = pop_stmt_list (stmt);
19013 else
19014 stmt = NULL_TREE;
19016 t = copy_node (t);
19017 OMP_BODY (t) = stmt;
19018 OMP_ORDERED_CLAUSES (t) = tmp;
19019 add_stmt (t);
19020 break;
19022 case OMP_MASTER:
19023 case OMP_STRUCTURED_BLOCK:
19024 omp_parallel_combined_clauses = NULL;
19025 /* FALLTHRU */
19026 case OMP_SECTION:
19027 stmt = push_stmt_list ();
19028 RECUR (OMP_BODY (t));
19029 stmt = pop_stmt_list (stmt);
19031 t = copy_node (t);
19032 OMP_BODY (t) = stmt;
19033 add_stmt (t);
19034 break;
19036 case OMP_ATOMIC:
19037 gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
19038 tmp = NULL_TREE;
19039 if (TREE_CODE (TREE_OPERAND (t, 0)) == OMP_CLAUSE)
19040 tmp = tsubst_omp_clauses (TREE_OPERAND (t, 0), C_ORT_OMP, args,
19041 complain, in_decl);
19042 if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
19044 tree op1 = TREE_OPERAND (t, 1);
19045 tree rhs1 = NULL_TREE;
19046 tree r = NULL_TREE;
19047 tree lhs, rhs;
19048 if (TREE_CODE (op1) == COMPOUND_EXPR)
19050 rhs1 = RECUR (TREE_OPERAND (op1, 0));
19051 op1 = TREE_OPERAND (op1, 1);
19053 if (TREE_CODE (op1) == COND_EXPR)
19055 gcc_assert (rhs1 == NULL_TREE);
19056 tree c = TREE_OPERAND (op1, 0);
19057 if (TREE_CODE (c) == MODIFY_EXPR)
19059 r = RECUR (TREE_OPERAND (c, 0));
19060 c = TREE_OPERAND (c, 1);
19062 gcc_assert (TREE_CODE (c) == EQ_EXPR);
19063 rhs = RECUR (TREE_OPERAND (c, 1));
19064 lhs = RECUR (TREE_OPERAND (op1, 2));
19065 rhs1 = RECUR (TREE_OPERAND (op1, 1));
19067 else
19069 lhs = RECUR (TREE_OPERAND (op1, 0));
19070 rhs = RECUR (TREE_OPERAND (op1, 1));
19072 finish_omp_atomic (EXPR_LOCATION (t), OMP_ATOMIC, TREE_CODE (op1),
19073 lhs, rhs, NULL_TREE, NULL_TREE, rhs1, r,
19074 tmp, OMP_ATOMIC_MEMORY_ORDER (t),
19075 OMP_ATOMIC_WEAK (t));
19077 else
19079 tree op1 = TREE_OPERAND (t, 1);
19080 tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
19081 tree rhs1 = NULL_TREE, r = NULL_TREE;
19082 enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
19083 enum tree_code opcode = NOP_EXPR;
19084 if (code == OMP_ATOMIC_READ)
19086 v = RECUR (TREE_OPERAND (op1, 0));
19087 lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
19089 else if (code == OMP_ATOMIC_CAPTURE_OLD
19090 || code == OMP_ATOMIC_CAPTURE_NEW)
19092 tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
19093 v = RECUR (TREE_OPERAND (op1, 0));
19094 lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
19095 if (TREE_CODE (op11) == COMPOUND_EXPR)
19097 rhs1 = RECUR (TREE_OPERAND (op11, 0));
19098 op11 = TREE_OPERAND (op11, 1);
19100 if (TREE_CODE (op11) == COND_EXPR)
19102 gcc_assert (rhs1 == NULL_TREE);
19103 tree c = TREE_OPERAND (op11, 0);
19104 if (TREE_CODE (c) == MODIFY_EXPR)
19106 r = RECUR (TREE_OPERAND (c, 0));
19107 c = TREE_OPERAND (c, 1);
19109 gcc_assert (TREE_CODE (c) == EQ_EXPR);
19110 rhs = RECUR (TREE_OPERAND (c, 1));
19111 lhs = RECUR (TREE_OPERAND (op11, 2));
19112 rhs1 = RECUR (TREE_OPERAND (op11, 1));
19114 else
19116 lhs = RECUR (TREE_OPERAND (op11, 0));
19117 rhs = RECUR (TREE_OPERAND (op11, 1));
19119 opcode = TREE_CODE (op11);
19120 if (opcode == MODIFY_EXPR)
19121 opcode = NOP_EXPR;
19123 else
19125 code = OMP_ATOMIC;
19126 lhs = RECUR (TREE_OPERAND (op1, 0));
19127 rhs = RECUR (TREE_OPERAND (op1, 1));
19129 finish_omp_atomic (EXPR_LOCATION (t), code, opcode, lhs, rhs, v,
19130 lhs1, rhs1, r, tmp,
19131 OMP_ATOMIC_MEMORY_ORDER (t), OMP_ATOMIC_WEAK (t));
19133 break;
19135 case TRANSACTION_EXPR:
19137 int flags = 0;
19138 flags |= (TRANSACTION_EXPR_OUTER (t) ? TM_STMT_ATTR_OUTER : 0);
19139 flags |= (TRANSACTION_EXPR_RELAXED (t) ? TM_STMT_ATTR_RELAXED : 0);
19141 if (TRANSACTION_EXPR_IS_STMT (t))
19143 tree body = TRANSACTION_EXPR_BODY (t);
19144 tree noex = NULL_TREE;
19145 if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
19147 noex = MUST_NOT_THROW_COND (body);
19148 if (noex == NULL_TREE)
19149 noex = boolean_true_node;
19150 body = TREE_OPERAND (body, 0);
19152 stmt = begin_transaction_stmt (input_location, NULL, flags);
19153 RECUR (body);
19154 finish_transaction_stmt (stmt, NULL, flags, RECUR (noex));
19156 else
19158 stmt = build_transaction_expr (EXPR_LOCATION (t),
19159 RECUR (TRANSACTION_EXPR_BODY (t)),
19160 flags, NULL_TREE);
19161 RETURN (stmt);
19164 break;
19166 case MUST_NOT_THROW_EXPR:
19168 tree op0 = RECUR (TREE_OPERAND (t, 0));
19169 tree cond = RECUR (MUST_NOT_THROW_COND (t));
19170 RETURN (build_must_not_throw_expr (op0, cond));
19173 case EXPR_PACK_EXPANSION:
19174 error ("invalid use of pack expansion expression");
19175 RETURN (error_mark_node);
19177 case NONTYPE_ARGUMENT_PACK:
19178 error ("use %<...%> to expand argument pack");
19179 RETURN (error_mark_node);
19181 case COMPOUND_EXPR:
19182 tmp = RECUR (TREE_OPERAND (t, 0));
19183 if (tmp == NULL_TREE)
19184 /* If the first operand was a statement, we're done with it. */
19185 RETURN (RECUR (TREE_OPERAND (t, 1)));
19186 RETURN (build_x_compound_expr (EXPR_LOCATION (t), tmp,
19187 RECUR (TREE_OPERAND (t, 1)),
19188 templated_operator_saved_lookups (t),
19189 complain));
19191 case PREDICT_EXPR:
19192 RETURN (add_stmt (copy_node (t)));
19194 default:
19195 gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
19197 RETURN (tsubst_expr (t, args, complain, in_decl));
19200 RETURN (NULL_TREE);
19201 out:
19202 input_location = loc;
19203 return r;
19204 #undef RECUR
19205 #undef RETURN
19208 /* Instantiate the special body of the artificial DECL_OMP_DECLARE_REDUCTION
19209 function. For description of the body see comment above
19210 cp_parser_omp_declare_reduction_exprs. */
19212 static void
19213 tsubst_omp_udr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
19215 if (t == NULL_TREE || t == error_mark_node)
19216 return;
19218 gcc_assert (TREE_CODE (t) == STATEMENT_LIST && current_function_decl);
19220 tree_stmt_iterator tsi;
19221 int i;
19222 tree stmts[7];
19223 memset (stmts, 0, sizeof stmts);
19224 for (i = 0, tsi = tsi_start (t);
19225 i < 7 && !tsi_end_p (tsi);
19226 i++, tsi_next (&tsi))
19227 stmts[i] = tsi_stmt (tsi);
19228 gcc_assert (tsi_end_p (tsi));
19230 if (i >= 3)
19232 gcc_assert (TREE_CODE (stmts[0]) == DECL_EXPR
19233 && TREE_CODE (stmts[1]) == DECL_EXPR);
19234 tree omp_out = tsubst (DECL_EXPR_DECL (stmts[0]),
19235 args, complain, in_decl);
19236 tree omp_in = tsubst (DECL_EXPR_DECL (stmts[1]),
19237 args, complain, in_decl);
19238 /* tsubsting a local var_decl leaves DECL_CONTEXT null, as we
19239 expect to be pushing it. */
19240 DECL_CONTEXT (omp_out) = current_function_decl;
19241 DECL_CONTEXT (omp_in) = current_function_decl;
19242 keep_next_level (true);
19243 tree block = begin_omp_structured_block ();
19244 tsubst_stmt (stmts[2], args, complain, in_decl);
19245 block = finish_omp_structured_block (block);
19246 block = maybe_cleanup_point_expr_void (block);
19247 add_decl_expr (omp_out);
19248 copy_warning (omp_out, DECL_EXPR_DECL (stmts[0]));
19249 add_decl_expr (omp_in);
19250 finish_expr_stmt (block);
19252 if (i >= 6)
19254 gcc_assert (TREE_CODE (stmts[3]) == DECL_EXPR
19255 && TREE_CODE (stmts[4]) == DECL_EXPR);
19256 tree omp_priv = tsubst (DECL_EXPR_DECL (stmts[3]),
19257 args, complain, in_decl);
19258 tree omp_orig = tsubst (DECL_EXPR_DECL (stmts[4]),
19259 args, complain, in_decl);
19260 DECL_CONTEXT (omp_priv) = current_function_decl;
19261 DECL_CONTEXT (omp_orig) = current_function_decl;
19262 keep_next_level (true);
19263 tree block = begin_omp_structured_block ();
19264 tsubst_stmt (stmts[5], args, complain, in_decl);
19265 block = finish_omp_structured_block (block);
19266 block = maybe_cleanup_point_expr_void (block);
19267 cp_walk_tree (&block, cp_remove_omp_priv_cleanup_stmt, omp_priv, NULL);
19268 add_decl_expr (omp_priv);
19269 add_decl_expr (omp_orig);
19270 finish_expr_stmt (block);
19271 if (i == 7)
19272 add_decl_expr (omp_orig);
19276 /* T is a postfix-expression that is not being used in a function
19277 call. Return the substituted version of T. */
19279 static tree
19280 tsubst_non_call_postfix_expression (tree t, tree args,
19281 tsubst_flags_t complain,
19282 tree in_decl)
19284 if (TREE_CODE (t) == SCOPE_REF)
19285 t = tsubst_qualified_id (t, args, complain, in_decl,
19286 /*done=*/false, /*address_p=*/false);
19287 else
19288 t = tsubst_expr (t, args, complain, in_decl);
19290 return t;
19293 /* Subroutine of tsubst_lambda_expr: add the FIELD/INIT capture pair to the
19294 LAMBDA_EXPR_CAPTURE_LIST passed in LIST. Do deduction for a previously
19295 dependent init-capture. EXPLICIT_P is true if the original list had
19296 explicit captures. */
19298 static void
19299 prepend_one_capture (tree field, tree init, tree &list, bool explicit_p,
19300 tsubst_flags_t complain)
19302 if (tree auto_node = type_uses_auto (TREE_TYPE (field)))
19304 tree type = NULL_TREE;
19305 if (!init)
19307 if (complain & tf_error)
19308 error ("empty initializer in lambda init-capture");
19309 init = error_mark_node;
19311 else if (TREE_CODE (init) == TREE_LIST)
19312 init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
19313 if (!type)
19314 type = do_auto_deduction (TREE_TYPE (field), init, auto_node, complain);
19315 TREE_TYPE (field) = type;
19316 cp_apply_type_quals_to_decl (cp_type_quals (type), field);
19318 list = tree_cons (field, init, list);
19319 LAMBDA_CAPTURE_EXPLICIT_P (list) = explicit_p;
19322 /* T is a LAMBDA_EXPR. Generate a new LAMBDA_EXPR for the current
19323 instantiation context. Instantiating a pack expansion containing a lambda
19324 might result in multiple lambdas all based on the same lambda in the
19325 template. */
19327 tree
19328 tsubst_lambda_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
19330 tree oldfn = lambda_function (t);
19331 in_decl = oldfn;
19333 tree r = build_lambda_expr ();
19335 LAMBDA_EXPR_LOCATION (r)
19336 = LAMBDA_EXPR_LOCATION (t);
19337 LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
19338 = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
19339 LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
19340 if (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
19341 LAMBDA_EXPR_REGEN_INFO (r)
19342 = build_template_info (t, add_to_template_args (TI_ARGS (ti),
19343 preserve_args (args)));
19344 else
19345 LAMBDA_EXPR_REGEN_INFO (r)
19346 = build_template_info (t, preserve_args (args));
19348 gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
19349 && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
19351 vec<tree,va_gc>* field_packs = NULL;
19353 for (tree cap = LAMBDA_EXPR_CAPTURE_LIST (t); cap;
19354 cap = TREE_CHAIN (cap))
19356 tree ofield = TREE_PURPOSE (cap);
19357 tree init = TREE_VALUE (cap);
19358 if (PACK_EXPANSION_P (init))
19359 init = tsubst_pack_expansion (init, args, complain, in_decl);
19360 else
19361 init = tsubst_expr (init, args, complain, in_decl);
19363 if (init == error_mark_node)
19364 return error_mark_node;
19366 if (init && TREE_CODE (init) == TREE_LIST)
19367 init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
19369 if (!processing_template_decl
19370 && init && TREE_CODE (init) != TREE_VEC
19371 && variably_modified_type_p (TREE_TYPE (init), NULL_TREE))
19373 /* For a VLA, simply tsubsting the field type won't work, we need to
19374 go through add_capture again. XXX do we want to do this for all
19375 captures? */
19376 tree name = (get_identifier
19377 (IDENTIFIER_POINTER (DECL_NAME (ofield)) + 2));
19378 tree ftype = TREE_TYPE (ofield);
19379 bool by_ref = (TYPE_REF_P (ftype)
19380 || (TREE_CODE (ftype) == DECLTYPE_TYPE
19381 && DECLTYPE_FOR_REF_CAPTURE (ftype)));
19382 add_capture (r, name, init, by_ref, !DECL_NORMAL_CAPTURE_P (ofield));
19383 continue;
19386 if (PACK_EXPANSION_P (ofield))
19387 ofield = PACK_EXPANSION_PATTERN (ofield);
19388 tree field = tsubst_decl (ofield, args, complain);
19390 if (DECL_PACK_P (ofield) && !DECL_NORMAL_CAPTURE_P (ofield))
19392 /* Remember these for when we've pushed local_specializations. */
19393 vec_safe_push (field_packs, ofield);
19394 vec_safe_push (field_packs, field);
19397 if (field == error_mark_node)
19398 return error_mark_node;
19400 if (TREE_CODE (field) == TREE_VEC)
19402 int len = TREE_VEC_LENGTH (field);
19403 gcc_assert (TREE_CODE (init) == TREE_VEC
19404 && TREE_VEC_LENGTH (init) == len);
19405 for (int i = 0; i < len; ++i)
19406 prepend_one_capture (TREE_VEC_ELT (field, i),
19407 TREE_VEC_ELT (init, i),
19408 LAMBDA_EXPR_CAPTURE_LIST (r),
19409 LAMBDA_CAPTURE_EXPLICIT_P (cap),
19410 complain);
19412 else
19414 prepend_one_capture (field, init, LAMBDA_EXPR_CAPTURE_LIST (r),
19415 LAMBDA_CAPTURE_EXPLICIT_P (cap), complain);
19417 if (id_equal (DECL_NAME (field), "__this"))
19418 LAMBDA_EXPR_THIS_CAPTURE (r) = field;
19422 tree type = begin_lambda_type (r);
19423 if (type == error_mark_node)
19424 return error_mark_node;
19426 if (LAMBDA_EXPR_EXTRA_SCOPE (t))
19427 record_lambda_scope (r);
19428 else if (TYPE_NAMESPACE_SCOPE_P (TREE_TYPE (t)))
19429 /* If we're pushed into another scope (PR105652), fix it. */
19430 TYPE_CONTEXT (type) = DECL_CONTEXT (TYPE_NAME (type))
19431 = TYPE_CONTEXT (TREE_TYPE (t));
19432 record_lambda_scope_discriminator (r);
19434 /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set. */
19435 determine_visibility (TYPE_NAME (type));
19437 register_capture_members (LAMBDA_EXPR_CAPTURE_LIST (r));
19439 tree oldtmpl = (generic_lambda_fn_p (oldfn)
19440 ? DECL_TI_TEMPLATE (oldfn)
19441 : NULL_TREE);
19443 tree tparms = NULL_TREE;
19444 if (oldtmpl)
19445 tparms = tsubst_template_parms (DECL_TEMPLATE_PARMS (oldtmpl), args, complain);
19447 tree fntype = static_fn_type (oldfn);
19449 tree saved_ctp = current_template_parms;
19450 if (oldtmpl)
19452 ++processing_template_decl;
19453 current_template_parms = tparms;
19455 fntype = tsubst (fntype, args, complain, in_decl);
19456 if (oldtmpl)
19458 current_template_parms = saved_ctp;
19459 --processing_template_decl;
19462 if (fntype == error_mark_node)
19463 r = error_mark_node;
19464 else
19466 /* The body of a lambda-expression is not a subexpression of the
19467 enclosing expression. Parms are to have DECL_CHAIN tsubsted,
19468 which would be skipped if cp_unevaluated_operand. */
19469 cp_evaluated ev;
19471 /* Fix the type of 'this'. */
19472 fntype = build_memfn_type (fntype, type,
19473 type_memfn_quals (fntype),
19474 type_memfn_rqual (fntype));
19475 tree inst = (oldtmpl
19476 ? tsubst_template_decl (oldtmpl, args, complain,
19477 fntype, tparms)
19478 : tsubst_function_decl (oldfn, args, complain, fntype));
19479 if (inst == error_mark_node)
19481 r = error_mark_node;
19482 goto out;
19484 finish_member_declaration (inst);
19485 record_lambda_scope_sig_discriminator (r, inst);
19487 tree fn = oldtmpl ? DECL_TEMPLATE_RESULT (inst) : inst;
19489 /* Let finish_function set this. */
19490 DECL_DECLARED_CONSTEXPR_P (fn) = false;
19492 bool nested = cfun;
19493 if (nested)
19494 push_function_context ();
19495 else
19496 /* Still increment function_depth so that we don't GC in the
19497 middle of an expression. */
19498 ++function_depth;
19500 local_specialization_stack s (lss_copy);
19502 bool save_in_consteval_if_p = in_consteval_if_p;
19503 in_consteval_if_p = false;
19505 tree body = start_lambda_function (fn, r);
19507 /* Now record them for lookup_init_capture_pack. */
19508 int fplen = vec_safe_length (field_packs);
19509 for (int i = 0; i < fplen; )
19511 tree pack = (*field_packs)[i++];
19512 tree inst = (*field_packs)[i++];
19513 register_local_specialization (inst, pack);
19515 release_tree_vector (field_packs);
19517 register_parameter_specializations (oldfn, fn);
19519 if (oldtmpl)
19521 /* We might not partially instantiate some parts of the function, so
19522 copy these flags from the original template. */
19523 language_function *ol = DECL_STRUCT_FUNCTION (oldfn)->language;
19524 current_function_returns_value = ol->returns_value;
19525 current_function_returns_null = ol->returns_null;
19526 current_function_returns_abnormally = ol->returns_abnormally;
19527 current_function_infinite_loop = ol->infinite_loop;
19530 /* [temp.deduct] A lambda-expression appearing in a function type or a
19531 template parameter is not considered part of the immediate context for
19532 the purposes of template argument deduction. */
19533 complain = tf_warning_or_error;
19535 tree saved = DECL_SAVED_TREE (oldfn);
19536 if (TREE_CODE (saved) == BIND_EXPR && BIND_EXPR_BODY_BLOCK (saved))
19537 /* We already have a body block from start_lambda_function, we don't
19538 need another to confuse NRV (91217). */
19539 saved = BIND_EXPR_BODY (saved);
19541 tsubst_stmt (saved, args, complain, r);
19543 finish_lambda_function (body);
19545 in_consteval_if_p = save_in_consteval_if_p;
19547 if (nested)
19548 pop_function_context ();
19549 else
19550 --function_depth;
19552 /* The capture list was built up in reverse order; fix that now. */
19553 LAMBDA_EXPR_CAPTURE_LIST (r)
19554 = nreverse (LAMBDA_EXPR_CAPTURE_LIST (r));
19556 LAMBDA_EXPR_THIS_CAPTURE (r) = NULL_TREE;
19558 maybe_add_lambda_conv_op (type);
19561 out:
19562 finish_struct (type, /*attr*/NULL_TREE);
19564 insert_pending_capture_proxies ();
19566 return r;
19569 /* Subroutine of maybe_fold_fn_template_args. */
19571 static bool
19572 fold_targs_r (tree targs, tsubst_flags_t complain)
19574 int len = TREE_VEC_LENGTH (targs);
19575 for (int i = 0; i < len; ++i)
19577 tree &elt = TREE_VEC_ELT (targs, i);
19578 if (!elt || TYPE_P (elt)
19579 || TREE_CODE (elt) == TEMPLATE_DECL)
19580 continue;
19581 if (TREE_CODE (elt) == NONTYPE_ARGUMENT_PACK)
19583 if (!fold_targs_r (ARGUMENT_PACK_ARGS (elt), complain))
19584 return false;
19586 else if (/* We can only safely preevaluate scalar prvalues. */
19587 SCALAR_TYPE_P (TREE_TYPE (elt))
19588 && !glvalue_p (elt)
19589 && !TREE_CONSTANT (elt))
19591 elt = cxx_constant_value (elt, complain);
19592 if (elt == error_mark_node)
19593 return false;
19597 return true;
19600 /* Try to do constant evaluation of any explicit template arguments in FN
19601 before overload resolution, to get any errors only once. Return true iff
19602 we didn't have any problems folding. */
19604 static bool
19605 maybe_fold_fn_template_args (tree fn, tsubst_flags_t complain)
19607 if (processing_template_decl || fn == NULL_TREE)
19608 return true;
19609 if (fn == error_mark_node)
19610 return false;
19611 if (TREE_CODE (fn) == OFFSET_REF
19612 || TREE_CODE (fn) == COMPONENT_REF)
19613 fn = TREE_OPERAND (fn, 1);
19614 if (BASELINK_P (fn))
19615 fn = BASELINK_FUNCTIONS (fn);
19616 if (TREE_CODE (fn) != TEMPLATE_ID_EXPR)
19617 return true;
19618 tree targs = TREE_OPERAND (fn, 1);
19619 if (targs == NULL_TREE)
19620 return true;
19621 if (targs == error_mark_node)
19622 return false;
19623 return fold_targs_r (targs, complain);
19626 /* Helper function for tsubst_expr CALL_EXPR and ARRAY_REF handling. */
19628 static void
19629 tsubst_call_args (tree t, tree args, tsubst_flags_t complain,
19630 tree in_decl, releasing_vec &call_args)
19632 unsigned int nargs = call_expr_nargs (t);
19633 for (unsigned int i = 0; i < nargs; ++i)
19635 tree arg = CALL_EXPR_ARG (t, i);
19637 if (!PACK_EXPANSION_P (arg))
19638 vec_safe_push (call_args, tsubst_expr (arg, args, complain, in_decl));
19639 else
19641 /* Expand the pack expansion and push each entry onto CALL_ARGS. */
19642 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
19643 if (TREE_CODE (arg) == TREE_VEC)
19645 unsigned int len, j;
19647 len = TREE_VEC_LENGTH (arg);
19648 for (j = 0; j < len; ++j)
19650 tree value = TREE_VEC_ELT (arg, j);
19651 if (value != NULL_TREE)
19652 value = convert_from_reference (value);
19653 vec_safe_push (call_args, value);
19656 else
19657 /* A partial substitution. Add one entry. */
19658 vec_safe_push (call_args, arg);
19663 /* Like tsubst but deals with expressions and performs semantic
19664 analysis. */
19666 tree
19667 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
19669 #define RETURN(EXP) do { retval = (EXP); goto out; } while(0)
19670 #define RECUR(NODE) \
19671 tsubst_expr (NODE, args, complain, in_decl)
19673 tree retval, op1;
19674 location_t save_loc;
19676 if (t == NULL_TREE || t == error_mark_node)
19677 return t;
19679 save_loc = input_location;
19680 if (location_t eloc = cp_expr_location (t))
19681 input_location = eloc;
19683 /* N3276 decltype magic only applies to calls at the top level or on the
19684 right side of a comma. */
19685 tsubst_flags_t decltype_flag = (complain & tf_decltype);
19686 complain &= ~tf_decltype;
19688 /* This flag only applies to id-expressions at the top level, and
19689 controls resolution thereof. */
19690 tsubst_flags_t no_name_lookup_flag = (complain & tf_no_name_lookup);
19691 complain &= ~tf_no_name_lookup;
19693 if (!no_name_lookup_flag)
19694 if (tree d = maybe_dependent_member_ref (t, args, complain, in_decl))
19695 return d;
19697 switch (TREE_CODE (t))
19699 case USING_DECL:
19700 t = DECL_NAME (t);
19701 /* Fall through. */
19702 case IDENTIFIER_NODE:
19704 tree decl;
19705 cp_id_kind idk;
19706 const char *error_msg;
19708 if (IDENTIFIER_CONV_OP_P (t))
19710 tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19711 t = make_conv_op_name (new_type);
19714 if (no_name_lookup_flag)
19715 RETURN (t);
19717 /* Look up the name. */
19718 decl = lookup_name (t);
19720 /* By convention, expressions use ERROR_MARK_NODE to indicate
19721 failure, not NULL_TREE. */
19722 if (decl == NULL_TREE)
19723 decl = error_mark_node;
19725 decl = finish_id_expression (t, decl, NULL_TREE,
19726 &idk,
19727 /*i_c_e_p=*/false,
19728 /*allow_i_c_e_p=*/true,
19729 /*non_i_c_e_p=*/nullptr,
19730 /*template_p=*/false,
19731 /*done=*/true,
19732 /*address_p=*/false,
19733 /*template_arg_p=*/false,
19734 &error_msg,
19735 input_location);
19736 if (error_msg)
19737 error (error_msg);
19738 if (identifier_p (decl))
19740 if (complain & tf_error)
19741 unqualified_name_lookup_error (decl);
19742 decl = error_mark_node;
19744 RETURN (decl);
19747 case TEMPLATE_ID_EXPR:
19749 tree object;
19750 tree templ = TREE_OPERAND (t, 0);
19751 tree targs = TREE_OPERAND (t, 1);
19753 if (no_name_lookup_flag)
19754 templ = tsubst_name (templ, args, complain, in_decl);
19755 else
19756 templ = tsubst_expr (templ, args, complain, in_decl);
19758 if (targs)
19759 targs = tsubst_template_args (targs, args, complain, in_decl);
19760 if (targs == error_mark_node)
19761 RETURN (error_mark_node);
19763 if (TREE_CODE (templ) == SCOPE_REF)
19765 tree name = TREE_OPERAND (templ, 1);
19766 tree tid = lookup_template_function (name, targs);
19767 TREE_OPERAND (templ, 1) = tid;
19768 RETURN (templ);
19771 if (concept_definition_p (templ))
19773 tree check = build_concept_check (templ, targs, complain);
19774 if (check == error_mark_node)
19775 RETURN (error_mark_node);
19777 tree id = unpack_concept_check (check);
19779 /* If we built a function concept check, return the underlying
19780 template-id. So we can evaluate it as a function call. */
19781 if (function_concept_p (TREE_OPERAND (id, 0)))
19782 RETURN (id);
19784 RETURN (check);
19787 if (variable_template_p (templ))
19789 if (no_name_lookup_flag)
19790 RETURN (lookup_template_variable (templ, targs, complain));
19792 tree r = lookup_and_finish_template_variable (templ, targs,
19793 complain);
19794 r = convert_from_reference (r);
19795 r = maybe_wrap_with_location (r, EXPR_LOCATION (t));
19796 RETURN (r);
19799 if (TREE_CODE (templ) == COMPONENT_REF)
19801 object = TREE_OPERAND (templ, 0);
19802 templ = TREE_OPERAND (templ, 1);
19804 else
19805 object = NULL_TREE;
19807 tree tid = lookup_template_function (templ, targs);
19808 protected_set_expr_location (tid, EXPR_LOCATION (t));
19810 if (object)
19811 RETURN (build3 (COMPONENT_REF, TREE_TYPE (tid),
19812 object, tid, NULL_TREE));
19813 else if (no_name_lookup_flag)
19814 RETURN (tid);
19815 else if (identifier_p (templ))
19817 /* C++20 P0846: we can encounter an IDENTIFIER_NODE here when
19818 name lookup found nothing when parsing the template name. */
19819 gcc_assert (cxx_dialect >= cxx20 || seen_error ());
19820 RETURN (tid);
19822 else
19823 RETURN (baselink_for_fns (tid));
19826 case INDIRECT_REF:
19828 tree r = RECUR (TREE_OPERAND (t, 0));
19830 if (REFERENCE_REF_P (t))
19832 /* A type conversion to reference type will be enclosed in
19833 such an indirect ref, but the substitution of the cast
19834 will have also added such an indirect ref. */
19835 r = convert_from_reference (r);
19837 else
19838 r = build_x_indirect_ref (input_location, r, RO_UNARY_STAR,
19839 templated_operator_saved_lookups (t),
19840 complain|decltype_flag);
19842 if (REF_PARENTHESIZED_P (t))
19843 r = force_paren_expr (r);
19845 RETURN (r);
19848 case NOP_EXPR:
19850 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19851 tree op0 = RECUR (TREE_OPERAND (t, 0));
19852 RETURN (build_nop (type, op0));
19855 case IMPLICIT_CONV_EXPR:
19857 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19858 tree expr = RECUR (TREE_OPERAND (t, 0));
19859 if (dependent_type_p (type) || type_dependent_expression_p (expr))
19861 retval = copy_node (t);
19862 TREE_TYPE (retval) = type;
19863 TREE_OPERAND (retval, 0) = expr;
19864 RETURN (retval);
19866 if (IMPLICIT_CONV_EXPR_NONTYPE_ARG (t))
19867 /* We'll pass this to convert_nontype_argument again, we don't need
19868 to actually perform any conversion here. */
19869 RETURN (expr);
19870 int flags = LOOKUP_IMPLICIT;
19871 if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
19872 flags = LOOKUP_NORMAL;
19873 if (IMPLICIT_CONV_EXPR_BRACED_INIT (t))
19874 flags |= LOOKUP_NO_NARROWING;
19875 RETURN (perform_implicit_conversion_flags (type, expr, complain,
19876 flags));
19879 case CONVERT_EXPR:
19881 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19882 tree op0 = RECUR (TREE_OPERAND (t, 0));
19883 if (op0 == error_mark_node)
19884 RETURN (error_mark_node);
19885 RETURN (build1 (CONVERT_EXPR, type, op0));
19888 case CAST_EXPR:
19889 case REINTERPRET_CAST_EXPR:
19890 case CONST_CAST_EXPR:
19891 case DYNAMIC_CAST_EXPR:
19892 case STATIC_CAST_EXPR:
19894 tree type;
19895 tree op, r = NULL_TREE;
19897 tsubst_flags_t tcomplain = complain;
19898 if (TREE_CODE (t) == CAST_EXPR)
19899 tcomplain |= tf_tst_ok;
19900 type = tsubst (TREE_TYPE (t), args, tcomplain, in_decl);
19902 op = RECUR (TREE_OPERAND (t, 0));
19904 warning_sentinel s(warn_useless_cast);
19905 warning_sentinel s2(warn_ignored_qualifiers);
19906 warning_sentinel s3(warn_int_in_bool_context);
19907 switch (TREE_CODE (t))
19909 case CAST_EXPR:
19910 r = build_functional_cast (input_location, type, op, complain);
19911 break;
19912 case REINTERPRET_CAST_EXPR:
19913 r = build_reinterpret_cast (input_location, type, op, complain);
19914 break;
19915 case CONST_CAST_EXPR:
19916 r = build_const_cast (input_location, type, op, complain);
19917 break;
19918 case DYNAMIC_CAST_EXPR:
19919 r = build_dynamic_cast (input_location, type, op, complain);
19920 break;
19921 case STATIC_CAST_EXPR:
19922 r = build_static_cast (input_location, type, op, complain);
19923 if (IMPLICIT_RVALUE_P (t))
19924 set_implicit_rvalue_p (r);
19925 break;
19926 default:
19927 gcc_unreachable ();
19930 RETURN (r);
19933 case BIT_CAST_EXPR:
19935 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19936 tree op0 = RECUR (TREE_OPERAND (t, 0));
19937 RETURN (cp_build_bit_cast (EXPR_LOCATION (t), type, op0, complain));
19940 case POSTDECREMENT_EXPR:
19941 case POSTINCREMENT_EXPR:
19942 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
19943 args, complain, in_decl);
19944 RETURN (build_x_unary_op (input_location, TREE_CODE (t), op1,
19945 templated_operator_saved_lookups (t),
19946 complain|decltype_flag));
19948 case BIT_NOT_EXPR:
19949 if (identifier_p (TREE_OPERAND (t, 0)))
19951 gcc_checking_assert (no_name_lookup_flag);
19952 RETURN (t);
19954 else if (TYPE_P (TREE_OPERAND (t, 0)))
19956 gcc_checking_assert (no_name_lookup_flag);
19957 tree op0 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
19958 RETURN (build_min_nt_loc (EXPR_LOCATION (t), BIT_NOT_EXPR, op0));
19960 /* Fall through. */
19961 case PREDECREMENT_EXPR:
19962 case PREINCREMENT_EXPR:
19963 case NEGATE_EXPR:
19964 case ABS_EXPR:
19965 case TRUTH_NOT_EXPR:
19966 case UNARY_PLUS_EXPR: /* Unary + */
19967 case REALPART_EXPR:
19968 case IMAGPART_EXPR:
19969 RETURN (build_x_unary_op (input_location, TREE_CODE (t),
19970 RECUR (TREE_OPERAND (t, 0)),
19971 templated_operator_saved_lookups (t),
19972 complain|decltype_flag));
19974 case EXCESS_PRECISION_EXPR:
19976 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19977 tree op0 = RECUR (TREE_OPERAND (t, 0));
19978 if (TREE_CODE (op0) == EXCESS_PRECISION_EXPR)
19979 RETURN (op0);
19980 RETURN (build1_loc (EXPR_LOCATION (t), EXCESS_PRECISION_EXPR,
19981 type, op0));
19984 case FIX_TRUNC_EXPR:
19985 /* convert_like should have created an IMPLICIT_CONV_EXPR. */
19986 gcc_unreachable ();
19988 case ADDR_EXPR:
19989 op1 = TREE_OPERAND (t, 0);
19990 if (TREE_CODE (op1) == LABEL_DECL)
19991 RETURN (finish_label_address_expr (DECL_NAME (op1),
19992 EXPR_LOCATION (op1)));
19993 if (TREE_CODE (op1) == SCOPE_REF)
19994 op1 = tsubst_qualified_id (op1, args, complain, in_decl,
19995 /*done=*/true, /*address_p=*/true);
19996 else
19997 op1 = tsubst_non_call_postfix_expression (op1, args, complain,
19998 in_decl);
19999 RETURN (build_x_unary_op (input_location, ADDR_EXPR, op1,
20000 templated_operator_saved_lookups (t),
20001 complain|decltype_flag));
20003 case PLUS_EXPR:
20004 case MINUS_EXPR:
20005 case MULT_EXPR:
20006 case TRUNC_DIV_EXPR:
20007 case CEIL_DIV_EXPR:
20008 case FLOOR_DIV_EXPR:
20009 case ROUND_DIV_EXPR:
20010 case EXACT_DIV_EXPR:
20011 case BIT_AND_EXPR:
20012 case BIT_IOR_EXPR:
20013 case BIT_XOR_EXPR:
20014 case TRUNC_MOD_EXPR:
20015 case FLOOR_MOD_EXPR:
20016 case TRUTH_ANDIF_EXPR:
20017 case TRUTH_ORIF_EXPR:
20018 case TRUTH_AND_EXPR:
20019 case TRUTH_OR_EXPR:
20020 case RSHIFT_EXPR:
20021 case LSHIFT_EXPR:
20022 case EQ_EXPR:
20023 case NE_EXPR:
20024 case MAX_EXPR:
20025 case MIN_EXPR:
20026 case LE_EXPR:
20027 case GE_EXPR:
20028 case LT_EXPR:
20029 case GT_EXPR:
20030 case SPACESHIP_EXPR:
20031 case MEMBER_REF:
20032 case DOTSTAR_EXPR:
20034 /* If either OP0 or OP1 was value- or type-dependent, suppress
20035 warnings that depend on the range of the types involved. */
20036 tree op0 = TREE_OPERAND (t, 0);
20037 tree op1 = TREE_OPERAND (t, 1);
20038 const bool was_dep = (dependent_operand_p (op0)
20039 || dependent_operand_p (op1));
20040 op0 = RECUR (op0);
20041 op1 = RECUR (op1);
20043 warning_sentinel s1(warn_type_limits, was_dep);
20044 warning_sentinel s2(warn_div_by_zero, was_dep);
20045 warning_sentinel s3(warn_logical_op, was_dep);
20046 warning_sentinel s4(warn_tautological_compare, was_dep);
20047 warning_sentinel s5(warn_address, was_dep);
20049 tree r = build_x_binary_op
20050 (input_location, TREE_CODE (t),
20051 op0,
20052 (warning_suppressed_p (TREE_OPERAND (t, 0))
20053 ? ERROR_MARK
20054 : TREE_CODE (TREE_OPERAND (t, 0))),
20055 op1,
20056 (warning_suppressed_p (TREE_OPERAND (t, 1))
20057 ? ERROR_MARK
20058 : TREE_CODE (TREE_OPERAND (t, 1))),
20059 templated_operator_saved_lookups (t),
20060 /*overload=*/NULL,
20061 complain|decltype_flag);
20062 if (EXPR_P (r))
20063 copy_warning (r, t);
20065 RETURN (r);
20068 case POINTER_PLUS_EXPR:
20070 tree op0 = RECUR (TREE_OPERAND (t, 0));
20071 if (op0 == error_mark_node)
20072 RETURN (error_mark_node);
20073 tree op1 = RECUR (TREE_OPERAND (t, 1));
20074 if (op1 == error_mark_node)
20075 RETURN (error_mark_node);
20076 RETURN (fold_build_pointer_plus (op0, op1));
20079 case SCOPE_REF:
20080 if (no_name_lookup_flag)
20082 tree op0 = tsubst_scope (TREE_OPERAND (t, 0), args, complain, in_decl);
20083 tree op1 = tsubst_name (TREE_OPERAND (t, 1), args, complain, in_decl);
20084 RETURN (build_qualified_name (/*type=*/NULL_TREE, op0, op1,
20085 QUALIFIED_NAME_IS_TEMPLATE (t)));
20087 else
20088 RETURN (tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
20089 /*address_p=*/false));
20091 case BASELINK:
20092 RETURN (tsubst_baselink (t, current_nonlambda_class_type (),
20093 args, complain, in_decl));
20095 case ARRAY_REF:
20096 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20097 args, complain, in_decl);
20098 if (TREE_CODE (TREE_OPERAND (t, 1)) == CALL_EXPR
20099 && (CALL_EXPR_FN (TREE_OPERAND (t, 1))
20100 == ovl_op_identifier (ARRAY_REF)))
20102 tree c = TREE_OPERAND (t, 1);
20103 releasing_vec index_exp_list;
20104 tsubst_call_args (c, args, complain, in_decl, index_exp_list);
20106 tree r;
20107 if (vec_safe_length (index_exp_list) == 1
20108 && !PACK_EXPANSION_P (index_exp_list[0]))
20109 r = grok_array_decl (EXPR_LOCATION (t), op1,
20110 index_exp_list[0], NULL,
20111 complain | decltype_flag);
20112 else
20113 r = grok_array_decl (EXPR_LOCATION (t), op1,
20114 NULL_TREE, &index_exp_list,
20115 complain | decltype_flag);
20116 RETURN (r);
20118 RETURN (build_x_array_ref (EXPR_LOCATION (t), op1,
20119 RECUR (TREE_OPERAND (t, 1)),
20120 complain|decltype_flag));
20122 case SIZEOF_EXPR:
20123 if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
20124 || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
20126 tree expanded, op = TREE_OPERAND (t, 0);
20127 int len = 0;
20129 if (SIZEOF_EXPR_TYPE_P (t))
20130 op = TREE_TYPE (op);
20132 ++cp_unevaluated_operand;
20133 ++c_inhibit_evaluation_warnings;
20134 /* We only want to compute the number of arguments. */
20135 if (PACK_EXPANSION_P (op))
20136 expanded = tsubst_pack_expansion (op, args, complain, in_decl);
20137 else
20138 expanded = tsubst_template_args (ARGUMENT_PACK_ARGS (op),
20139 args, complain, in_decl);
20140 --cp_unevaluated_operand;
20141 --c_inhibit_evaluation_warnings;
20143 if (TREE_CODE (expanded) == TREE_VEC)
20145 len = TREE_VEC_LENGTH (expanded);
20146 /* Set TREE_USED for the benefit of -Wunused. */
20147 for (int i = 0; i < len; i++)
20148 if (DECL_P (TREE_VEC_ELT (expanded, i)))
20149 TREE_USED (TREE_VEC_ELT (expanded, i)) = true;
20152 if (expanded == error_mark_node)
20153 RETURN (error_mark_node);
20154 else if (PACK_EXPANSION_P (expanded)
20155 || (TREE_CODE (expanded) == TREE_VEC
20156 && pack_expansion_args_count (expanded)))
20159 if (PACK_EXPANSION_P (expanded))
20160 /* OK. */;
20161 else if (TREE_VEC_LENGTH (expanded) == 1)
20162 expanded = TREE_VEC_ELT (expanded, 0);
20163 else
20164 expanded = make_argument_pack (expanded);
20166 if (TYPE_P (expanded))
20167 RETURN (cxx_sizeof_or_alignof_type (input_location,
20168 expanded, SIZEOF_EXPR,
20169 false,
20170 complain & tf_error));
20171 else
20172 RETURN (cxx_sizeof_or_alignof_expr (input_location,
20173 expanded, SIZEOF_EXPR,
20174 false,
20175 complain & tf_error));
20177 else
20178 RETURN (build_int_cst (size_type_node, len));
20180 /* Fall through */
20182 case ALIGNOF_EXPR:
20184 tree r;
20186 op1 = TREE_OPERAND (t, 0);
20187 if (TREE_CODE (t) == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (t))
20188 op1 = TREE_TYPE (op1);
20189 bool std_alignof = (TREE_CODE (t) == ALIGNOF_EXPR
20190 && ALIGNOF_EXPR_STD_P (t));
20191 if (!args)
20193 /* When there are no ARGS, we are trying to evaluate a
20194 non-dependent expression from the parser. Trying to do
20195 the substitutions may not work. */
20196 if (!TYPE_P (op1))
20197 op1 = TREE_TYPE (op1);
20199 else
20201 ++cp_unevaluated_operand;
20202 ++c_inhibit_evaluation_warnings;
20203 if (TYPE_P (op1))
20204 op1 = tsubst (op1, args, complain, in_decl);
20205 else
20206 op1 = tsubst_expr (op1, args, complain, in_decl);
20207 --cp_unevaluated_operand;
20208 --c_inhibit_evaluation_warnings;
20210 if (TYPE_P (op1))
20211 r = cxx_sizeof_or_alignof_type (input_location,
20212 op1, TREE_CODE (t), std_alignof,
20213 complain & tf_error);
20214 else
20215 r = cxx_sizeof_or_alignof_expr (input_location,
20216 op1, TREE_CODE (t), std_alignof,
20217 complain & tf_error);
20218 if (TREE_CODE (t) == SIZEOF_EXPR && r != error_mark_node)
20220 if (TREE_CODE (r) != SIZEOF_EXPR || TYPE_P (op1))
20222 if (!processing_template_decl && TYPE_P (op1))
20224 r = build_min (SIZEOF_EXPR, size_type_node,
20225 build1 (NOP_EXPR, op1, error_mark_node));
20226 SIZEOF_EXPR_TYPE_P (r) = 1;
20228 else
20229 r = build_min (SIZEOF_EXPR, size_type_node, op1);
20230 TREE_SIDE_EFFECTS (r) = 0;
20231 TREE_READONLY (r) = 1;
20233 SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
20235 RETURN (r);
20238 case AT_ENCODE_EXPR:
20240 op1 = TREE_OPERAND (t, 0);
20241 ++cp_unevaluated_operand;
20242 ++c_inhibit_evaluation_warnings;
20243 op1 = tsubst (op1, args, complain, in_decl);
20244 --cp_unevaluated_operand;
20245 --c_inhibit_evaluation_warnings;
20246 RETURN (objc_build_encode_expr (op1));
20249 case NOEXCEPT_EXPR:
20250 op1 = TREE_OPERAND (t, 0);
20251 ++cp_unevaluated_operand;
20252 ++c_inhibit_evaluation_warnings;
20253 ++cp_noexcept_operand;
20254 op1 = tsubst_expr (op1, args, complain, in_decl);
20255 --cp_unevaluated_operand;
20256 --c_inhibit_evaluation_warnings;
20257 --cp_noexcept_operand;
20258 RETURN (finish_noexcept_expr (op1, complain));
20260 case MODOP_EXPR:
20262 warning_sentinel s(warn_div_by_zero);
20263 tree lhs = RECUR (TREE_OPERAND (t, 0));
20264 tree rhs = RECUR (TREE_OPERAND (t, 2));
20266 tree r = build_x_modify_expr
20267 (EXPR_LOCATION (t), lhs, TREE_CODE (TREE_OPERAND (t, 1)), rhs,
20268 templated_operator_saved_lookups (t),
20269 complain|decltype_flag);
20270 /* TREE_NO_WARNING must be set if either the expression was
20271 parenthesized or it uses an operator such as >>= rather
20272 than plain assignment. In the former case, it was already
20273 set and must be copied. In the latter case,
20274 build_x_modify_expr sets it and it must not be reset
20275 here. */
20276 if (warning_suppressed_p (t, OPT_Wparentheses))
20277 suppress_warning (r, OPT_Wparentheses);
20279 RETURN (r);
20282 case ARROW_EXPR:
20283 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20284 args, complain, in_decl);
20285 /* Remember that there was a reference to this entity. */
20286 if (DECL_P (op1)
20287 && !mark_used (op1, complain) && !(complain & tf_error))
20288 RETURN (error_mark_node);
20289 RETURN (build_x_arrow (input_location, op1, complain));
20291 case NEW_EXPR:
20293 tree placement = RECUR (TREE_OPERAND (t, 0));
20294 tree init = RECUR (TREE_OPERAND (t, 3));
20295 vec<tree, va_gc> *placement_vec;
20296 vec<tree, va_gc> *init_vec;
20297 tree ret;
20298 location_t loc = EXPR_LOCATION (t);
20300 if (placement == NULL_TREE)
20301 placement_vec = NULL;
20302 else if (placement == error_mark_node)
20303 RETURN (error_mark_node);
20304 else
20306 placement_vec = make_tree_vector ();
20307 for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
20308 vec_safe_push (placement_vec, TREE_VALUE (placement));
20311 /* If there was an initializer in the original tree, but it
20312 instantiated to an empty list, then we should pass a
20313 non-NULL empty vector to tell build_new that it was an
20314 empty initializer() rather than no initializer. This can
20315 only happen when the initializer is a pack expansion whose
20316 parameter packs are of length zero. */
20317 if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
20318 init_vec = NULL;
20319 else if (init == error_mark_node)
20320 RETURN (error_mark_node);
20321 else
20323 init_vec = make_tree_vector ();
20324 if (init == void_node)
20325 gcc_assert (init_vec != NULL);
20326 else
20328 for (; init != NULL_TREE; init = TREE_CHAIN (init))
20329 vec_safe_push (init_vec, TREE_VALUE (init));
20333 /* Avoid passing an enclosing decl to valid_array_size_p. */
20334 in_decl = NULL_TREE;
20336 tree op1 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
20337 tree op2 = RECUR (TREE_OPERAND (t, 2));
20338 ret = build_new (loc, &placement_vec, op1, op2,
20339 &init_vec, NEW_EXPR_USE_GLOBAL (t),
20340 complain);
20342 if (placement_vec != NULL)
20343 release_tree_vector (placement_vec);
20344 if (init_vec != NULL)
20345 release_tree_vector (init_vec);
20347 RETURN (ret);
20350 case DELETE_EXPR:
20352 tree op0 = RECUR (TREE_OPERAND (t, 0));
20353 tree op1 = RECUR (TREE_OPERAND (t, 1));
20354 RETURN (delete_sanity (input_location, op0, op1,
20355 DELETE_EXPR_USE_VEC (t),
20356 DELETE_EXPR_USE_GLOBAL (t),
20357 complain));
20360 case COMPOUND_EXPR:
20362 tree op0 = tsubst_expr (TREE_OPERAND (t, 0), args,
20363 complain & ~tf_decltype, in_decl);
20364 RETURN (build_x_compound_expr (EXPR_LOCATION (t),
20365 op0,
20366 RECUR (TREE_OPERAND (t, 1)),
20367 templated_operator_saved_lookups (t),
20368 complain|decltype_flag));
20371 case CALL_EXPR:
20373 tree function;
20374 unsigned int nargs;
20375 bool qualified_p;
20376 bool koenig_p;
20377 tree ret;
20379 function = CALL_EXPR_FN (t);
20380 /* Internal function with no arguments. */
20381 if (function == NULL_TREE && call_expr_nargs (t) == 0)
20382 RETURN (t);
20384 /* When we parsed the expression, we determined whether or
20385 not Koenig lookup should be performed. */
20386 koenig_p = KOENIG_LOOKUP_P (t);
20387 if (function == NULL_TREE)
20389 koenig_p = false;
20390 qualified_p = false;
20392 else if (TREE_CODE (function) == SCOPE_REF)
20394 qualified_p = true;
20395 function = tsubst_qualified_id (function, args, complain, in_decl,
20396 /*done=*/false,
20397 /*address_p=*/false);
20399 else if (CALL_EXPR_STATIC_CHAIN (t)
20400 && TREE_CODE (function) == FUNCTION_DECL
20401 && fndecl_built_in_p (function, BUILT_IN_CLASSIFY_TYPE))
20403 tree type = tsubst (CALL_EXPR_STATIC_CHAIN (t), args, complain,
20404 in_decl);
20405 if (dependent_type_p (type))
20407 ret = build_vl_exp (CALL_EXPR, 4);
20408 CALL_EXPR_FN (ret) = function;
20409 CALL_EXPR_STATIC_CHAIN (ret) = type;
20410 CALL_EXPR_ARG (ret, 0)
20411 = build_min (SIZEOF_EXPR, size_type_node, type);
20412 TREE_TYPE (ret) = integer_type_node;
20414 else
20415 ret = build_int_cst (integer_type_node, type_to_class (type));
20416 RETURN (ret);
20418 else if (koenig_p
20419 && (identifier_p (function)
20420 || (TREE_CODE (function) == TEMPLATE_ID_EXPR
20421 && identifier_p (TREE_OPERAND (function, 0)))))
20423 /* Do nothing; calling tsubst_expr on an identifier
20424 would incorrectly perform unqualified lookup again.
20426 Note that we can also have an IDENTIFIER_NODE if the earlier
20427 unqualified lookup found a dependent local extern declaration
20428 (as per finish_call_expr); in that case koenig_p will be false
20429 and we do want to do the lookup again to find the substituted
20430 declaration. */
20431 qualified_p = false;
20433 if (TREE_CODE (function) == TEMPLATE_ID_EXPR)
20434 function = tsubst_name (function, args, complain, in_decl);
20436 else
20438 if (TREE_CODE (function) == COMPONENT_REF)
20440 tree op = TREE_OPERAND (function, 1);
20442 qualified_p = (TREE_CODE (op) == SCOPE_REF
20443 || (BASELINK_P (op)
20444 && BASELINK_QUALIFIED_P (op)));
20446 else
20447 qualified_p = false;
20449 if (TREE_CODE (function) == ADDR_EXPR
20450 && TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL)
20451 /* Avoid error about taking the address of a constructor. */
20452 function = TREE_OPERAND (function, 0);
20454 tsubst_flags_t subcomplain = complain;
20455 if (koenig_p && TREE_CODE (function) == FUNCTION_DECL)
20456 /* When KOENIG_P, we don't want to mark_used the callee before
20457 augmenting the overload set via ADL, so during this initial
20458 substitution we disable mark_used by setting tf_conv (68942). */
20459 subcomplain |= tf_conv;
20460 function = tsubst_expr (function, args, subcomplain, in_decl);
20462 if (BASELINK_P (function))
20463 qualified_p = true;
20466 nargs = call_expr_nargs (t);
20467 releasing_vec call_args;
20468 tsubst_call_args (t, args, complain, in_decl, call_args);
20470 /* Stripped-down processing for a call in a thunk. Specifically, in
20471 the thunk template for a generic lambda. */
20472 if (call_from_lambda_thunk_p (t))
20474 /* Now that we've expanded any packs, the number of call args
20475 might be different. */
20476 unsigned int cargs = call_args->length ();
20477 tree thisarg = NULL_TREE;
20478 if (TREE_CODE (function) == COMPONENT_REF)
20480 thisarg = TREE_OPERAND (function, 0);
20481 if (TREE_CODE (thisarg) == INDIRECT_REF)
20482 thisarg = TREE_OPERAND (thisarg, 0);
20483 function = TREE_OPERAND (function, 1);
20484 if (TREE_CODE (function) == BASELINK)
20485 function = BASELINK_FUNCTIONS (function);
20487 /* We aren't going to do normal overload resolution, so force the
20488 template-id to resolve. */
20489 function = resolve_nondeduced_context (function, complain);
20490 for (unsigned i = 0; i < cargs; ++i)
20492 /* In a thunk, pass through args directly, without any
20493 conversions. */
20494 tree arg = (*call_args)[i];
20495 while (TREE_CODE (arg) != PARM_DECL)
20496 arg = TREE_OPERAND (arg, 0);
20497 (*call_args)[i] = arg;
20499 if (thisarg)
20501 /* If there are no other args, just push 'this'. */
20502 if (cargs == 0)
20503 vec_safe_push (call_args, thisarg);
20504 else
20506 /* Otherwise, shift the other args over to make room. */
20507 tree last = (*call_args)[cargs - 1];
20508 vec_safe_push (call_args, last);
20509 for (int i = cargs - 1; i > 0; --i)
20510 (*call_args)[i] = (*call_args)[i - 1];
20511 (*call_args)[0] = thisarg;
20514 ret = build_call_a (function, call_args->length (),
20515 call_args->address ());
20516 /* The thunk location is not interesting. */
20517 SET_EXPR_LOCATION (ret, UNKNOWN_LOCATION);
20518 CALL_FROM_THUNK_P (ret) = true;
20519 if (CLASS_TYPE_P (TREE_TYPE (ret)))
20520 CALL_EXPR_RETURN_SLOT_OPT (ret) = true;
20522 RETURN (ret);
20525 /* We do not perform argument-dependent lookup if normal
20526 lookup finds a non-function, in accordance with the
20527 resolution of DR 218. */
20528 if (koenig_p
20529 && ((is_overloaded_fn (function)
20530 /* If lookup found a member function, the Koenig lookup is
20531 not appropriate, even if an unqualified-name was used
20532 to denote the function. */
20533 && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
20534 || identifier_p (function)
20535 /* C++20 P0846: Lookup found nothing. */
20536 || (TREE_CODE (function) == TEMPLATE_ID_EXPR
20537 && identifier_p (TREE_OPERAND (function, 0))))
20538 /* Only do this when substitution turns a dependent call
20539 into a non-dependent call. */
20540 && type_dependent_expression_p_push (t)
20541 && !any_type_dependent_arguments_p (call_args))
20542 function = perform_koenig_lookup (function, call_args, tf_none);
20544 if (function != NULL_TREE
20545 && (identifier_p (function)
20546 || (TREE_CODE (function) == TEMPLATE_ID_EXPR
20547 && identifier_p (TREE_OPERAND (function, 0))
20548 && !any_dependent_template_arguments_p (TREE_OPERAND
20549 (function, 1))))
20550 && !any_type_dependent_arguments_p (call_args))
20552 bool template_id_p = (TREE_CODE (function) == TEMPLATE_ID_EXPR);
20553 if (template_id_p)
20554 function = TREE_OPERAND (function, 0);
20555 if (koenig_p && (complain & tf_warning_or_error))
20557 /* For backwards compatibility and good diagnostics, try
20558 the unqualified lookup again if we aren't in SFINAE
20559 context. */
20560 tree unq = tsubst_expr (function, args, complain, in_decl);
20561 if (unq == error_mark_node)
20562 RETURN (error_mark_node);
20564 if (unq != function)
20566 char const *const msg
20567 = G_("%qD was not declared in this scope, "
20568 "and no declarations were found by "
20569 "argument-dependent lookup at the point "
20570 "of instantiation");
20572 bool in_lambda = (current_class_type
20573 && LAMBDA_TYPE_P (current_class_type));
20574 /* In a lambda fn, we have to be careful to not
20575 introduce new this captures. Legacy code can't
20576 be using lambdas anyway, so it's ok to be
20577 stricter. Be strict with C++20 template-id ADL too.
20578 And be strict if we're already failing anyway. */
20579 bool strict = in_lambda || template_id_p || seen_error();
20580 bool diag = true;
20581 if (strict)
20582 error_at (cp_expr_loc_or_input_loc (t),
20583 msg, function);
20584 else
20585 diag = permerror (cp_expr_loc_or_input_loc (t),
20586 msg, function);
20587 if (diag)
20589 tree fn = unq;
20591 if (INDIRECT_REF_P (fn))
20592 fn = TREE_OPERAND (fn, 0);
20593 if (is_overloaded_fn (fn))
20594 fn = get_first_fn (fn);
20596 if (!DECL_P (fn))
20597 /* Can't say anything more. */;
20598 else if (DECL_CLASS_SCOPE_P (fn))
20600 location_t loc = cp_expr_loc_or_input_loc (t);
20601 inform (loc,
20602 "declarations in dependent base %qT are "
20603 "not found by unqualified lookup",
20604 DECL_CLASS_CONTEXT (fn));
20605 if (current_class_ptr)
20606 inform (loc,
20607 "use %<this->%D%> instead", function);
20608 else
20609 inform (loc,
20610 "use %<%T::%D%> instead",
20611 current_class_name, function);
20613 else
20614 inform (DECL_SOURCE_LOCATION (fn),
20615 "%qD declared here, later in the "
20616 "translation unit", fn);
20617 if (strict)
20618 RETURN (error_mark_node);
20621 function = unq;
20624 if (identifier_p (function))
20626 if (complain & tf_error)
20627 unqualified_name_lookup_error (function);
20628 RETURN (error_mark_node);
20632 /* Remember that there was a reference to this entity. */
20633 if (function != NULL_TREE
20634 && DECL_P (function)
20635 && !mark_used (function, complain) && !(complain & tf_error))
20636 RETURN (error_mark_node);
20638 if (!maybe_fold_fn_template_args (function, complain))
20639 return error_mark_node;
20641 /* Put back tf_decltype for the actual call. */
20642 complain |= decltype_flag;
20644 if (function == NULL_TREE)
20645 switch (CALL_EXPR_IFN (t))
20647 case IFN_LAUNDER:
20648 gcc_assert (nargs == 1);
20649 if (vec_safe_length (call_args) != 1)
20651 error_at (cp_expr_loc_or_input_loc (t),
20652 "wrong number of arguments to "
20653 "%<__builtin_launder%>");
20654 ret = error_mark_node;
20656 else
20657 ret = finish_builtin_launder (cp_expr_loc_or_input_loc (t),
20658 (*call_args)[0], complain);
20659 break;
20661 case IFN_VEC_CONVERT:
20662 gcc_assert (nargs == 1);
20663 if (vec_safe_length (call_args) != 1)
20665 error_at (cp_expr_loc_or_input_loc (t),
20666 "wrong number of arguments to "
20667 "%<__builtin_convertvector%>");
20668 ret = error_mark_node;
20669 break;
20671 ret = cp_build_vec_convert ((*call_args)[0], input_location,
20672 tsubst (TREE_TYPE (t), args,
20673 complain, in_decl),
20674 complain);
20675 if (TREE_CODE (ret) == VIEW_CONVERT_EXPR)
20676 RETURN (ret);
20677 break;
20679 case IFN_SHUFFLEVECTOR:
20681 ret = build_x_shufflevector (input_location, call_args,
20682 complain);
20683 if (ret != error_mark_node)
20684 RETURN (ret);
20685 break;
20688 case IFN_ASSUME:
20689 gcc_assert (nargs == 1);
20690 if (vec_safe_length (call_args) != 1)
20692 error_at (cp_expr_loc_or_input_loc (t),
20693 "wrong number of arguments to "
20694 "%<assume%> attribute");
20695 ret = error_mark_node;
20697 else
20699 tree &arg = (*call_args)[0];
20700 if (!type_dependent_expression_p (arg))
20701 arg = contextual_conv_bool (arg, tf_warning_or_error);
20702 if (error_operand_p (arg))
20704 ret = error_mark_node;
20705 break;
20707 ret = build_assume_call (EXPR_LOCATION (t), arg);
20708 RETURN (ret);
20710 break;
20712 default:
20713 /* Unsupported internal function with arguments. */
20714 gcc_unreachable ();
20716 else if (TREE_CODE (function) == OFFSET_REF
20717 || TREE_CODE (function) == DOTSTAR_EXPR
20718 || TREE_CODE (function) == MEMBER_REF)
20719 ret = build_offset_ref_call_from_tree (function, &call_args,
20720 complain);
20721 else if (concept_check_p (function))
20723 /* FUNCTION is a template-id referring to a concept definition. */
20724 tree id = unpack_concept_check (function);
20725 tree tmpl = TREE_OPERAND (id, 0);
20726 tree args = TREE_OPERAND (id, 1);
20728 /* Calls to standard and variable concepts should have been
20729 previously diagnosed. */
20730 gcc_assert (function_concept_p (tmpl));
20732 /* Ensure the result is wrapped as a call expression. */
20733 ret = build_concept_check (tmpl, args, tf_warning_or_error);
20735 else
20736 ret = finish_call_expr (function, &call_args,
20737 /*disallow_virtual=*/qualified_p,
20738 koenig_p,
20739 complain);
20741 if (ret != error_mark_node)
20743 bool op = CALL_EXPR_OPERATOR_SYNTAX (t);
20744 bool ord = CALL_EXPR_ORDERED_ARGS (t);
20745 bool rev = CALL_EXPR_REVERSE_ARGS (t);
20746 if (op || ord || rev)
20747 if (tree call = extract_call_expr (ret))
20749 CALL_EXPR_OPERATOR_SYNTAX (call) = op;
20750 CALL_EXPR_ORDERED_ARGS (call) = ord;
20751 CALL_EXPR_REVERSE_ARGS (call) = rev;
20753 if (warning_suppressed_p (t, OPT_Wpessimizing_move))
20754 /* This also suppresses -Wredundant-move. */
20755 suppress_warning (ret, OPT_Wpessimizing_move);
20758 RETURN (ret);
20761 case COND_EXPR:
20763 tree cond = RECUR (TREE_OPERAND (t, 0));
20764 cond = mark_rvalue_use (cond);
20765 tree folded_cond = fold_non_dependent_expr (cond, complain);
20766 tree exp1, exp2;
20768 if (TREE_CODE (folded_cond) == INTEGER_CST)
20770 if (integer_zerop (folded_cond))
20772 ++c_inhibit_evaluation_warnings;
20773 exp1 = RECUR (TREE_OPERAND (t, 1));
20774 --c_inhibit_evaluation_warnings;
20775 exp2 = RECUR (TREE_OPERAND (t, 2));
20777 else
20779 exp1 = RECUR (TREE_OPERAND (t, 1));
20780 ++c_inhibit_evaluation_warnings;
20781 exp2 = RECUR (TREE_OPERAND (t, 2));
20782 --c_inhibit_evaluation_warnings;
20784 cond = folded_cond;
20786 else
20788 exp1 = RECUR (TREE_OPERAND (t, 1));
20789 exp2 = RECUR (TREE_OPERAND (t, 2));
20792 warning_sentinel s(warn_duplicated_branches);
20793 RETURN (build_x_conditional_expr (EXPR_LOCATION (t),
20794 cond, exp1, exp2, complain));
20797 case PSEUDO_DTOR_EXPR:
20799 tree op0 = RECUR (TREE_OPERAND (t, 0));
20800 tree op1 = RECUR (TREE_OPERAND (t, 1));
20801 tree op2 = tsubst (TREE_OPERAND (t, 2), args, complain, in_decl);
20802 RETURN (finish_pseudo_destructor_expr (op0, op1, op2,
20803 input_location));
20806 case TREE_LIST:
20807 RETURN (tsubst_tree_list (t, args, complain, in_decl));
20809 case COMPONENT_REF:
20811 tree object;
20812 tree object_type;
20813 tree member;
20814 tree r;
20816 object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20817 args, complain, in_decl);
20818 /* Remember that there was a reference to this entity. */
20819 if (DECL_P (object)
20820 && !mark_used (object, complain) && !(complain & tf_error))
20821 RETURN (error_mark_node);
20822 object_type = TREE_TYPE (object);
20824 member = TREE_OPERAND (t, 1);
20825 if (BASELINK_P (member))
20826 member = tsubst_baselink (member,
20827 non_reference (TREE_TYPE (object)),
20828 args, complain, in_decl);
20829 else
20830 member = tsubst_name (member, args, complain, in_decl);
20831 if (member == error_mark_node)
20832 RETURN (error_mark_node);
20834 if (object_type && TYPE_PTRMEMFUNC_P (object_type)
20835 && TREE_CODE (member) == FIELD_DECL)
20837 r = build_ptrmemfunc_access_expr (object, DECL_NAME (member));
20838 RETURN (r);
20840 else if (TREE_CODE (member) == FIELD_DECL)
20842 r = finish_non_static_data_member (member, object, NULL_TREE,
20843 complain);
20844 if (TREE_CODE (r) == COMPONENT_REF)
20845 REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
20846 RETURN (r);
20848 else if (type_dependent_expression_p (object))
20849 /* We can't do much here. */;
20850 else if (!CLASS_TYPE_P (object_type))
20852 if (scalarish_type_p (object_type))
20854 tree s = NULL_TREE;
20855 tree dtor = member;
20857 if (TREE_CODE (dtor) == SCOPE_REF)
20859 s = TREE_OPERAND (dtor, 0);
20860 dtor = TREE_OPERAND (dtor, 1);
20862 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
20864 dtor = TREE_OPERAND (dtor, 0);
20865 if (TYPE_P (dtor))
20866 RETURN (finish_pseudo_destructor_expr
20867 (object, s, dtor, input_location));
20871 else if (TREE_CODE (member) == SCOPE_REF
20872 && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
20874 /* Lookup the template functions now that we know what the
20875 scope is. */
20876 tree scope = TREE_OPERAND (member, 0);
20877 tree tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
20878 tree args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
20879 member = lookup_qualified_name (scope, tmpl, LOOK_want::NORMAL,
20880 /*complain=*/false);
20881 if (BASELINK_P (member))
20883 BASELINK_FUNCTIONS (member)
20884 = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
20885 args);
20886 member = (adjust_result_of_qualified_name_lookup
20887 (member, BINFO_TYPE (BASELINK_BINFO (member)),
20888 object_type));
20890 else
20892 qualified_name_lookup_error (scope, tmpl, member,
20893 input_location);
20894 RETURN (error_mark_node);
20897 else if (TREE_CODE (member) == SCOPE_REF
20898 && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
20899 && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
20901 if (complain & tf_error)
20903 if (TYPE_P (TREE_OPERAND (member, 0)))
20904 error ("%qT is not a class or namespace",
20905 TREE_OPERAND (member, 0));
20906 else
20907 error ("%qD is not a class or namespace",
20908 TREE_OPERAND (member, 0));
20910 RETURN (error_mark_node);
20913 r = finish_class_member_access_expr (object, member,
20914 /*template_p=*/false,
20915 complain);
20916 if (REF_PARENTHESIZED_P (t))
20917 r = force_paren_expr (r);
20918 RETURN (r);
20921 case THROW_EXPR:
20922 RETURN (build_throw
20923 (input_location, RECUR (TREE_OPERAND (t, 0))));
20925 case CONSTRUCTOR:
20927 vec<constructor_elt, va_gc> *n;
20928 constructor_elt *ce;
20929 unsigned HOST_WIDE_INT idx;
20930 bool process_index_p;
20931 int newlen;
20932 bool need_copy_p = false;
20933 tree r;
20935 tsubst_flags_t tcomplain = complain;
20936 if (COMPOUND_LITERAL_P (t))
20937 tcomplain |= tf_tst_ok;
20938 tree type = tsubst (TREE_TYPE (t), args, tcomplain, in_decl);
20939 if (type == error_mark_node)
20940 RETURN (error_mark_node);
20942 /* We do not want to process the index of aggregate
20943 initializers as they are identifier nodes which will be
20944 looked up by digest_init. */
20945 process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
20947 if (null_member_pointer_value_p (t))
20949 gcc_assert (same_type_p (type, TREE_TYPE (t)));
20950 RETURN (t);
20953 n = vec_safe_copy (CONSTRUCTOR_ELTS (t));
20954 newlen = vec_safe_length (n);
20955 FOR_EACH_VEC_SAFE_ELT (n, idx, ce)
20957 if (ce->index && process_index_p
20958 /* An identifier index is looked up in the type
20959 being initialized, not the current scope. */
20960 && TREE_CODE (ce->index) != IDENTIFIER_NODE)
20961 ce->index = RECUR (ce->index);
20963 if (PACK_EXPANSION_P (ce->value))
20965 /* Substitute into the pack expansion. */
20966 ce->value = tsubst_pack_expansion (ce->value, args, complain,
20967 in_decl);
20969 if (ce->value == error_mark_node
20970 || PACK_EXPANSION_P (ce->value))
20972 else if (TREE_VEC_LENGTH (ce->value) == 1)
20973 /* Just move the argument into place. */
20974 ce->value = TREE_VEC_ELT (ce->value, 0);
20975 else
20977 /* Update the length of the final CONSTRUCTOR
20978 arguments vector, and note that we will need to
20979 copy.*/
20980 newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
20981 need_copy_p = true;
20984 else
20985 ce->value = RECUR (ce->value);
20988 if (need_copy_p)
20990 vec<constructor_elt, va_gc> *old_n = n;
20992 vec_alloc (n, newlen);
20993 FOR_EACH_VEC_ELT (*old_n, idx, ce)
20995 if (TREE_CODE (ce->value) == TREE_VEC)
20997 int i, len = TREE_VEC_LENGTH (ce->value);
20998 for (i = 0; i < len; ++i)
20999 CONSTRUCTOR_APPEND_ELT (n, 0,
21000 TREE_VEC_ELT (ce->value, i));
21002 else
21003 CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
21007 r = build_constructor (init_list_type_node, n);
21008 CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
21009 CONSTRUCTOR_IS_DESIGNATED_INIT (r)
21010 = CONSTRUCTOR_IS_DESIGNATED_INIT (t);
21012 if (TREE_HAS_CONSTRUCTOR (t))
21014 fcl_t cl = fcl_functional;
21015 if (CONSTRUCTOR_C99_COMPOUND_LITERAL (t))
21016 cl = fcl_c99;
21017 RETURN (finish_compound_literal (type, r, complain, cl));
21020 TREE_TYPE (r) = type;
21021 RETURN (r);
21024 case TYPEID_EXPR:
21026 tree operand_0 = TREE_OPERAND (t, 0);
21027 if (TYPE_P (operand_0))
21029 operand_0 = tsubst (operand_0, args, complain, in_decl);
21030 RETURN (get_typeid (operand_0, complain));
21032 else
21034 operand_0 = RECUR (operand_0);
21035 RETURN (build_typeid (operand_0, complain));
21039 case FUNCTION_DECL:
21040 case PARM_DECL:
21041 case VAR_DECL:
21042 if (!args)
21043 RETURN (t);
21044 tree r;
21045 if (VAR_OR_FUNCTION_DECL_P (t)
21046 && DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
21047 r = tsubst_decl (t, args, complain);
21048 else if (VAR_OR_FUNCTION_DECL_P (t) && DECL_LOCAL_DECL_P (t))
21050 /* Local specialization will usually have been created when
21051 we instantiated the DECL_EXPR_DECL. */
21052 r = retrieve_local_specialization (t);
21053 if (!r)
21055 /* We're in a generic lambda referencing a local extern
21056 from an outer block-scope of a non-template. */
21057 gcc_checking_assert (LAMBDA_FUNCTION_P (current_function_decl));
21058 r = t;
21061 else if (local_variable_p (t)
21062 && ((r = retrieve_local_specialization (t))
21063 || TREE_CODE (t) == PARM_DECL
21064 || uses_template_parms (DECL_CONTEXT (t))))
21066 if (r == NULL_TREE && TREE_CODE (t) == PARM_DECL)
21068 /* We get here for a use of 'this' in an NSDMI. */
21069 if (DECL_NAME (t) == this_identifier && current_class_ptr)
21070 RETURN (current_class_ptr);
21072 /* This can happen for a parameter name used later in a function
21073 declaration (such as in a late-specified return type). Just
21074 make a dummy decl, since it's only used for its type. */
21075 gcc_assert (cp_unevaluated_operand);
21076 r = tsubst_decl (t, args, complain);
21077 /* Give it the template pattern as its context; its true context
21078 hasn't been instantiated yet and this is good enough for
21079 mangling. */
21080 DECL_CONTEXT (r) = DECL_CONTEXT (t);
21082 else if (r == NULL_TREE)
21084 /* First try name lookup to find the instantiation. */
21085 r = lookup_name (DECL_NAME (t));
21086 if (r)
21088 if (!VAR_P (r))
21090 /* During error-recovery we may find a non-variable,
21091 even an OVERLOAD: just bail out and avoid ICEs and
21092 duplicate diagnostics (c++/62207). */
21093 gcc_assert (seen_error ());
21094 RETURN (error_mark_node);
21096 if (!is_capture_proxy (r))
21098 /* Make sure the one we found is the one we want. */
21099 tree ctx = enclosing_instantiation_of (DECL_CONTEXT (t));
21100 if (ctx != DECL_CONTEXT (r))
21101 r = NULL_TREE;
21105 if (r)
21106 /* OK */;
21107 else
21109 /* This can happen for a variable used in a
21110 late-specified return type of a local lambda, or for a
21111 local static or constant. Building a new VAR_DECL
21112 should be OK in all those cases. */
21113 r = tsubst_decl (t, args, complain);
21114 if (local_specializations)
21115 /* Avoid infinite recursion (79640). */
21116 register_local_specialization (r, t);
21117 if (decl_maybe_constant_var_p (r))
21119 /* We can't call cp_finish_decl, so handle the
21120 initializer by hand. */
21121 tree init = tsubst_init (DECL_INITIAL (t), r, args,
21122 complain, in_decl);
21123 if (!processing_template_decl)
21124 init = maybe_constant_init (init);
21125 if (processing_template_decl
21126 ? potential_constant_expression (init)
21127 : reduced_constant_expression_p (init))
21128 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
21129 = TREE_CONSTANT (r) = true;
21130 DECL_INITIAL (r) = init;
21131 if (tree auto_node = type_uses_auto (TREE_TYPE (r)))
21132 TREE_TYPE (r)
21133 = do_auto_deduction (TREE_TYPE (r), init, auto_node,
21134 complain, adc_variable_type);
21136 gcc_assert (cp_unevaluated_operand
21137 || processing_contract_condition
21138 || TREE_STATIC (r)
21139 || decl_constant_var_p (r)
21140 || seen_error ());
21141 if (!processing_template_decl
21142 && !TREE_STATIC (r))
21143 r = process_outer_var_ref (r, complain);
21145 /* Remember this for subsequent uses. */
21146 if (local_specializations)
21147 register_local_specialization (r, t);
21149 if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
21150 r = argument_pack_select_arg (r);
21152 else
21153 r = t;
21154 if (!mark_used (r, complain))
21155 RETURN (error_mark_node);
21157 if (!no_name_lookup_flag
21158 && (TREE_CODE (t) == PARM_DECL || TREE_CODE (t) == VAR_DECL))
21160 /* ??? We're doing a subset of finish_id_expression here. */
21161 if (tree wrap = maybe_get_tls_wrapper_call (r))
21162 /* Replace an evaluated use of the thread_local variable with
21163 a call to its wrapper. */
21164 r = wrap;
21165 else if (outer_automatic_var_p (r))
21166 r = process_outer_var_ref (r, complain);
21168 if (!TYPE_REF_P (TREE_TYPE (t)))
21169 /* If the original type was a reference, we'll be wrapped in
21170 the appropriate INDIRECT_REF. */
21171 r = convert_from_reference (r);
21173 RETURN (r);
21175 case CONST_DECL:
21177 tree enum_type;
21178 tree v;
21180 if (DECL_TEMPLATE_PARM_P (t))
21181 RETURN (RECUR (DECL_INITIAL (t)));
21182 if (!uses_template_parms (DECL_CONTEXT (t)))
21183 RETURN (t);
21185 /* Unfortunately, we cannot just call lookup_name here.
21186 Consider:
21188 template <int I> int f() {
21189 enum E { a = I };
21190 struct S { void g() { E e = a; } };
21193 When we instantiate f<7>::S::g(), say, lookup_name is not
21194 clever enough to find f<7>::a. */
21195 enum_type
21196 = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
21197 /*entering_scope=*/0);
21199 for (v = TYPE_VALUES (enum_type);
21200 v != NULL_TREE;
21201 v = TREE_CHAIN (v))
21202 if (TREE_PURPOSE (v) == DECL_NAME (t))
21203 RETURN (TREE_VALUE (v));
21205 /* We didn't find the name. That should never happen; if
21206 name-lookup found it during preliminary parsing, we
21207 should find it again here during instantiation. */
21208 gcc_unreachable ();
21209 RETURN (t);
21212 case FIELD_DECL:
21213 if (DECL_CONTEXT (t))
21215 tree ctx;
21217 ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
21218 /*entering_scope=*/1);
21219 if (ctx != DECL_CONTEXT (t))
21221 tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
21222 if (!r)
21224 if (complain & tf_error)
21225 error ("using invalid field %qD", t);
21226 RETURN (error_mark_node);
21228 RETURN (r);
21231 RETURN (t);
21233 case NAMESPACE_DECL:
21234 case OVERLOAD:
21235 RETURN (t);
21237 case TEMPLATE_DECL:
21238 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
21239 RETURN (tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
21240 args, complain, in_decl));
21241 else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
21242 RETURN (tsubst (t, args, complain, in_decl));
21243 else if (DECL_CLASS_SCOPE_P (t)
21244 && uses_template_parms (DECL_CONTEXT (t)))
21246 /* Template template argument like the following example need
21247 special treatment:
21249 template <template <class> class TT> struct C {};
21250 template <class T> struct D {
21251 template <class U> struct E {};
21252 C<E> c; // #1
21254 D<int> d; // #2
21256 We are processing the template argument `E' in #1 for
21257 the template instantiation #2. Originally, `E' is a
21258 TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT. Now we
21259 have to substitute this with one having context `D<int>'. */
21261 tree context = tsubst_aggr_type (DECL_CONTEXT (t), args, complain,
21262 in_decl, /*entering_scope=*/true);
21263 RETURN (lookup_field (context, DECL_NAME(t), 0, false));
21265 else
21266 /* Ordinary template template argument. */
21267 RETURN (t);
21269 case TEMPLATE_PARM_INDEX:
21270 case TYPE_DECL:
21271 RETURN (tsubst (t, args, complain, in_decl));
21273 case CLEANUP_POINT_EXPR:
21274 /* We shouldn't have built any of these during initial template
21275 generation. Instead, they should be built during instantiation
21276 in response to the saved STMT_IS_FULL_EXPR_P setting. */
21277 gcc_unreachable ();
21279 case OFFSET_REF:
21281 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
21282 tree op0 = RECUR (TREE_OPERAND (t, 0));
21283 tree op1 = RECUR (TREE_OPERAND (t, 1));
21284 r = build2 (OFFSET_REF, type, op0, op1);
21285 PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
21286 if (!mark_used (TREE_OPERAND (r, 1), complain)
21287 && !(complain & tf_error))
21288 RETURN (error_mark_node);
21289 RETURN (r);
21292 case EXPR_PACK_EXPANSION:
21293 error ("invalid use of pack expansion expression");
21294 RETURN (error_mark_node);
21296 case NONTYPE_ARGUMENT_PACK:
21297 error ("use %<...%> to expand argument pack");
21298 RETURN (error_mark_node);
21300 case VOID_CST:
21301 gcc_checking_assert (t == void_node && VOID_TYPE_P (TREE_TYPE (t)));
21302 RETURN (t);
21304 case INTEGER_CST:
21305 case REAL_CST:
21306 case COMPLEX_CST:
21307 case VECTOR_CST:
21309 /* Instantiate any typedefs in the type. */
21310 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
21311 r = fold_convert (type, t);
21312 gcc_assert (TREE_CODE (r) == TREE_CODE (t));
21313 RETURN (r);
21316 case STRING_CST:
21318 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
21319 r = t;
21320 if (type != TREE_TYPE (t))
21322 r = copy_node (t);
21323 TREE_TYPE (r) = type;
21325 RETURN (r);
21328 case PTRMEM_CST:
21329 /* These can sometimes show up in a partial instantiation, but never
21330 involve template parms. */
21331 gcc_assert (!uses_template_parms (t));
21332 RETURN (t);
21334 case UNARY_LEFT_FOLD_EXPR:
21335 RETURN (tsubst_unary_left_fold (t, args, complain, in_decl));
21336 case UNARY_RIGHT_FOLD_EXPR:
21337 RETURN (tsubst_unary_right_fold (t, args, complain, in_decl));
21338 case BINARY_LEFT_FOLD_EXPR:
21339 RETURN (tsubst_binary_left_fold (t, args, complain, in_decl));
21340 case BINARY_RIGHT_FOLD_EXPR:
21341 RETURN (tsubst_binary_right_fold (t, args, complain, in_decl));
21342 case PREDICT_EXPR:
21343 RETURN (t);
21345 case DEBUG_BEGIN_STMT:
21346 /* ??? There's no point in copying it for now, but maybe some
21347 day it will contain more information, such as a pointer back
21348 to the containing function, inlined copy or so. */
21349 RETURN (t);
21351 case CO_YIELD_EXPR:
21352 RETURN (finish_co_yield_expr (input_location,
21353 RECUR (TREE_OPERAND (t, 0))));
21355 case CO_AWAIT_EXPR:
21356 RETURN (finish_co_await_expr (input_location,
21357 RECUR (TREE_OPERAND (t, 0))));
21359 case VA_ARG_EXPR:
21361 tree op0 = RECUR (TREE_OPERAND (t, 0));
21362 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
21363 RETURN (build_x_va_arg (EXPR_LOCATION (t), op0, type));
21366 case OFFSETOF_EXPR:
21368 tree object_ptr
21369 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl);
21370 RETURN (finish_offsetof (object_ptr,
21371 RECUR (TREE_OPERAND (t, 0)),
21372 EXPR_LOCATION (t)));
21375 case ADDRESSOF_EXPR:
21376 RETURN (cp_build_addressof (EXPR_LOCATION (t),
21377 RECUR (TREE_OPERAND (t, 0)), complain));
21379 case TRAIT_EXPR:
21381 tree type1 = TRAIT_EXPR_TYPE1 (t);
21382 if (TYPE_P (type1))
21383 type1 = tsubst (type1, args, complain, in_decl);
21384 else
21385 type1 = tsubst_expr (type1, args, complain, in_decl);
21386 tree type2 = tsubst (TRAIT_EXPR_TYPE2 (t), args,
21387 complain, in_decl);
21388 RETURN (finish_trait_expr (TRAIT_EXPR_LOCATION (t),
21389 TRAIT_EXPR_KIND (t), type1, type2));
21392 case STMT_EXPR:
21394 tree old_stmt_expr = cur_stmt_expr;
21395 tree stmt_expr = begin_stmt_expr ();
21397 cur_stmt_expr = stmt_expr;
21398 tsubst_stmt (STMT_EXPR_STMT (t), args, complain, in_decl);
21399 stmt_expr = finish_stmt_expr (stmt_expr, false);
21400 cur_stmt_expr = old_stmt_expr;
21402 /* If the resulting list of expression statement is empty,
21403 fold it further into void_node. */
21404 if (empty_expr_stmt_p (stmt_expr))
21405 stmt_expr = void_node;
21407 RETURN (stmt_expr);
21410 case LAMBDA_EXPR:
21412 if (complain & tf_partial)
21414 /* We don't have a full set of template arguments yet; don't touch
21415 the lambda at all. */
21416 gcc_assert (processing_template_decl);
21417 return t;
21419 tree r = tsubst_lambda_expr (t, args, complain, in_decl);
21421 RETURN (build_lambda_object (r));
21424 case TRANSACTION_EXPR:
21425 gcc_checking_assert (!TRANSACTION_EXPR_IS_STMT (t));
21426 RETURN (tsubst_stmt (t, args, complain, in_decl));
21428 case PAREN_EXPR:
21429 if (REF_PARENTHESIZED_P (t))
21430 RETURN (finish_parenthesized_expr (RECUR (TREE_OPERAND (t, 0))));
21431 else
21432 /* Recreate the PAREN_EXPR from __builtin_assoc_barrier. */
21434 tree op0 = RECUR (TREE_OPERAND (t, 0));
21435 RETURN (build1_loc (input_location, PAREN_EXPR,
21436 TREE_TYPE (op0), op0));
21439 case VEC_PERM_EXPR:
21441 tree op0 = RECUR (TREE_OPERAND (t, 0));
21442 tree op1 = RECUR (TREE_OPERAND (t, 1));
21443 tree op2 = RECUR (TREE_OPERAND (t, 2));
21444 RETURN (build_x_vec_perm_expr (input_location, op0, op1, op2,
21445 complain));
21448 case REQUIRES_EXPR:
21450 tree r = tsubst_requires_expr (t, args, tf_none, in_decl);
21451 RETURN (r);
21454 case RANGE_EXPR:
21455 /* No need to substitute further, a RANGE_EXPR will always be built
21456 with constant operands. */
21457 RETURN (t);
21459 case NON_LVALUE_EXPR:
21460 case VIEW_CONVERT_EXPR:
21462 tree op = RECUR (TREE_OPERAND (t, 0));
21464 if (location_wrapper_p (t))
21465 /* We need to do this here as well as in tsubst_copy so we get the
21466 other tsubst_copy_and_build semantics for a PARM_DECL operand. */
21467 RETURN (maybe_wrap_with_location (op, EXPR_LOCATION (t)));
21469 gcc_checking_assert (TREE_CODE (t) == VIEW_CONVERT_EXPR);
21470 if (REF_PARENTHESIZED_P (t))
21471 /* force_paren_expr can also create a VIEW_CONVERT_EXPR. */
21472 RETURN (finish_parenthesized_expr (op));
21474 /* Otherwise, we're dealing with a wrapper to make a C++20 template
21475 parameter object const. */
21476 if (TREE_TYPE (op) == NULL_TREE
21477 || !CP_TYPE_CONST_P (TREE_TYPE (op)))
21479 /* The template argument is not const, presumably because
21480 it is still dependent, and so not the const template parm
21481 object. */
21482 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
21483 if (TREE_CODE (op) == CONSTRUCTOR
21484 || TREE_CODE (op) == IMPLICIT_CONV_EXPR)
21486 /* Don't add a wrapper to these. */
21487 op = copy_node (op);
21488 TREE_TYPE (op) = type;
21490 else
21491 /* Do add a wrapper otherwise (in particular, if op is
21492 another TEMPLATE_PARM_INDEX). */
21493 op = build1 (VIEW_CONVERT_EXPR, type, op);
21495 RETURN (op);
21498 case ANNOTATE_EXPR:
21499 op1 = RECUR (TREE_OPERAND (t, 0));
21500 RETURN (build3_loc (EXPR_LOCATION (t), ANNOTATE_EXPR,
21501 TREE_TYPE (op1), op1,
21502 RECUR (TREE_OPERAND (t, 1)),
21503 RECUR (TREE_OPERAND (t, 2))));
21505 default:
21506 /* Handle Objective-C++ constructs, if appropriate. */
21507 if (tree subst = objcp_tsubst_expr (t, args, complain, in_decl))
21508 RETURN (subst);
21510 /* We shouldn't get here, but keep going if !flag_checking. */
21511 if (flag_checking)
21512 gcc_unreachable ();
21513 RETURN (t);
21516 #undef RECUR
21517 #undef RETURN
21518 out:
21519 input_location = save_loc;
21520 return retval;
21523 /* Verify that the instantiated ARGS are valid. For type arguments,
21524 make sure that the type's linkage is ok. For non-type arguments,
21525 make sure they are constants if they are integral or enumerations.
21526 Emit an error under control of COMPLAIN, and return TRUE on error. */
21528 static bool
21529 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
21531 if (dependent_template_arg_p (t))
21532 return false;
21533 if (ARGUMENT_PACK_P (t))
21535 tree vec = ARGUMENT_PACK_ARGS (t);
21536 int len = TREE_VEC_LENGTH (vec);
21537 bool result = false;
21538 int i;
21540 for (i = 0; i < len; ++i)
21541 if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
21542 result = true;
21543 return result;
21545 else if (TYPE_P (t))
21547 /* [basic.link]: A name with no linkage (notably, the name
21548 of a class or enumeration declared in a local scope)
21549 shall not be used to declare an entity with linkage.
21550 This implies that names with no linkage cannot be used as
21551 template arguments
21553 DR 757 relaxes this restriction for C++0x. */
21554 tree nt = (cxx_dialect > cxx98 ? NULL_TREE
21555 : no_linkage_check (t, /*relaxed_p=*/false));
21557 if (nt)
21559 /* DR 488 makes use of a type with no linkage cause
21560 type deduction to fail. */
21561 if (complain & tf_error)
21563 if (TYPE_UNNAMED_P (nt))
21564 error ("%qT is/uses unnamed type", t);
21565 else
21566 error ("template argument for %qD uses local type %qT",
21567 tmpl, t);
21569 return true;
21571 /* In order to avoid all sorts of complications, we do not
21572 allow variably-modified types as template arguments. */
21573 else if (variably_modified_type_p (t, NULL_TREE))
21575 if (complain & tf_error)
21576 error ("%qT is a variably modified type", t);
21577 return true;
21580 /* Class template and alias template arguments should be OK. */
21581 else if (DECL_TYPE_TEMPLATE_P (t))
21583 /* A non-type argument of integral or enumerated type must be a
21584 constant. */
21585 else if (TREE_TYPE (t)
21586 && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
21587 && !REFERENCE_REF_P (t)
21588 && !TREE_CONSTANT (t))
21590 if (complain & tf_error)
21591 error ("integral expression %qE is not constant", t);
21592 return true;
21594 return false;
21597 static bool
21598 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
21600 int ix, len = DECL_NTPARMS (tmpl);
21601 bool result = false;
21603 for (ix = 0; ix != len; ix++)
21605 if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
21606 result = true;
21608 if (result && (complain & tf_error))
21609 error (" trying to instantiate %qD", tmpl);
21610 return result;
21613 /* Call mark_used on each entity within the non-type template arguments in
21614 ARGS for an instantiation of TMPL, to ensure that each such entity is
21615 considered odr-used (and therefore marked for instantiation) regardless of
21616 whether the specialization was first formed in a template context (which
21617 inhibits mark_used).
21619 This function assumes push_to_top_level has been called beforehand. */
21621 static void
21622 mark_template_arguments_used (tree tmpl, tree args)
21624 /* It suffices to do this only when instantiating a primary template. */
21625 if (TREE_CODE (tmpl) != TEMPLATE_DECL || !PRIMARY_TEMPLATE_P (tmpl))
21626 return;
21628 /* We already marked outer arguments when specializing the context. */
21629 args = INNERMOST_TEMPLATE_ARGS (args);
21631 for (tree arg : tree_vec_range (args))
21633 /* A (pointer/reference to) function or variable NTTP argument. */
21634 if (TREE_CODE (arg) == ADDR_EXPR
21635 || TREE_CODE (arg) == INDIRECT_REF)
21637 while (TREE_CODE (arg) == ADDR_EXPR
21638 || REFERENCE_REF_P (arg)
21639 || CONVERT_EXPR_P (arg))
21640 arg = TREE_OPERAND (arg, 0);
21641 if (VAR_OR_FUNCTION_DECL_P (arg))
21643 /* Pass tf_none to avoid duplicate diagnostics: if this call
21644 fails then an earlier call to mark_used for this argument
21645 must have also failed and emitted a diagnostic. */
21646 bool ok = mark_used (arg, tf_none);
21647 gcc_checking_assert (ok || seen_error ());
21650 /* A class NTTP argument. */
21651 else if (VAR_P (arg)
21652 && DECL_NTTP_OBJECT_P (arg))
21654 auto mark_used_r = [](tree *tp, int *, void *) {
21655 if (VAR_OR_FUNCTION_DECL_P (*tp))
21657 bool ok = mark_used (*tp, tf_none);
21658 gcc_checking_assert (ok || seen_error ());
21660 return NULL_TREE;
21662 cp_walk_tree_without_duplicates (&DECL_INITIAL (arg),
21663 mark_used_r, nullptr);
21668 /* We're out of SFINAE context now, so generate diagnostics for the access
21669 errors we saw earlier when instantiating D from TMPL and ARGS. */
21671 static void
21672 recheck_decl_substitution (tree d, tree tmpl, tree args)
21674 tree pattern = DECL_TEMPLATE_RESULT (tmpl);
21675 tree type = TREE_TYPE (pattern);
21676 location_t loc = input_location;
21678 push_access_scope (d);
21679 push_deferring_access_checks (dk_no_deferred);
21680 input_location = DECL_SOURCE_LOCATION (pattern);
21681 tsubst (type, args, tf_warning_or_error, d);
21682 input_location = loc;
21683 pop_deferring_access_checks ();
21684 pop_access_scope (d);
21687 /* Instantiate the indicated variable, function, or alias template TMPL with
21688 the template arguments in TARG_PTR. */
21690 tree
21691 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
21693 auto_timevar tv (TV_TEMPLATE_INST);
21695 tree targ_ptr = orig_args;
21696 tree fndecl;
21697 tree gen_tmpl;
21698 bool access_ok = true;
21700 if (tmpl == error_mark_node)
21701 return error_mark_node;
21703 /* The other flags are not relevant anymore here, especially tf_partial
21704 shouldn't be set. For instance, we may be called while doing a partial
21705 substitution of a template variable, but the type of the variable
21706 template may be auto, in which case we will call do_auto_deduction
21707 in mark_used (which clears tf_partial) and the auto must be properly
21708 reduced at that time for the deduction to work. */
21709 complain &= tf_warning_or_error;
21711 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
21713 if (modules_p ())
21714 lazy_load_pendings (tmpl);
21716 /* If this function is a clone, handle it specially. */
21717 if (DECL_CLONED_FUNCTION_P (tmpl))
21719 tree spec;
21720 tree clone;
21722 /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
21723 DECL_CLONED_FUNCTION. */
21724 spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
21725 targ_ptr, complain);
21726 if (spec == error_mark_node)
21727 return error_mark_node;
21729 /* Look for the clone. */
21730 FOR_EACH_CLONE (clone, spec)
21731 if (DECL_NAME (clone) == DECL_NAME (tmpl))
21732 return clone;
21733 /* We should always have found the clone by now. */
21734 gcc_unreachable ();
21735 return NULL_TREE;
21738 if (targ_ptr == error_mark_node)
21739 return error_mark_node;
21741 /* Check to see if we already have this specialization. */
21742 gen_tmpl = most_general_template (tmpl);
21743 if (TMPL_ARGS_DEPTH (targ_ptr)
21744 < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)))
21745 /* targ_ptr only has the innermost template args, so add the outer ones
21746 from tmpl, which could be either a partial instantiation or gen_tmpl (in
21747 the case of a non-dependent call within a template definition). */
21748 targ_ptr = (add_outermost_template_args
21749 (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (tmpl)),
21750 targ_ptr));
21752 hashval_t hash = spec_hasher::hash (gen_tmpl, targ_ptr);
21753 tree spec = retrieve_specialization (gen_tmpl, targ_ptr, hash);
21755 gcc_checking_assert (tmpl == gen_tmpl
21756 || ((fndecl
21757 = retrieve_specialization (tmpl, orig_args, 0))
21758 == spec)
21759 || fndecl == NULL_TREE);
21761 if (spec != NULL_TREE)
21763 if (FNDECL_HAS_ACCESS_ERRORS (spec))
21765 if (complain & tf_error)
21766 recheck_decl_substitution (spec, gen_tmpl, targ_ptr);
21767 return error_mark_node;
21769 return spec;
21772 if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
21773 complain))
21774 return error_mark_node;
21776 /* We are building a FUNCTION_DECL, during which the access of its
21777 parameters and return types have to be checked. However this
21778 FUNCTION_DECL which is the desired context for access checking
21779 is not built yet. We solve this chicken-and-egg problem by
21780 deferring all checks until we have the FUNCTION_DECL. */
21781 push_deferring_access_checks (dk_deferred);
21783 /* Instantiation of the function happens in the context of the function
21784 template, not the context of the overload resolution we're doing. */
21785 push_to_top_level ();
21786 /* If there are dependent arguments, e.g. because we're doing partial
21787 ordering, make sure processing_template_decl stays set. */
21788 if (uses_template_parms (targ_ptr))
21789 ++processing_template_decl;
21790 if (DECL_CLASS_SCOPE_P (gen_tmpl))
21792 tree ctx;
21793 if (!uses_template_parms (DECL_CONTEXT (tmpl)))
21794 /* If the context of the partially instantiated template is
21795 already non-dependent, then we might as well use it. */
21796 ctx = DECL_CONTEXT (tmpl);
21797 else
21798 ctx = tsubst_aggr_type (DECL_CONTEXT (gen_tmpl), targ_ptr,
21799 complain, gen_tmpl, true);
21800 push_nested_class (ctx);
21803 tree pattern = DECL_TEMPLATE_RESULT (gen_tmpl);
21805 tree partial_ti = NULL_TREE;
21806 fndecl = NULL_TREE;
21807 if (VAR_P (pattern))
21809 /* We need to determine if we're using a partial or explicit
21810 specialization now, because the type of the variable could be
21811 different. */
21812 tree tid = build2 (TEMPLATE_ID_EXPR, NULL_TREE, tmpl, targ_ptr);
21813 partial_ti = most_specialized_partial_spec (tid, complain);
21814 if (partial_ti == error_mark_node)
21815 pattern = error_mark_node;
21816 else if (partial_ti)
21818 tree partial_tmpl = TI_TEMPLATE (partial_ti);
21819 tree partial_args = TI_ARGS (partial_ti);
21820 tree partial_pat = DECL_TEMPLATE_RESULT (partial_tmpl);
21821 fndecl = tsubst_decl (partial_pat, partial_args, complain,
21822 /*use_spec_table=*/false);
21826 /* Substitute template parameters to obtain the specialization. */
21827 if (fndecl == NULL_TREE)
21828 fndecl = tsubst_decl (pattern, targ_ptr, complain, /*use_spec_table=*/false);
21829 if (DECL_CLASS_SCOPE_P (gen_tmpl))
21830 pop_nested_class ();
21831 pop_from_top_level ();
21833 if (fndecl == error_mark_node)
21835 pop_deferring_access_checks ();
21836 return error_mark_node;
21839 /* The DECL_TI_TEMPLATE should always be the immediate parent
21840 template, not the most general template. */
21841 DECL_TI_TEMPLATE (fndecl) = tmpl;
21842 DECL_TI_ARGS (fndecl) = targ_ptr;
21843 if (VAR_P (pattern))
21844 /* Now that we we've formed this variable template specialization,
21845 remember the result of most_specialized_partial_spec for it. */
21846 TI_PARTIAL_INFO (DECL_TEMPLATE_INFO (fndecl)) = partial_ti;
21848 fndecl = register_specialization (fndecl, gen_tmpl, targ_ptr, false, hash);
21849 if (fndecl == error_mark_node)
21850 return error_mark_node;
21852 set_instantiating_module (fndecl);
21854 /* Now we know the specialization, compute access previously
21855 deferred. Do no access control for inheriting constructors,
21856 as we already checked access for the inherited constructor. */
21857 if (!(flag_new_inheriting_ctors
21858 && DECL_INHERITED_CTOR (fndecl)))
21860 push_access_scope (fndecl);
21861 if (!perform_deferred_access_checks (complain))
21862 access_ok = false;
21863 pop_access_scope (fndecl);
21865 pop_deferring_access_checks ();
21867 /* If we've just instantiated the main entry point for a function,
21868 instantiate all the alternate entry points as well. We do this
21869 by cloning the instantiation of the main entry point, not by
21870 instantiating the template clones. */
21871 if (tree chain = DECL_CHAIN (gen_tmpl))
21872 if (DECL_P (chain) && DECL_CLONED_FUNCTION_P (chain))
21873 clone_cdtor (fndecl, /*update_methods=*/false);
21875 if (!access_ok)
21877 if (!(complain & tf_error))
21879 /* Remember to reinstantiate when we're out of SFINAE so the user
21880 can see the errors. */
21881 FNDECL_HAS_ACCESS_ERRORS (fndecl) = true;
21883 return error_mark_node;
21886 return fndecl;
21889 /* Instantiate the alias template TMPL with ARGS. Also push a template
21890 instantiation level, which instantiate_template doesn't do because
21891 functions and variables have sufficient context established by the
21892 callers. */
21894 static tree
21895 instantiate_alias_template (tree tmpl, tree args, tsubst_flags_t complain)
21897 if (tmpl == error_mark_node || args == error_mark_node)
21898 return error_mark_node;
21900 args = coerce_template_parms (DECL_TEMPLATE_PARMS (tmpl),
21901 args, tmpl, complain);
21902 if (args == error_mark_node)
21903 return error_mark_node;
21905 /* FIXME check for satisfaction in check_instantiated_args. */
21906 if (!constraints_satisfied_p (tmpl, args))
21908 if (complain & tf_error)
21910 auto_diagnostic_group d;
21911 error ("template constraint failure for %qD", tmpl);
21912 diagnose_constraints (input_location, tmpl, args);
21914 return error_mark_node;
21917 if (!push_tinst_level (tmpl, args))
21918 return error_mark_node;
21919 tree r = instantiate_template (tmpl, args, complain);
21920 pop_tinst_level ();
21922 if (tree d = dependent_alias_template_spec_p (TREE_TYPE (r), nt_opaque))
21924 /* An alias template specialization can be dependent
21925 even if its underlying type is not. */
21926 TYPE_DEPENDENT_P (d) = true;
21927 TYPE_DEPENDENT_P_VALID (d) = true;
21928 /* Sometimes a dependent alias spec is equivalent to its expansion,
21929 sometimes not. So always use structural_comptypes. */
21930 SET_TYPE_STRUCTURAL_EQUALITY (d);
21933 return r;
21936 /* PARM is a template parameter pack for FN. Returns true iff
21937 PARM is used in a deducible way in the argument list of FN. */
21939 static bool
21940 pack_deducible_p (tree parm, tree fn)
21942 tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
21943 for (; t; t = TREE_CHAIN (t))
21945 tree type = TREE_VALUE (t);
21946 tree packs;
21947 if (!PACK_EXPANSION_P (type))
21948 continue;
21949 for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
21950 packs; packs = TREE_CHAIN (packs))
21951 if (template_args_equal (TREE_VALUE (packs), parm))
21953 /* The template parameter pack is used in a function parameter
21954 pack. If this is the end of the parameter list, the
21955 template parameter pack is deducible. */
21956 if (TREE_CHAIN (t) == void_list_node)
21957 return true;
21958 else
21959 /* Otherwise, not. Well, it could be deduced from
21960 a non-pack parameter, but doing so would end up with
21961 a deduction mismatch, so don't bother. */
21962 return false;
21965 /* The template parameter pack isn't used in any function parameter
21966 packs, but it might be used deeper, e.g. tuple<Args...>. */
21967 return true;
21970 /* Subroutine of fn_type_unification: check non-dependent parms for
21971 convertibility. */
21973 static int
21974 check_non_deducible_conversions (tree parms, const tree *args, unsigned nargs,
21975 tree fn, unification_kind_t strict, int flags,
21976 struct conversion **convs, bool explain_p,
21977 bool noninst_only_p)
21979 /* Non-constructor methods need to leave a conversion for 'this', which
21980 isn't included in nargs here. */
21981 unsigned offset = (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
21982 && !DECL_CONSTRUCTOR_P (fn));
21984 for (unsigned ia = 0;
21985 parms && parms != void_list_node && ia < nargs; )
21987 tree parm = TREE_VALUE (parms);
21989 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
21990 && (!TREE_CHAIN (parms)
21991 || TREE_CHAIN (parms) == void_list_node))
21992 /* For a function parameter pack that occurs at the end of the
21993 parameter-declaration-list, the type A of each remaining
21994 argument of the call is compared with the type P of the
21995 declarator-id of the function parameter pack. */
21996 break;
21998 parms = TREE_CHAIN (parms);
22000 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
22001 /* For a function parameter pack that does not occur at the
22002 end of the parameter-declaration-list, the type of the
22003 parameter pack is a non-deduced context. */
22004 continue;
22006 if (!uses_template_parms (parm))
22008 tree arg = args[ia];
22009 conversion **conv_p = convs ? &convs[ia+offset] : NULL;
22010 int lflags = conv_flags (ia, nargs, fn, arg, flags);
22012 if (check_non_deducible_conversion (parm, arg, strict, lflags,
22013 conv_p, explain_p, noninst_only_p))
22014 return 1;
22017 ++ia;
22020 return 0;
22023 /* The FN is a TEMPLATE_DECL for a function. ARGS is an array with
22024 NARGS elements of the arguments that are being used when calling
22025 it. TARGS is a vector into which the deduced template arguments
22026 are placed.
22028 Returns either a FUNCTION_DECL for the matching specialization of FN or
22029 NULL_TREE if no suitable specialization can be found. If EXPLAIN_P is
22030 true, diagnostics will be printed to explain why it failed.
22032 If FN is a conversion operator, or we are trying to produce a specific
22033 specialization, RETURN_TYPE is the return type desired.
22035 The EXPLICIT_TARGS are explicit template arguments provided via a
22036 template-id.
22038 The parameter STRICT is one of:
22040 DEDUCE_CALL:
22041 We are deducing arguments for a function call, as in
22042 [temp.deduct.call]. If RETURN_TYPE is non-null, we are
22043 deducing arguments for a call to the result of a conversion
22044 function template, as in [over.call.object].
22046 DEDUCE_CONV:
22047 We are deducing arguments for a conversion function, as in
22048 [temp.deduct.conv].
22050 DEDUCE_EXACT:
22051 We are deducing arguments when doing an explicit instantiation
22052 as in [temp.explicit], when determining an explicit specialization
22053 as in [temp.expl.spec], or when taking the address of a function
22054 template, as in [temp.deduct.funcaddr]. */
22056 tree
22057 fn_type_unification (tree fn,
22058 tree explicit_targs,
22059 tree targs,
22060 const tree *args,
22061 unsigned int nargs,
22062 tree return_type,
22063 unification_kind_t strict,
22064 int flags,
22065 struct conversion **convs,
22066 bool explain_p,
22067 bool decltype_p)
22069 tree parms;
22070 tree fntype;
22071 tree decl = NULL_TREE;
22072 tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
22073 bool ok;
22074 static int deduction_depth;
22075 /* type_unification_real will pass back any access checks from default
22076 template argument substitution. */
22077 vec<deferred_access_check, va_gc> *checks = NULL;
22078 /* We don't have all the template args yet. */
22079 bool incomplete = true;
22081 tree orig_fn = fn;
22082 if (flag_new_inheriting_ctors)
22083 fn = strip_inheriting_ctors (fn);
22085 tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
22086 tree r = error_mark_node;
22088 tree full_targs = targs;
22089 if (TMPL_ARGS_DEPTH (targs)
22090 < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (fn)))
22091 full_targs = (add_outermost_template_args
22092 (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (fn)),
22093 targs));
22095 if (decltype_p)
22096 complain |= tf_decltype;
22098 /* In C++0x, it's possible to have a function template whose type depends
22099 on itself recursively. This is most obvious with decltype, but can also
22100 occur with enumeration scope (c++/48969). So we need to catch infinite
22101 recursion and reject the substitution at deduction time; this function
22102 will return error_mark_node for any repeated substitution.
22104 This also catches excessive recursion such as when f<N> depends on
22105 f<N-1> across all integers, and returns error_mark_node for all the
22106 substitutions back up to the initial one.
22108 This is, of course, not reentrant. */
22109 if (excessive_deduction_depth)
22110 return error_mark_node;
22111 ++deduction_depth;
22113 gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
22115 fntype = TREE_TYPE (fn);
22116 if (explicit_targs)
22118 /* [temp.deduct]
22120 The specified template arguments must match the template
22121 parameters in kind (i.e., type, nontype, template), and there
22122 must not be more arguments than there are parameters;
22123 otherwise type deduction fails.
22125 Nontype arguments must match the types of the corresponding
22126 nontype template parameters, or must be convertible to the
22127 types of the corresponding nontype parameters as specified in
22128 _temp.arg.nontype_, otherwise type deduction fails.
22130 All references in the function type of the function template
22131 to the corresponding template parameters are replaced by the
22132 specified template argument values. If a substitution in a
22133 template parameter or in the function type of the function
22134 template results in an invalid type, type deduction fails. */
22135 int i, len = TREE_VEC_LENGTH (tparms);
22136 location_t loc = input_location;
22137 incomplete = false;
22139 if (explicit_targs == error_mark_node)
22140 goto fail;
22142 if (TMPL_ARGS_DEPTH (explicit_targs)
22143 < TMPL_ARGS_DEPTH (full_targs))
22144 explicit_targs = add_outermost_template_args (full_targs,
22145 explicit_targs);
22147 /* Adjust any explicit template arguments before entering the
22148 substitution context. */
22149 explicit_targs
22150 = (coerce_template_parms (tparms, explicit_targs, fn,
22151 complain|tf_partial,
22152 /*require_all_args=*/false));
22153 if (explicit_targs == error_mark_node)
22154 goto fail;
22156 /* Substitute the explicit args into the function type. This is
22157 necessary so that, for instance, explicitly declared function
22158 arguments can match null pointed constants. If we were given
22159 an incomplete set of explicit args, we must not do semantic
22160 processing during substitution as we could create partial
22161 instantiations. */
22162 for (i = 0; i < len; i++)
22164 tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
22165 bool parameter_pack = false;
22166 tree targ = TREE_VEC_ELT (explicit_targs, i);
22168 /* Dig out the actual parm. */
22169 if (TREE_CODE (parm) == TYPE_DECL
22170 || TREE_CODE (parm) == TEMPLATE_DECL)
22172 parm = TREE_TYPE (parm);
22173 parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
22175 else if (TREE_CODE (parm) == PARM_DECL)
22177 parm = DECL_INITIAL (parm);
22178 parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
22181 if (targ == NULL_TREE)
22182 /* No explicit argument for this template parameter. */
22183 incomplete = true;
22184 else if (parameter_pack && pack_deducible_p (parm, fn))
22186 /* Mark the argument pack as "incomplete". We could
22187 still deduce more arguments during unification.
22188 We remove this mark in type_unification_real. */
22189 ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
22190 ARGUMENT_PACK_EXPLICIT_ARGS (targ)
22191 = ARGUMENT_PACK_ARGS (targ);
22193 /* We have some incomplete argument packs. */
22194 incomplete = true;
22198 if (incomplete)
22200 if (!push_tinst_level (fn, explicit_targs))
22202 excessive_deduction_depth = true;
22203 goto fail;
22205 ++processing_template_decl;
22206 input_location = DECL_SOURCE_LOCATION (fn);
22207 /* Ignore any access checks; we'll see them again in
22208 instantiate_template and they might have the wrong
22209 access path at this point. */
22210 push_deferring_access_checks (dk_deferred);
22211 tsubst_flags_t ecomplain = complain | tf_partial | tf_fndecl_type;
22212 fntype = tsubst (TREE_TYPE (fn), explicit_targs, ecomplain, NULL_TREE);
22213 pop_deferring_access_checks ();
22214 input_location = loc;
22215 --processing_template_decl;
22216 pop_tinst_level ();
22218 if (fntype == error_mark_node)
22219 goto fail;
22222 /* Place the explicitly specified arguments in TARGS. */
22223 explicit_targs = INNERMOST_TEMPLATE_ARGS (explicit_targs);
22224 for (i = NUM_TMPL_ARGS (explicit_targs); i--;)
22225 TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (explicit_targs, i);
22226 if (!incomplete && CHECKING_P
22227 && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
22228 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
22229 (targs, NUM_TMPL_ARGS (explicit_targs));
22232 if (return_type && strict != DEDUCE_CALL)
22234 tree *new_args = XALLOCAVEC (tree, nargs + 1);
22235 new_args[0] = return_type;
22236 memcpy (new_args + 1, args, nargs * sizeof (tree));
22237 args = new_args;
22238 ++nargs;
22241 if (!incomplete)
22242 goto deduced;
22244 /* Never do unification on the 'this' parameter. */
22245 parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
22247 if (return_type && strict == DEDUCE_CALL)
22249 /* We're deducing for a call to the result of a template conversion
22250 function. The parms we really want are in return_type. */
22251 if (INDIRECT_TYPE_P (return_type))
22252 return_type = TREE_TYPE (return_type);
22253 parms = TYPE_ARG_TYPES (return_type);
22255 else if (return_type)
22257 parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
22260 /* We allow incomplete unification without an error message here
22261 because the standard doesn't seem to explicitly prohibit it. Our
22262 callers must be ready to deal with unification failures in any
22263 event. */
22265 /* If we aren't explaining yet, push tinst context so we can see where
22266 any errors (e.g. from class instantiations triggered by instantiation
22267 of default template arguments) come from. If we are explaining, this
22268 context is redundant. */
22269 if (!explain_p && !push_tinst_level (fn, targs))
22271 excessive_deduction_depth = true;
22272 goto fail;
22275 ok = !type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
22276 full_targs, parms, args, nargs, /*subr=*/0,
22277 strict, &checks, explain_p);
22278 if (!explain_p)
22279 pop_tinst_level ();
22280 if (!ok)
22281 goto fail;
22283 /* Now that we have bindings for all of the template arguments,
22284 ensure that the arguments deduced for the template template
22285 parameters have compatible template parameter lists. We cannot
22286 check this property before we have deduced all template
22287 arguments, because the template parameter types of a template
22288 template parameter might depend on prior template parameters
22289 deduced after the template template parameter. The following
22290 ill-formed example illustrates this issue:
22292 template<typename T, template<T> class C> void f(C<5>, T);
22294 template<int N> struct X {};
22296 void g() {
22297 f(X<5>(), 5l); // error: template argument deduction fails
22300 The template parameter list of 'C' depends on the template type
22301 parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
22302 'long'. Thus, we can't check that 'C' cannot bind to 'X' at the
22303 time that we deduce 'C'. */
22304 if (!template_template_parm_bindings_ok_p
22305 (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
22307 unify_inconsistent_template_template_parameters (explain_p);
22308 goto fail;
22311 deduced:
22313 /* As a refinement of CWG2369, check first and foremost non-dependent
22314 conversions that we know are not going to induce template instantiation
22315 (PR99599). */
22316 if (strict == DEDUCE_CALL
22317 && incomplete
22318 && check_non_deducible_conversions (parms, args, nargs, fn, strict, flags,
22319 convs, explain_p,
22320 /*noninst_only_p=*/true))
22321 goto fail;
22323 /* CWG2369: Check satisfaction before non-deducible conversions. */
22324 if (!constraints_satisfied_p (fn, targs))
22326 if (explain_p)
22327 diagnose_constraints (DECL_SOURCE_LOCATION (fn), fn, targs);
22328 goto fail;
22331 /* DR 1391: All parameters have args, now check non-dependent parms for
22332 convertibility. We don't do this if all args were explicitly specified,
22333 as the standard says that we substitute explicit args immediately. */
22334 if (incomplete
22335 && check_non_deducible_conversions (parms, args, nargs, fn, strict, flags,
22336 convs, explain_p,
22337 /*noninst_only_p=*/false))
22338 goto fail;
22340 /* All is well so far. Now, check:
22342 [temp.deduct]
22344 When all template arguments have been deduced, all uses of
22345 template parameters in nondeduced contexts are replaced with
22346 the corresponding deduced argument values. If the
22347 substitution results in an invalid type, as described above,
22348 type deduction fails. */
22349 if (!push_tinst_level (fn, targs))
22351 excessive_deduction_depth = true;
22352 goto fail;
22355 /* Also collect access checks from the instantiation. */
22356 reopen_deferring_access_checks (checks);
22358 decl = instantiate_template (fn, targs, complain);
22360 checks = get_deferred_access_checks ();
22361 pop_deferring_access_checks ();
22363 pop_tinst_level ();
22365 if (decl == error_mark_node)
22366 goto fail;
22368 /* Now perform any access checks encountered during substitution. */
22369 push_access_scope (decl);
22370 ok = perform_access_checks (checks, complain);
22371 pop_access_scope (decl);
22372 if (!ok)
22373 goto fail;
22375 /* If we're looking for an exact match, check that what we got
22376 is indeed an exact match. It might not be if some template
22377 parameters are used in non-deduced contexts. But don't check
22378 for an exact match if we have dependent template arguments;
22379 in that case we're doing partial ordering, and we already know
22380 that we have two candidates that will provide the actual type. */
22381 if (strict == DEDUCE_EXACT && !any_dependent_template_arguments_p (targs))
22383 tree substed = TREE_TYPE (decl);
22384 unsigned int i;
22386 tree sarg
22387 = skip_artificial_parms_for (decl, TYPE_ARG_TYPES (substed));
22388 if (return_type)
22389 sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
22390 for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
22391 if (!same_type_p (args[i], TREE_VALUE (sarg)))
22393 unify_type_mismatch (explain_p, args[i],
22394 TREE_VALUE (sarg));
22395 goto fail;
22397 if ((i < nargs || sarg)
22398 /* add_candidates uses DEDUCE_EXACT for x.operator foo(), but args
22399 doesn't contain the trailing void, and conv fns are always (). */
22400 && !DECL_CONV_FN_P (decl))
22402 unsigned nsargs = i + list_length (sarg);
22403 unify_arity (explain_p, nargs, nsargs);
22404 goto fail;
22408 /* After doing deduction with the inherited constructor, actually return an
22409 instantiation of the inheriting constructor. */
22410 if (orig_fn != fn)
22411 decl = instantiate_template (orig_fn, targs, complain);
22413 r = decl;
22415 fail:
22416 --deduction_depth;
22417 if (excessive_deduction_depth)
22419 if (deduction_depth == 0)
22420 /* Reset once we're all the way out. */
22421 excessive_deduction_depth = false;
22424 return r;
22427 /* Returns true iff PARM is a forwarding reference in the context of
22428 template argument deduction for TMPL. */
22430 static bool
22431 forwarding_reference_p (tree parm, tree tmpl)
22433 /* [temp.deduct.call], "A forwarding reference is an rvalue reference to a
22434 cv-unqualified template parameter ..." */
22435 if (TYPE_REF_P (parm)
22436 && TYPE_REF_IS_RVALUE (parm)
22437 && TREE_CODE (TREE_TYPE (parm)) == TEMPLATE_TYPE_PARM
22438 && cp_type_quals (TREE_TYPE (parm)) == TYPE_UNQUALIFIED)
22440 parm = TREE_TYPE (parm);
22441 /* [temp.deduct.call], "... that does not represent a template parameter
22442 of a class template (during class template argument deduction)." */
22443 if (tmpl
22444 && deduction_guide_p (tmpl)
22445 && DECL_ARTIFICIAL (tmpl))
22447 /* Since the template parameters of a synthesized guide consist of
22448 the template parameters of the class template followed by those of
22449 the constructor (if any), we can tell if PARM represents a template
22450 parameter of the class template by comparing its index with the
22451 arity of the class template. */
22452 tree ctmpl = CLASSTYPE_TI_TEMPLATE (TREE_TYPE (TREE_TYPE (tmpl)));
22453 if (TEMPLATE_TYPE_IDX (parm)
22454 < TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (ctmpl)))
22455 return false;
22457 return true;
22459 return false;
22462 /* Adjust types before performing type deduction, as described in
22463 [temp.deduct.call] and [temp.deduct.conv]. The rules in these two
22464 sections are symmetric. PARM is the type of a function parameter
22465 or the return type of the conversion function. ARG is the type of
22466 the argument passed to the call, or the type of the value
22467 initialized with the result of the conversion function.
22468 ARG_EXPR is the original argument expression, which may be null. */
22470 static int
22471 maybe_adjust_types_for_deduction (tree tparms,
22472 unification_kind_t strict,
22473 tree* parm,
22474 tree* arg,
22475 tree arg_expr)
22477 int result = 0;
22479 switch (strict)
22481 case DEDUCE_CALL:
22482 break;
22484 case DEDUCE_CONV:
22485 /* [temp.deduct.conv] First remove a reference type on parm.
22486 DRs 322 & 976 affected this. */
22487 if (TYPE_REF_P (*parm))
22488 *parm = TREE_TYPE (*parm);
22490 /* Swap PARM and ARG throughout the remainder of this
22491 function; the handling is precisely symmetric since PARM
22492 will initialize ARG rather than vice versa. */
22493 std::swap (parm, arg);
22495 break;
22497 case DEDUCE_EXACT:
22498 /* Core issue #873: Do the DR606 thing (see below) for these cases,
22499 too, but here handle it by stripping the reference from PARM
22500 rather than by adding it to ARG. */
22501 if (forwarding_reference_p (*parm, TPARMS_PRIMARY_TEMPLATE (tparms))
22502 && TYPE_REF_P (*arg)
22503 && !TYPE_REF_IS_RVALUE (*arg))
22504 *parm = TREE_TYPE (*parm);
22505 /* Nothing else to do in this case. */
22506 return 0;
22508 default:
22509 gcc_unreachable ();
22512 if (!TYPE_REF_P (*parm))
22514 /* [temp.deduct.call]
22516 If P is not a reference type:
22518 --If A is an array type, the pointer type produced by the
22519 array-to-pointer standard conversion (_conv.array_) is
22520 used in place of A for type deduction; otherwise,
22522 --If A is a function type, the pointer type produced by
22523 the function-to-pointer standard conversion
22524 (_conv.func_) is used in place of A for type deduction;
22525 otherwise,
22527 --If A is a cv-qualified type, the top level
22528 cv-qualifiers of A's type are ignored for type
22529 deduction. */
22530 if (TREE_CODE (*arg) == ARRAY_TYPE)
22531 *arg = build_pointer_type (TREE_TYPE (*arg));
22532 else if (TREE_CODE (*arg) == FUNCTION_TYPE)
22533 *arg = build_pointer_type (*arg);
22534 else
22535 *arg = TYPE_MAIN_VARIANT (*arg);
22538 /* [temp.deduct.call], "If P is a forwarding reference and the argument is
22539 an lvalue, the type 'lvalue reference to A' is used in place of A for
22540 type deduction." */
22541 if (forwarding_reference_p (*parm, TPARMS_PRIMARY_TEMPLATE (tparms))
22542 && (arg_expr ? lvalue_p (arg_expr)
22543 /* try_one_overload doesn't provide an arg_expr, but
22544 functions are always lvalues. */
22545 : TREE_CODE (*arg) == FUNCTION_TYPE))
22546 *arg = build_reference_type (*arg);
22548 /* [temp.deduct.call]
22550 If P is a cv-qualified type, the top level cv-qualifiers
22551 of P's type are ignored for type deduction. If P is a
22552 reference type, the type referred to by P is used for
22553 type deduction. */
22554 *parm = TYPE_MAIN_VARIANT (*parm);
22555 if (TYPE_REF_P (*parm))
22557 *parm = TREE_TYPE (*parm);
22558 result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
22561 return result;
22564 /* Return true if computing a conversion from FROM to TO might induce template
22565 instantiation. Conversely, if this predicate returns false then computing
22566 the conversion definitely won't induce template instantiation. */
22568 static bool
22569 conversion_may_instantiate_p (tree to, tree from)
22571 to = non_reference (to);
22572 from = non_reference (from);
22574 bool ptr_conv_p = false;
22575 if (TYPE_PTR_P (to)
22576 && TYPE_PTR_P (from))
22578 to = TREE_TYPE (to);
22579 from = TREE_TYPE (from);
22580 ptr_conv_p = true;
22583 /* If one of the types is a not-yet-instantiated class template
22584 specialization, then computing the conversion might instantiate
22585 it in order to inspect bases, conversion functions and/or
22586 converting constructors. */
22587 if ((CLASS_TYPE_P (to)
22588 && !COMPLETE_TYPE_P (to)
22589 && CLASSTYPE_TEMPLATE_INSTANTIATION (to))
22590 || (CLASS_TYPE_P (from)
22591 && !COMPLETE_TYPE_P (from)
22592 && CLASSTYPE_TEMPLATE_INSTANTIATION (from)))
22593 return true;
22595 /* Converting from one pointer type to another, or between
22596 reference-related types, always yields a standard conversion. */
22597 if (ptr_conv_p || reference_related_p (to, from))
22598 return false;
22600 /* Converting to a non-aggregate class type will consider its
22601 user-declared constructors, which might induce instantiation. */
22602 if (CLASS_TYPE_P (to)
22603 && CLASSTYPE_NON_AGGREGATE (to))
22604 return true;
22606 /* Similarly, converting from a class type will consider its conversion
22607 functions. */
22608 if (CLASS_TYPE_P (from)
22609 && TYPE_HAS_CONVERSION (from))
22610 return true;
22612 /* Otherwise, computing this conversion definitely won't induce
22613 template instantiation. */
22614 return false;
22617 /* Subroutine of fn_type_unification. PARM is a function parameter of a
22618 template which doesn't contain any deducible template parameters; check if
22619 ARG is a suitable match for it. STRICT, FLAGS and EXPLAIN_P are as in
22620 unify_one_argument. */
22622 static int
22623 check_non_deducible_conversion (tree parm, tree arg, unification_kind_t strict,
22624 int flags, struct conversion **conv_p,
22625 bool explain_p, bool noninst_only_p)
22627 tree type;
22629 if (!TYPE_P (arg))
22630 type = TREE_TYPE (arg);
22631 else
22632 type = arg;
22634 if (same_type_p (parm, type))
22635 return unify_success (explain_p);
22637 tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
22638 if (strict == DEDUCE_CONV)
22640 if (can_convert_arg (type, parm, NULL_TREE, flags, complain))
22641 return unify_success (explain_p);
22643 else if (strict == DEDUCE_CALL)
22645 if (conv_p && *conv_p)
22647 /* This conversion was already computed earlier (when
22648 computing only non-instantiating conversions). */
22649 gcc_checking_assert (!noninst_only_p);
22650 return unify_success (explain_p);
22653 if (noninst_only_p
22654 && conversion_may_instantiate_p (parm, type))
22655 return unify_success (explain_p);
22657 bool ok = false;
22658 tree conv_arg = TYPE_P (arg) ? NULL_TREE : arg;
22659 if (conv_p)
22660 /* Avoid recalculating this in add_function_candidate. */
22661 ok = (*conv_p
22662 = good_conversion (parm, type, conv_arg, flags, complain));
22663 else
22664 ok = can_convert_arg (parm, type, conv_arg, flags, complain);
22665 if (ok)
22666 return unify_success (explain_p);
22669 if (strict == DEDUCE_EXACT)
22670 return unify_type_mismatch (explain_p, parm, arg);
22671 else
22672 return unify_arg_conversion (explain_p, parm, type, arg);
22675 static bool uses_deducible_template_parms (tree type);
22677 /* Returns true iff the expression EXPR is one from which a template
22678 argument can be deduced. In other words, if it's an undecorated
22679 use of a template non-type parameter. */
22681 static bool
22682 deducible_expression (tree expr)
22684 /* Strip implicit conversions and implicit INDIRECT_REFs. */
22685 while (CONVERT_EXPR_P (expr)
22686 || TREE_CODE (expr) == VIEW_CONVERT_EXPR
22687 || REFERENCE_REF_P (expr))
22688 expr = TREE_OPERAND (expr, 0);
22689 return (TREE_CODE (expr) == TEMPLATE_PARM_INDEX);
22692 /* Returns true iff the array domain DOMAIN uses a template parameter in a
22693 deducible way; that is, if it has a max value of <PARM> - 1. */
22695 static bool
22696 deducible_array_bound (tree domain)
22698 if (domain == NULL_TREE)
22699 return false;
22701 tree max = TYPE_MAX_VALUE (domain);
22702 if (TREE_CODE (max) != MINUS_EXPR)
22703 return false;
22705 return deducible_expression (TREE_OPERAND (max, 0));
22708 /* Returns true iff the template arguments ARGS use a template parameter
22709 in a deducible way. */
22711 static bool
22712 deducible_template_args (tree args)
22714 for (tree elt : tree_vec_range (args))
22716 bool deducible;
22717 if (ARGUMENT_PACK_P (elt))
22718 deducible = deducible_template_args (ARGUMENT_PACK_ARGS (elt));
22719 else
22721 if (PACK_EXPANSION_P (elt))
22722 elt = PACK_EXPANSION_PATTERN (elt);
22723 if (TREE_CODE (elt) == TEMPLATE_TEMPLATE_PARM)
22724 deducible = true;
22725 else if (TYPE_P (elt))
22726 deducible = uses_deducible_template_parms (elt);
22727 else
22728 deducible = deducible_expression (elt);
22730 if (deducible)
22731 return true;
22733 return false;
22736 /* Returns true iff TYPE contains any deducible references to template
22737 parameters, as per 14.8.2.5. */
22739 static bool
22740 uses_deducible_template_parms (tree type)
22742 if (PACK_EXPANSION_P (type))
22743 type = PACK_EXPANSION_PATTERN (type);
22745 /* T
22746 cv-list T
22747 TT<T>
22748 TT<i>
22749 TT<> */
22750 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
22751 || TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
22752 return true;
22754 /* T*
22756 T&& */
22757 if (INDIRECT_TYPE_P (type))
22758 return uses_deducible_template_parms (TREE_TYPE (type));
22760 /* T[integer-constant ]
22761 type [i] */
22762 if (TREE_CODE (type) == ARRAY_TYPE)
22763 return (uses_deducible_template_parms (TREE_TYPE (type))
22764 || deducible_array_bound (TYPE_DOMAIN (type)));
22766 /* T type ::*
22767 type T::*
22768 T T::*
22769 T (type ::*)()
22770 type (T::*)()
22771 type (type ::*)(T)
22772 type (T::*)(T)
22773 T (type ::*)(T)
22774 T (T::*)()
22775 T (T::*)(T) */
22776 if (TYPE_PTRMEM_P (type))
22777 return (uses_deducible_template_parms (TYPE_PTRMEM_CLASS_TYPE (type))
22778 || (uses_deducible_template_parms
22779 (TYPE_PTRMEM_POINTED_TO_TYPE (type))));
22781 /* template-name <T> (where template-name refers to a class template)
22782 template-name <i> (where template-name refers to a class template) */
22783 if (CLASS_TYPE_P (type)
22784 && CLASSTYPE_TEMPLATE_INFO (type)
22785 && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type)))
22786 return deducible_template_args (INNERMOST_TEMPLATE_ARGS
22787 (CLASSTYPE_TI_ARGS (type)));
22789 /* type (T)
22791 T(T) */
22792 if (FUNC_OR_METHOD_TYPE_P (type))
22794 if (uses_deducible_template_parms (TREE_TYPE (type)))
22795 return true;
22796 tree parm = TYPE_ARG_TYPES (type);
22797 if (TREE_CODE (type) == METHOD_TYPE)
22798 parm = TREE_CHAIN (parm);
22799 for (; parm; parm = TREE_CHAIN (parm))
22800 if (uses_deducible_template_parms (TREE_VALUE (parm)))
22801 return true;
22802 if (flag_noexcept_type
22803 && TYPE_RAISES_EXCEPTIONS (type)
22804 && TREE_PURPOSE (TYPE_RAISES_EXCEPTIONS (type))
22805 && deducible_expression (TREE_PURPOSE (TYPE_RAISES_EXCEPTIONS (type))))
22806 return true;
22809 return false;
22812 /* Subroutine of type_unification_real and unify_pack_expansion to
22813 handle unification of a single P/A pair. Parameters are as
22814 for those functions. */
22816 static int
22817 unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
22818 int subr, unification_kind_t strict,
22819 bool explain_p)
22821 tree arg_expr = NULL_TREE;
22822 int arg_strict;
22824 if (arg == error_mark_node || parm == error_mark_node)
22825 return unify_invalid (explain_p);
22826 if (arg == unknown_type_node)
22827 /* We can't deduce anything from this, but we might get all the
22828 template args from other function args. */
22829 return unify_success (explain_p);
22831 /* Implicit conversions (Clause 4) will be performed on a function
22832 argument to convert it to the type of the corresponding function
22833 parameter if the parameter type contains no template-parameters that
22834 participate in template argument deduction. */
22835 if (strict != DEDUCE_EXACT
22836 && TYPE_P (parm) && !uses_deducible_template_parms (parm))
22837 /* For function parameters with no deducible template parameters,
22838 just return. We'll check non-dependent conversions later. */
22839 return unify_success (explain_p);
22841 switch (strict)
22843 case DEDUCE_CALL:
22844 arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
22845 | UNIFY_ALLOW_MORE_CV_QUAL
22846 | UNIFY_ALLOW_DERIVED);
22847 break;
22849 case DEDUCE_CONV:
22850 arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
22851 break;
22853 case DEDUCE_EXACT:
22854 arg_strict = UNIFY_ALLOW_NONE;
22855 break;
22857 default:
22858 gcc_unreachable ();
22861 /* We only do these transformations if this is the top-level
22862 parameter_type_list in a call or declaration matching; in other
22863 situations (nested function declarators, template argument lists) we
22864 won't be comparing a type to an expression, and we don't do any type
22865 adjustments. */
22866 if (!subr)
22868 if (!TYPE_P (arg))
22870 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
22871 if (type_unknown_p (arg))
22873 /* [temp.deduct.type] A template-argument can be
22874 deduced from a pointer to function or pointer
22875 to member function argument if the set of
22876 overloaded functions does not contain function
22877 templates and at most one of a set of
22878 overloaded functions provides a unique
22879 match. */
22880 resolve_overloaded_unification (tparms, targs, parm,
22881 arg, strict,
22882 arg_strict, explain_p);
22883 /* If a unique match was not found, this is a
22884 non-deduced context, so we still succeed. */
22885 return unify_success (explain_p);
22888 arg_expr = arg;
22889 arg = unlowered_expr_type (arg);
22890 if (arg == error_mark_node)
22891 return unify_invalid (explain_p);
22894 arg_strict |= maybe_adjust_types_for_deduction (tparms, strict,
22895 &parm, &arg, arg_expr);
22897 else
22898 if ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
22899 != (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL))
22900 return unify_template_argument_mismatch (explain_p, parm, arg);
22902 /* For deduction from an init-list we need the actual list. */
22903 if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
22904 arg = arg_expr;
22905 return unify (tparms, targs, parm, arg, arg_strict, explain_p);
22908 /* for_each_template_parm callback that always returns 0. */
22910 static int
22911 zero_r (tree, void *)
22913 return 0;
22916 /* for_each_template_parm any_fn callback to handle deduction of a template
22917 type argument from the type of an array bound. */
22919 static int
22920 array_deduction_r (tree t, void *data)
22922 tree_pair_p d = (tree_pair_p)data;
22923 tree &tparms = d->purpose;
22924 tree &targs = d->value;
22926 if (TREE_CODE (t) == ARRAY_TYPE)
22927 if (tree dom = TYPE_DOMAIN (t))
22928 if (tree max = TYPE_MAX_VALUE (dom))
22930 if (TREE_CODE (max) == MINUS_EXPR)
22931 max = TREE_OPERAND (max, 0);
22932 if (TREE_CODE (max) == TEMPLATE_PARM_INDEX)
22933 unify (tparms, targs, TREE_TYPE (max), size_type_node,
22934 UNIFY_ALLOW_NONE, /*explain*/false);
22937 /* Keep walking. */
22938 return 0;
22941 /* Try to deduce any not-yet-deduced template type arguments from the type of
22942 an array bound. This is handled separately from unify because 14.8.2.5 says
22943 "The type of a type parameter is only deduced from an array bound if it is
22944 not otherwise deduced." */
22946 static void
22947 try_array_deduction (tree tparms, tree targs, tree parm)
22949 tree_pair_s data = { tparms, targs };
22950 hash_set<tree> visited;
22951 for_each_template_parm (parm, zero_r, &data, &visited,
22952 /*nondeduced*/false, array_deduction_r);
22955 /* Most parms like fn_type_unification.
22957 If SUBR is 1, we're being called recursively (to unify the
22958 arguments of a function or method parameter of a function
22959 template).
22961 CHECKS is a pointer to a vector of access checks encountered while
22962 substituting default template arguments. */
22964 static int
22965 type_unification_real (tree tparms,
22966 tree full_targs,
22967 tree xparms,
22968 const tree *xargs,
22969 unsigned int xnargs,
22970 int subr,
22971 unification_kind_t strict,
22972 vec<deferred_access_check, va_gc> **checks,
22973 bool explain_p)
22975 tree parm, arg;
22976 int i;
22977 int ntparms = TREE_VEC_LENGTH (tparms);
22978 int saw_undeduced = 0;
22979 tree parms;
22980 const tree *args;
22981 unsigned int nargs;
22982 unsigned int ia;
22984 gcc_assert (TREE_CODE (tparms) == TREE_VEC);
22985 gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
22986 gcc_assert (ntparms > 0);
22988 tree targs = INNERMOST_TEMPLATE_ARGS (full_targs);
22990 /* Reset the number of non-defaulted template arguments contained
22991 in TARGS. */
22992 NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
22994 again:
22995 parms = xparms;
22996 args = xargs;
22997 nargs = xnargs;
22999 /* Only fn_type_unification cares about terminal void. */
23000 if (nargs && args[nargs-1] == void_type_node)
23001 --nargs;
23003 ia = 0;
23004 while (parms && parms != void_list_node
23005 && ia < nargs)
23007 parm = TREE_VALUE (parms);
23009 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
23010 && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
23011 /* For a function parameter pack that occurs at the end of the
23012 parameter-declaration-list, the type A of each remaining
23013 argument of the call is compared with the type P of the
23014 declarator-id of the function parameter pack. */
23015 break;
23017 parms = TREE_CHAIN (parms);
23019 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
23020 /* For a function parameter pack that does not occur at the
23021 end of the parameter-declaration-list, the type of the
23022 parameter pack is a non-deduced context. */
23023 continue;
23025 arg = args[ia];
23026 ++ia;
23028 if (unify_one_argument (tparms, full_targs, parm, arg, subr, strict,
23029 explain_p))
23030 return 1;
23033 if (parms
23034 && parms != void_list_node
23035 && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
23037 /* Unify the remaining arguments with the pack expansion type. */
23038 tree argvec;
23039 tree parmvec = make_tree_vec (1);
23041 /* Allocate a TREE_VEC and copy in all of the arguments */
23042 argvec = make_tree_vec (nargs - ia);
23043 for (i = 0; ia < nargs; ++ia, ++i)
23044 TREE_VEC_ELT (argvec, i) = args[ia];
23046 /* Copy the parameter into parmvec. */
23047 TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
23048 if (unify_pack_expansion (tparms, full_targs, parmvec, argvec, strict,
23049 /*subr=*/subr, explain_p))
23050 return 1;
23052 /* Advance to the end of the list of parameters. */
23053 parms = TREE_CHAIN (parms);
23056 /* Fail if we've reached the end of the parm list, and more args
23057 are present, and the parm list isn't variadic. */
23058 if (ia < nargs && parms == void_list_node)
23059 return unify_too_many_arguments (explain_p, nargs, ia);
23060 /* Fail if parms are left and they don't have default values and
23061 they aren't all deduced as empty packs (c++/57397). This is
23062 consistent with sufficient_parms_p. */
23063 if (parms && parms != void_list_node
23064 && TREE_PURPOSE (parms) == NULL_TREE)
23066 unsigned int count = nargs;
23067 tree p = parms;
23068 bool type_pack_p;
23071 type_pack_p = TREE_CODE (TREE_VALUE (p)) == TYPE_PACK_EXPANSION;
23072 if (!type_pack_p)
23073 count++;
23074 p = TREE_CHAIN (p);
23076 while (p && p != void_list_node);
23077 if (count != nargs)
23078 return unify_too_few_arguments (explain_p, ia, count,
23079 type_pack_p);
23082 if (!subr)
23084 tsubst_flags_t complain = (explain_p
23085 ? tf_warning_or_error
23086 : tf_none);
23087 bool tried_array_deduction = (cxx_dialect < cxx17);
23089 for (i = 0; i < ntparms; i++)
23091 tree targ = TREE_VEC_ELT (targs, i);
23092 tree tparm = TREE_VEC_ELT (tparms, i);
23094 /* Clear the "incomplete" flags on all argument packs now so that
23095 substituting them into later default arguments works. */
23096 if (targ && ARGUMENT_PACK_P (targ))
23098 ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
23099 ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
23102 if (targ || tparm == error_mark_node)
23103 continue;
23104 tparm = TREE_VALUE (tparm);
23106 if (TREE_CODE (tparm) == TYPE_DECL
23107 && !tried_array_deduction)
23109 try_array_deduction (tparms, targs, xparms);
23110 tried_array_deduction = true;
23111 if (TREE_VEC_ELT (targs, i))
23112 continue;
23115 /* If this is an undeduced nontype parameter that depends on
23116 a type parameter, try another pass; its type may have been
23117 deduced from a later argument than the one from which
23118 this parameter can be deduced. */
23119 if (TREE_CODE (tparm) == PARM_DECL
23120 && !is_auto (TREE_TYPE (tparm))
23121 && uses_template_parms (TREE_TYPE (tparm))
23122 && saw_undeduced < 2)
23124 saw_undeduced = 1;
23125 continue;
23128 /* Core issue #226 (C++0x) [temp.deduct]:
23130 If a template argument has not been deduced, its
23131 default template argument, if any, is used.
23133 When we are in C++98 mode, TREE_PURPOSE will either
23134 be NULL_TREE or ERROR_MARK_NODE, so we do not need
23135 to explicitly check cxx_dialect here. */
23136 if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
23137 /* OK, there is a default argument. Wait until after the
23138 conversion check to do substitution. */
23139 continue;
23141 /* If the type parameter is a parameter pack, then it will
23142 be deduced to an empty parameter pack. */
23143 if (template_parameter_pack_p (tparm))
23145 tree arg;
23147 if (TREE_CODE (tparm) == PARM_DECL)
23149 arg = make_node (NONTYPE_ARGUMENT_PACK);
23150 TREE_CONSTANT (arg) = 1;
23152 else
23153 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
23155 ARGUMENT_PACK_ARGS (arg) = make_tree_vec (0);
23157 TREE_VEC_ELT (targs, i) = arg;
23158 continue;
23161 return unify_parameter_deduction_failure (explain_p, tparm);
23164 /* During partial ordering, we deduce dependent template args. */
23165 bool any_dependent_targs = false;
23167 /* Now substitute into the default template arguments. */
23168 for (i = 0; i < ntparms; i++)
23170 tree targ = TREE_VEC_ELT (targs, i);
23171 tree tparm = TREE_VEC_ELT (tparms, i);
23173 if (targ)
23175 if (!any_dependent_targs && dependent_template_arg_p (targ))
23176 any_dependent_targs = true;
23177 continue;
23179 if (tparm == error_mark_node)
23180 continue;
23182 tree parm = TREE_VALUE (tparm);
23183 tree arg = TREE_PURPOSE (tparm);
23184 reopen_deferring_access_checks (*checks);
23185 location_t save_loc = input_location;
23186 if (DECL_P (parm))
23187 input_location = DECL_SOURCE_LOCATION (parm);
23189 if (saw_undeduced == 1
23190 && TREE_CODE (parm) == PARM_DECL
23191 && !is_auto (TREE_TYPE (parm))
23192 && uses_template_parms (TREE_TYPE (parm)))
23194 /* The type of this non-type parameter depends on undeduced
23195 parameters. Don't try to use its default argument yet,
23196 since we might deduce an argument for it on the next pass,
23197 but do check whether the arguments we already have cause
23198 substitution failure, so that that happens before we try
23199 later default arguments (78489). */
23200 ++processing_template_decl;
23201 tree type = tsubst (TREE_TYPE (parm), full_targs, complain,
23202 NULL_TREE);
23203 --processing_template_decl;
23204 if (type == error_mark_node)
23205 arg = error_mark_node;
23206 else
23207 arg = NULL_TREE;
23209 else
23211 /* Even if the call is happening in template context, getting
23212 here means it's non-dependent, and a default argument is
23213 considered a separate definition under [temp.decls], so we can
23214 do this substitution without processing_template_decl. This
23215 is important if the default argument contains something that
23216 might be instantiation-dependent like access (87480). */
23217 processing_template_decl_sentinel s (!any_dependent_targs);
23218 tree substed = NULL_TREE;
23219 if (saw_undeduced == 1 && !any_dependent_targs)
23221 /* First instatiate in template context, in case we still
23222 depend on undeduced template parameters. */
23223 ++processing_template_decl;
23224 substed = tsubst_template_arg (arg, full_targs, complain,
23225 NULL_TREE);
23226 --processing_template_decl;
23227 if (substed != error_mark_node
23228 && !uses_template_parms (substed))
23229 /* We replaced all the tparms, substitute again out of
23230 template context. */
23231 substed = NULL_TREE;
23233 if (!substed)
23234 substed = tsubst_template_arg (arg, full_targs, complain,
23235 NULL_TREE);
23237 if (!uses_template_parms (substed))
23238 arg = convert_template_argument (parm, substed, full_targs,
23239 complain, i, NULL_TREE);
23240 else if (saw_undeduced == 1)
23241 arg = NULL_TREE;
23242 else if (!any_dependent_targs)
23243 arg = error_mark_node;
23246 input_location = save_loc;
23247 *checks = get_deferred_access_checks ();
23248 pop_deferring_access_checks ();
23250 if (arg == error_mark_node)
23251 return 1;
23252 else if (arg)
23254 TREE_VEC_ELT (targs, i) = arg;
23255 /* The position of the first default template argument,
23256 is also the number of non-defaulted arguments in TARGS.
23257 Record that. */
23258 if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
23259 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
23263 if (saw_undeduced++ == 1)
23264 goto again;
23267 if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
23268 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
23270 return unify_success (explain_p);
23273 /* Subroutine of type_unification_real. Args are like the variables
23274 at the call site. ARG is an overloaded function (or template-id);
23275 we try deducing template args from each of the overloads, and if
23276 only one succeeds, we go with that. Modifies TARGS and returns
23277 true on success. */
23279 static bool
23280 resolve_overloaded_unification (tree tparms,
23281 tree targs,
23282 tree parm,
23283 tree arg,
23284 unification_kind_t strict,
23285 int sub_strict,
23286 bool explain_p)
23288 tree tempargs = copy_node (targs);
23289 int good = 0;
23290 tree goodfn = NULL_TREE;
23291 bool addr_p;
23293 if (TREE_CODE (arg) == ADDR_EXPR)
23295 arg = TREE_OPERAND (arg, 0);
23296 addr_p = true;
23298 else
23299 addr_p = false;
23301 if (TREE_CODE (arg) == COMPONENT_REF)
23302 /* Handle `&x' where `x' is some static or non-static member
23303 function name. */
23304 arg = TREE_OPERAND (arg, 1);
23306 if (TREE_CODE (arg) == OFFSET_REF)
23307 arg = TREE_OPERAND (arg, 1);
23309 /* Strip baselink information. */
23310 if (BASELINK_P (arg))
23311 arg = BASELINK_FUNCTIONS (arg);
23313 if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
23315 /* If we got some explicit template args, we need to plug them into
23316 the affected templates before we try to unify, in case the
23317 explicit args will completely resolve the templates in question. */
23319 int ok = 0;
23320 tree expl_subargs = TREE_OPERAND (arg, 1);
23321 arg = TREE_OPERAND (arg, 0);
23323 for (lkp_iterator iter (arg); iter; ++iter)
23325 tree fn = *iter;
23326 tree subargs, elem;
23328 if (TREE_CODE (fn) != TEMPLATE_DECL)
23329 continue;
23331 subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
23332 expl_subargs, NULL_TREE, tf_none);
23333 if (subargs != error_mark_node
23334 && !any_dependent_template_arguments_p (subargs))
23336 fn = instantiate_template (fn, subargs, tf_none);
23337 if (!constraints_satisfied_p (fn))
23338 continue;
23339 if (undeduced_auto_decl (fn))
23341 /* Instantiate the function to deduce its return type. */
23342 ++function_depth;
23343 instantiate_decl (fn, /*defer*/false, /*class*/false);
23344 --function_depth;
23347 if (flag_noexcept_type)
23348 maybe_instantiate_noexcept (fn, tf_none);
23350 elem = TREE_TYPE (fn);
23351 if (try_one_overload (tparms, targs, tempargs, parm,
23352 elem, strict, sub_strict, addr_p, explain_p)
23353 && (!goodfn || !same_type_p (goodfn, elem)))
23355 goodfn = elem;
23356 ++good;
23359 else if (subargs)
23360 ++ok;
23362 /* If no templates (or more than one) are fully resolved by the
23363 explicit arguments, this template-id is a non-deduced context; it
23364 could still be OK if we deduce all template arguments for the
23365 enclosing call through other arguments. */
23366 if (good != 1)
23367 good = ok;
23369 else if (!OVL_P (arg))
23370 /* If ARG is, for example, "(0, &f)" then its type will be unknown
23371 -- but the deduction does not succeed because the expression is
23372 not just the function on its own. */
23373 return false;
23374 else
23375 for (lkp_iterator iter (arg); iter; ++iter)
23377 tree fn = *iter;
23378 if (try_one_overload (tparms, targs, tempargs, parm, TREE_TYPE (fn),
23379 strict, sub_strict, addr_p, explain_p)
23380 && (!goodfn || !decls_match (goodfn, fn)))
23382 goodfn = fn;
23383 ++good;
23387 /* [temp.deduct.type] A template-argument can be deduced from a pointer
23388 to function or pointer to member function argument if the set of
23389 overloaded functions does not contain function templates and at most
23390 one of a set of overloaded functions provides a unique match.
23392 So if we found multiple possibilities, we return success but don't
23393 deduce anything. */
23395 if (good == 1)
23397 int i = TREE_VEC_LENGTH (targs);
23398 for (; i--; )
23399 if (TREE_VEC_ELT (tempargs, i))
23401 tree old = TREE_VEC_ELT (targs, i);
23402 tree new_ = TREE_VEC_ELT (tempargs, i);
23403 if (new_ && old && ARGUMENT_PACK_P (old)
23404 && ARGUMENT_PACK_EXPLICIT_ARGS (old))
23405 /* Don't forget explicit template arguments in a pack. */
23406 ARGUMENT_PACK_EXPLICIT_ARGS (new_)
23407 = ARGUMENT_PACK_EXPLICIT_ARGS (old);
23408 TREE_VEC_ELT (targs, i) = new_;
23411 if (good)
23412 return true;
23414 return false;
23417 /* Core DR 115: In contexts where deduction is done and fails, or in
23418 contexts where deduction is not done, if a template argument list is
23419 specified and it, along with any default template arguments, identifies
23420 a single function template specialization, then the template-id is an
23421 lvalue for the function template specialization. */
23423 tree
23424 resolve_nondeduced_context (tree orig_expr, tsubst_flags_t complain)
23426 tree expr, offset, baselink;
23427 bool addr;
23429 if (!type_unknown_p (orig_expr))
23430 return orig_expr;
23432 expr = orig_expr;
23433 addr = false;
23434 offset = NULL_TREE;
23435 baselink = NULL_TREE;
23437 if (TREE_CODE (expr) == ADDR_EXPR)
23439 expr = TREE_OPERAND (expr, 0);
23440 addr = true;
23442 if (TREE_CODE (expr) == OFFSET_REF)
23444 offset = expr;
23445 expr = TREE_OPERAND (expr, 1);
23447 if (BASELINK_P (expr))
23449 baselink = expr;
23450 expr = BASELINK_FUNCTIONS (expr);
23453 if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
23455 int good = 0;
23456 tree goodfn = NULL_TREE;
23458 /* If we got some explicit template args, we need to plug them into
23459 the affected templates before we try to unify, in case the
23460 explicit args will completely resolve the templates in question. */
23462 tree expl_subargs = TREE_OPERAND (expr, 1);
23463 tree arg = TREE_OPERAND (expr, 0);
23464 tree badfn = NULL_TREE;
23465 tree badargs = NULL_TREE;
23467 for (lkp_iterator iter (arg); iter; ++iter)
23469 tree fn = *iter;
23470 tree subargs, elem;
23472 if (TREE_CODE (fn) != TEMPLATE_DECL)
23473 continue;
23475 subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
23476 expl_subargs, NULL_TREE, tf_none);
23477 if (subargs != error_mark_node
23478 && !any_dependent_template_arguments_p (subargs))
23480 elem = instantiate_template (fn, subargs, tf_none);
23481 if (elem == error_mark_node)
23483 badfn = fn;
23484 badargs = subargs;
23486 else if (elem && (!goodfn || !decls_match (goodfn, elem))
23487 && constraints_satisfied_p (elem))
23489 goodfn = elem;
23490 ++good;
23494 if (good == 1)
23496 mark_used (goodfn);
23497 expr = goodfn;
23498 if (baselink)
23499 expr = build_baselink (BASELINK_BINFO (baselink),
23500 BASELINK_ACCESS_BINFO (baselink),
23501 expr, BASELINK_OPTYPE (baselink));
23502 if (offset)
23504 tree base
23505 = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
23506 expr = build_offset_ref (base, expr, addr, complain);
23508 if (addr)
23509 expr = cp_build_addr_expr (expr, complain);
23510 return expr;
23512 else if (good == 0 && badargs && (complain & tf_error))
23513 /* There were no good options and at least one bad one, so let the
23514 user know what the problem is. */
23515 instantiate_template (badfn, badargs, complain);
23517 return orig_expr;
23520 /* As above, but error out if the expression remains overloaded. */
23522 tree
23523 resolve_nondeduced_context_or_error (tree exp, tsubst_flags_t complain)
23525 exp = resolve_nondeduced_context (exp, complain);
23526 if (type_unknown_p (exp))
23528 if (complain & tf_error)
23529 cxx_incomplete_type_error (exp, TREE_TYPE (exp));
23530 return error_mark_node;
23532 return exp;
23535 /* Subroutine of resolve_overloaded_unification; does deduction for a single
23536 overload. Fills TARGS with any deduced arguments, or error_mark_node if
23537 different overloads deduce different arguments for a given parm.
23538 ADDR_P is true if the expression for which deduction is being
23539 performed was of the form "& fn" rather than simply "fn".
23541 Returns 1 on success. */
23543 static int
23544 try_one_overload (tree tparms,
23545 tree orig_targs,
23546 tree targs,
23547 tree parm,
23548 tree arg,
23549 unification_kind_t strict,
23550 int sub_strict,
23551 bool addr_p,
23552 bool explain_p)
23554 int nargs;
23555 tree tempargs;
23556 int i;
23558 if (arg == error_mark_node)
23559 return 0;
23561 /* [temp.deduct.type] A template-argument can be deduced from a pointer
23562 to function or pointer to member function argument if the set of
23563 overloaded functions does not contain function templates and at most
23564 one of a set of overloaded functions provides a unique match.
23566 So if this is a template, just return success. */
23568 if (uses_template_parms (arg))
23569 return 1;
23571 if (TREE_CODE (arg) == METHOD_TYPE)
23572 arg = build_ptrmemfunc_type (build_pointer_type (arg));
23573 else if (addr_p)
23574 arg = build_pointer_type (arg);
23576 sub_strict |= maybe_adjust_types_for_deduction (tparms, strict,
23577 &parm, &arg, NULL_TREE);
23579 /* We don't copy orig_targs for this because if we have already deduced
23580 some template args from previous args, unify would complain when we
23581 try to deduce a template parameter for the same argument, even though
23582 there isn't really a conflict. */
23583 nargs = TREE_VEC_LENGTH (targs);
23584 tempargs = make_tree_vec (nargs);
23586 if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
23587 return 0;
23589 /* First make sure we didn't deduce anything that conflicts with
23590 explicitly specified args. */
23591 for (i = nargs; i--; )
23593 tree elt = TREE_VEC_ELT (tempargs, i);
23594 tree oldelt = TREE_VEC_ELT (orig_targs, i);
23596 if (!elt)
23597 /*NOP*/;
23598 else if (uses_template_parms (elt))
23599 /* Since we're unifying against ourselves, we will fill in
23600 template args used in the function parm list with our own
23601 template parms. Discard them. */
23602 TREE_VEC_ELT (tempargs, i) = NULL_TREE;
23603 else if (oldelt && ARGUMENT_PACK_P (oldelt))
23605 /* Check that the argument at each index of the deduced argument pack
23606 is equivalent to the corresponding explicitly specified argument.
23607 We may have deduced more arguments than were explicitly specified,
23608 and that's OK. */
23610 /* We used to assert ARGUMENT_PACK_INCOMPLETE_P (oldelt) here, but
23611 that's wrong if we deduce the same argument pack from multiple
23612 function arguments: it's only incomplete the first time. */
23614 tree explicit_pack = ARGUMENT_PACK_ARGS (oldelt);
23615 tree deduced_pack = ARGUMENT_PACK_ARGS (elt);
23617 if (TREE_VEC_LENGTH (deduced_pack)
23618 < TREE_VEC_LENGTH (explicit_pack))
23619 return 0;
23621 for (int j = 0; j < TREE_VEC_LENGTH (explicit_pack); j++)
23622 if (!template_args_equal (TREE_VEC_ELT (explicit_pack, j),
23623 TREE_VEC_ELT (deduced_pack, j)))
23624 return 0;
23626 else if (oldelt && !template_args_equal (oldelt, elt))
23627 return 0;
23630 for (i = nargs; i--; )
23632 tree elt = TREE_VEC_ELT (tempargs, i);
23634 if (elt)
23635 TREE_VEC_ELT (targs, i) = elt;
23638 return 1;
23641 /* PARM is a template class (perhaps with unbound template
23642 parameters). ARG is a fully instantiated type. If ARG can be
23643 bound to PARM, return ARG, otherwise return NULL_TREE. TPARMS and
23644 TARGS are as for unify. */
23646 static tree
23647 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
23648 bool explain_p)
23650 if (!CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
23651 return NULL_TREE;
23652 else if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23653 /* Matches anything. */;
23654 else if (CLASSTYPE_TI_TEMPLATE (arg) != CLASSTYPE_TI_TEMPLATE (parm))
23655 return NULL_TREE;
23657 /* We need to make a new template argument vector for the call to
23658 unify. If we used TARGS, we'd clutter it up with the result of
23659 the attempted unification, even if this class didn't work out.
23660 We also don't want to commit ourselves to all the unifications
23661 we've already done, since unification is supposed to be done on
23662 an argument-by-argument basis. In other words, consider the
23663 following pathological case:
23665 template <int I, int J, int K>
23666 struct S {};
23668 template <int I, int J>
23669 struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
23671 template <int I, int J, int K>
23672 void f(S<I, J, K>, S<I, I, I>);
23674 void g() {
23675 S<0, 0, 0> s0;
23676 S<0, 1, 2> s2;
23678 f(s0, s2);
23681 Now, by the time we consider the unification involving `s2', we
23682 already know that we must have `f<0, 0, 0>'. But, even though
23683 `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
23684 because there are two ways to unify base classes of S<0, 1, 2>
23685 with S<I, I, I>. If we kept the already deduced knowledge, we
23686 would reject the possibility I=1. */
23687 targs = copy_template_args (targs);
23688 for (tree& targ : tree_vec_range (INNERMOST_TEMPLATE_ARGS (targs)))
23689 targ = NULL_TREE;
23691 int err;
23692 if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23693 err = unify_bound_ttp_args (tparms, targs, parm, arg, explain_p);
23694 else
23695 err = unify (tparms, targs,
23696 INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (parm)),
23697 INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (arg)),
23698 UNIFY_ALLOW_NONE, explain_p);
23700 return err ? NULL_TREE : arg;
23703 /* Given a template type PARM and a class type ARG, find the unique
23704 base type in ARG that is an instance of PARM. We do not examine
23705 ARG itself; only its base-classes. If there is not exactly one
23706 appropriate base class, return NULL_TREE. PARM may be the type of
23707 a partial specialization, as well as a plain template type. Used
23708 by unify. */
23710 static enum template_base_result
23711 get_template_base (tree tparms, tree targs, tree parm, tree arg,
23712 bool explain_p, tree *result)
23714 tree rval = NULL_TREE;
23715 tree binfo;
23717 gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
23719 binfo = TYPE_BINFO (complete_type (arg));
23720 if (!binfo)
23722 /* The type could not be completed. */
23723 *result = NULL_TREE;
23724 return tbr_incomplete_type;
23727 /* Walk in inheritance graph order. The search order is not
23728 important, and this avoids multiple walks of virtual bases. */
23729 for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
23731 tree r = try_class_unification (tparms, targs, parm,
23732 BINFO_TYPE (binfo), explain_p);
23734 if (r)
23736 /* If there is more than one satisfactory baseclass, then:
23738 [temp.deduct.call]
23740 If they yield more than one possible deduced A, the type
23741 deduction fails.
23743 applies. */
23744 if (rval && !same_type_p (r, rval))
23746 /* [temp.deduct.call]/4.3: If there is a class C that is a
23747 (direct or indirect) base class of D and derived (directly or
23748 indirectly) from a class B and that would be a valid deduced
23749 A, the deduced A cannot be B or pointer to B, respectively. */
23750 if (DERIVED_FROM_P (r, rval))
23751 /* Ignore r. */
23752 continue;
23753 else if (DERIVED_FROM_P (rval, r))
23754 /* Ignore rval. */;
23755 else
23757 *result = NULL_TREE;
23758 return tbr_ambiguous_baseclass;
23762 rval = r;
23766 *result = rval;
23767 return tbr_success;
23770 /* Returns the level of DECL, which declares a template parameter. */
23772 static int
23773 template_decl_level (tree decl)
23775 switch (TREE_CODE (decl))
23777 case TYPE_DECL:
23778 case TEMPLATE_DECL:
23779 return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
23781 case PARM_DECL:
23782 return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
23784 default:
23785 gcc_unreachable ();
23787 return 0;
23790 /* Decide whether ARG can be unified with PARM, considering only the
23791 cv-qualifiers of each type, given STRICT as documented for unify.
23792 Returns nonzero iff the unification is OK on that basis. */
23794 static int
23795 check_cv_quals_for_unify (int strict, tree arg, tree parm)
23797 int arg_quals = cp_type_quals (arg);
23798 int parm_quals = cp_type_quals (parm);
23800 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
23801 && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
23803 /* Although a CVR qualifier is ignored when being applied to a
23804 substituted template parameter ([8.3.2]/1 for example), that
23805 does not allow us to unify "const T" with "int&" because both
23806 types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
23807 It is ok when we're allowing additional CV qualifiers
23808 at the outer level [14.8.2.1]/3,1st bullet. */
23809 if ((TYPE_REF_P (arg)
23810 || FUNC_OR_METHOD_TYPE_P (arg))
23811 && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
23812 return 0;
23814 if ((!INDIRECT_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
23815 && (parm_quals & TYPE_QUAL_RESTRICT))
23816 return 0;
23819 if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
23820 && (arg_quals & parm_quals) != parm_quals)
23821 return 0;
23823 if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
23824 && (parm_quals & arg_quals) != arg_quals)
23825 return 0;
23827 return 1;
23830 /* Determines the LEVEL and INDEX for the template parameter PARM. */
23831 void
23832 template_parm_level_and_index (tree parm, int* level, int* index)
23834 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
23835 || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
23836 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23838 *index = TEMPLATE_TYPE_IDX (parm);
23839 *level = TEMPLATE_TYPE_LEVEL (parm);
23841 else
23843 *index = TEMPLATE_PARM_IDX (parm);
23844 *level = TEMPLATE_PARM_LEVEL (parm);
23848 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP) \
23849 do { \
23850 if (unify (TP, TA, P, A, S, EP)) \
23851 return 1; \
23852 } while (0)
23854 /* Unifies the remaining arguments in PACKED_ARGS with the pack
23855 expansion at the end of PACKED_PARMS. Returns 0 if the type
23856 deduction succeeds, 1 otherwise. STRICT is the same as in
23857 fn_type_unification. CALL_ARGS_P is true iff PACKED_ARGS is actually a
23858 function call argument list. We'll need to adjust the arguments to make them
23859 types. SUBR tells us if this is from a recursive call to
23860 type_unification_real, or for comparing two template argument
23861 lists. */
23863 static int
23864 unify_pack_expansion (tree tparms, tree targs, tree packed_parms,
23865 tree packed_args, unification_kind_t strict,
23866 bool subr, bool explain_p)
23868 tree parm
23869 = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
23870 tree pattern = PACK_EXPANSION_PATTERN (parm);
23871 tree pack, packs = NULL_TREE;
23872 int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
23874 /* Add in any args remembered from an earlier partial instantiation. */
23875 targs = add_to_template_args (PACK_EXPANSION_EXTRA_ARGS (parm), targs);
23876 int levels = TMPL_ARGS_DEPTH (targs);
23878 packed_args = expand_template_argument_pack (packed_args);
23880 int len = TREE_VEC_LENGTH (packed_args);
23882 /* Determine the parameter packs we will be deducing from the
23883 pattern, and record their current deductions. */
23884 for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm);
23885 pack; pack = TREE_CHAIN (pack))
23887 tree parm_pack = TREE_VALUE (pack);
23888 int idx, level;
23890 /* Only template parameter packs can be deduced, not e.g. function
23891 parameter packs or __bases or __integer_pack. */
23892 if (!TEMPLATE_PARM_P (parm_pack))
23893 continue;
23895 /* Determine the index and level of this parameter pack. */
23896 template_parm_level_and_index (parm_pack, &level, &idx);
23897 if (level > levels)
23898 continue;
23900 /* Keep track of the parameter packs and their corresponding
23901 argument packs. */
23902 packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
23903 TREE_TYPE (packs) = make_tree_vec (len - start);
23906 /* Loop through all of the arguments that have not yet been
23907 unified and unify each with the pattern. */
23908 for (i = start; i < len; i++)
23910 tree parm;
23911 bool any_explicit = false;
23912 tree arg = TREE_VEC_ELT (packed_args, i);
23914 /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
23915 or the element of its argument pack at the current index if
23916 this argument was explicitly specified. */
23917 for (pack = packs; pack; pack = TREE_CHAIN (pack))
23919 int idx, level;
23920 tree arg, pargs;
23921 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
23923 arg = NULL_TREE;
23924 if (TREE_VALUE (pack)
23925 && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
23926 && (i - start < TREE_VEC_LENGTH (pargs)))
23928 any_explicit = true;
23929 arg = TREE_VEC_ELT (pargs, i - start);
23931 TMPL_ARG (targs, level, idx) = arg;
23934 /* If we had explicit template arguments, substitute them into the
23935 pattern before deduction. */
23936 if (any_explicit)
23938 /* Some arguments might still be unspecified or dependent. */
23939 bool dependent;
23940 ++processing_template_decl;
23941 dependent = any_dependent_template_arguments_p (targs);
23942 if (!dependent)
23943 --processing_template_decl;
23944 parm = tsubst (pattern, targs,
23945 explain_p ? tf_warning_or_error : tf_none,
23946 NULL_TREE);
23947 if (dependent)
23948 --processing_template_decl;
23949 if (parm == error_mark_node)
23950 return 1;
23952 else
23953 parm = pattern;
23955 /* Unify the pattern with the current argument. */
23956 if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
23957 explain_p))
23958 return 1;
23960 /* For each parameter pack, collect the deduced value. */
23961 for (pack = packs; pack; pack = TREE_CHAIN (pack))
23963 int idx, level;
23964 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
23966 TREE_VEC_ELT (TREE_TYPE (pack), i - start) =
23967 TMPL_ARG (targs, level, idx);
23971 /* Verify that the results of unification with the parameter packs
23972 produce results consistent with what we've seen before, and make
23973 the deduced argument packs available. */
23974 for (pack = packs; pack; pack = TREE_CHAIN (pack))
23976 tree old_pack = TREE_VALUE (pack);
23977 tree new_args = TREE_TYPE (pack);
23978 int i, len = TREE_VEC_LENGTH (new_args);
23979 int idx, level;
23980 bool nondeduced_p = false;
23982 /* By default keep the original deduced argument pack.
23983 If necessary, more specific code is going to update the
23984 resulting deduced argument later down in this function. */
23985 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
23986 TMPL_ARG (targs, level, idx) = old_pack;
23988 /* If NEW_ARGS contains any NULL_TREE entries, we didn't
23989 actually deduce anything. */
23990 for (i = 0; i < len && !nondeduced_p; ++i)
23991 if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
23992 nondeduced_p = true;
23993 if (nondeduced_p)
23994 continue;
23996 if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
23998 /* If we had fewer function args than explicit template args,
23999 just use the explicits. */
24000 tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
24001 int explicit_len = TREE_VEC_LENGTH (explicit_args);
24002 if (len < explicit_len)
24003 new_args = explicit_args;
24006 if (!old_pack)
24008 tree result;
24009 /* Build the deduced *_ARGUMENT_PACK. */
24010 if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
24012 result = make_node (NONTYPE_ARGUMENT_PACK);
24013 TREE_CONSTANT (result) = 1;
24015 else
24016 result = cxx_make_type (TYPE_ARGUMENT_PACK);
24018 ARGUMENT_PACK_ARGS (result) = new_args;
24020 /* Note the deduced argument packs for this parameter
24021 pack. */
24022 TMPL_ARG (targs, level, idx) = result;
24024 else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
24025 && (ARGUMENT_PACK_ARGS (old_pack)
24026 == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
24028 /* We only had the explicitly-provided arguments before, but
24029 now we have a complete set of arguments. */
24030 tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
24032 ARGUMENT_PACK_ARGS (old_pack) = new_args;
24033 ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
24034 ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
24036 else
24038 tree bad_old_arg = NULL_TREE, bad_new_arg = NULL_TREE;
24039 tree old_args = ARGUMENT_PACK_ARGS (old_pack);
24040 temp_override<int> ovl (TREE_VEC_LENGTH (old_args));
24041 /* During template argument deduction for the aggregate deduction
24042 candidate, the number of elements in a trailing parameter pack
24043 is only deduced from the number of remaining function
24044 arguments if it is not otherwise deduced. */
24045 if (cxx_dialect >= cxx20
24046 && TREE_VEC_LENGTH (new_args) < TREE_VEC_LENGTH (old_args)
24047 /* FIXME This isn't set properly for partial instantiations. */
24048 && TPARMS_PRIMARY_TEMPLATE (tparms)
24049 && builtin_guide_p (TPARMS_PRIMARY_TEMPLATE (tparms)))
24050 TREE_VEC_LENGTH (old_args) = TREE_VEC_LENGTH (new_args);
24051 if (!comp_template_args (old_args, new_args,
24052 &bad_old_arg, &bad_new_arg))
24053 /* Inconsistent unification of this parameter pack. */
24054 return unify_parameter_pack_inconsistent (explain_p,
24055 bad_old_arg,
24056 bad_new_arg);
24060 return unify_success (explain_p);
24063 /* Handle unification of the domain of an array. PARM_DOM and ARG_DOM are
24064 INTEGER_TYPEs representing the TYPE_DOMAIN of ARRAY_TYPEs. The other
24065 parameters and return value are as for unify. */
24067 static int
24068 unify_array_domain (tree tparms, tree targs,
24069 tree parm_dom, tree arg_dom,
24070 bool explain_p)
24072 tree parm_max;
24073 tree arg_max;
24074 bool parm_cst;
24075 bool arg_cst;
24077 /* Our representation of array types uses "N - 1" as the
24078 TYPE_MAX_VALUE for an array with "N" elements, if "N" is
24079 not an integer constant. We cannot unify arbitrarily
24080 complex expressions, so we eliminate the MINUS_EXPRs
24081 here. */
24082 parm_max = TYPE_MAX_VALUE (parm_dom);
24083 parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
24084 if (!parm_cst)
24086 gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
24087 parm_max = TREE_OPERAND (parm_max, 0);
24089 arg_max = TYPE_MAX_VALUE (arg_dom);
24090 arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
24091 if (!arg_cst)
24093 /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
24094 trying to unify the type of a variable with the type
24095 of a template parameter. For example:
24097 template <unsigned int N>
24098 void f (char (&) [N]);
24099 int g();
24100 void h(int i) {
24101 char a[g(i)];
24102 f(a);
24105 Here, the type of the ARG will be "int [g(i)]", and
24106 may be a SAVE_EXPR, etc. */
24107 if (TREE_CODE (arg_max) != MINUS_EXPR)
24108 return unify_vla_arg (explain_p, arg_dom);
24109 arg_max = TREE_OPERAND (arg_max, 0);
24112 /* If only one of the bounds used a MINUS_EXPR, compensate
24113 by adding one to the other bound. */
24114 if (parm_cst && !arg_cst)
24115 parm_max = fold_build2_loc (input_location, PLUS_EXPR,
24116 integer_type_node,
24117 parm_max,
24118 integer_one_node);
24119 else if (arg_cst && !parm_cst)
24120 arg_max = fold_build2_loc (input_location, PLUS_EXPR,
24121 integer_type_node,
24122 arg_max,
24123 integer_one_node);
24125 return unify (tparms, targs, parm_max, arg_max,
24126 UNIFY_ALLOW_INTEGER, explain_p);
24129 /* Returns whether T, a P or A in unify, is a type, template or expression. */
24131 enum pa_kind_t { pa_type, pa_tmpl, pa_expr };
24133 static pa_kind_t
24134 pa_kind (tree t)
24136 if (PACK_EXPANSION_P (t))
24137 t = PACK_EXPANSION_PATTERN (t);
24138 if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM
24139 || TREE_CODE (t) == UNBOUND_CLASS_TEMPLATE
24140 || DECL_TYPE_TEMPLATE_P (t))
24141 return pa_tmpl;
24142 else if (TYPE_P (t))
24143 return pa_type;
24144 else
24145 return pa_expr;
24148 /* Deduce the value of template parameters. TPARMS is the (innermost)
24149 set of template parameters to a template. TARGS is the bindings
24150 for those template parameters, as determined thus far; TARGS may
24151 include template arguments for outer levels of template parameters
24152 as well. PARM is a parameter to a template function, or a
24153 subcomponent of that parameter; ARG is the corresponding argument.
24154 This function attempts to match PARM with ARG in a manner
24155 consistent with the existing assignments in TARGS. If more values
24156 are deduced, then TARGS is updated.
24158 Returns 0 if the type deduction succeeds, 1 otherwise. The
24159 parameter STRICT is a bitwise or of the following flags:
24161 UNIFY_ALLOW_NONE:
24162 Require an exact match between PARM and ARG.
24163 UNIFY_ALLOW_MORE_CV_QUAL:
24164 Allow the deduced ARG to be more cv-qualified (by qualification
24165 conversion) than ARG.
24166 UNIFY_ALLOW_LESS_CV_QUAL:
24167 Allow the deduced ARG to be less cv-qualified than ARG.
24168 UNIFY_ALLOW_DERIVED:
24169 Allow the deduced ARG to be a template base class of ARG,
24170 or a pointer to a template base class of the type pointed to by
24171 ARG.
24172 UNIFY_ALLOW_INTEGER:
24173 Allow any integral type to be deduced. See the TEMPLATE_PARM_INDEX
24174 case for more information.
24175 UNIFY_ALLOW_OUTER_LEVEL:
24176 This is the outermost level of a deduction. Used to determine validity
24177 of qualification conversions. A valid qualification conversion must
24178 have const qualified pointers leading up to the inner type which
24179 requires additional CV quals, except at the outer level, where const
24180 is not required [conv.qual]. It would be normal to set this flag in
24181 addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
24182 UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
24183 This is the outermost level of a deduction, and PARM can be more CV
24184 qualified at this point.
24185 UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
24186 This is the outermost level of a deduction, and PARM can be less CV
24187 qualified at this point. */
24189 static int
24190 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
24191 bool explain_p)
24193 int idx;
24194 tree targ;
24195 tree tparm;
24196 int strict_in = strict;
24197 tsubst_flags_t complain = (explain_p
24198 ? tf_warning_or_error
24199 : tf_none);
24201 /* I don't think this will do the right thing with respect to types.
24202 But the only case I've seen it in so far has been array bounds, where
24203 signedness is the only information lost, and I think that will be
24204 okay. VIEW_CONVERT_EXPR can appear with class NTTP, thanks to
24205 finish_id_expression_1, and are also OK. */
24206 while (CONVERT_EXPR_P (parm) || TREE_CODE (parm) == VIEW_CONVERT_EXPR)
24207 parm = TREE_OPERAND (parm, 0);
24209 if (arg == error_mark_node)
24210 return unify_invalid (explain_p);
24211 if (arg == unknown_type_node
24212 || arg == init_list_type_node)
24213 /* We can't deduce anything from this, but we might get all the
24214 template args from other function args. */
24215 return unify_success (explain_p);
24217 if (parm == any_targ_node || arg == any_targ_node)
24218 return unify_success (explain_p);
24220 /* If PARM uses template parameters, then we can't bail out here,
24221 even if ARG == PARM, since we won't record unifications for the
24222 template parameters. We might need them if we're trying to
24223 figure out which of two things is more specialized. */
24224 if (arg == parm
24225 && (DECL_P (parm) || !uses_template_parms (parm)))
24226 return unify_success (explain_p);
24228 /* Handle init lists early, so the rest of the function can assume
24229 we're dealing with a type. */
24230 if (BRACE_ENCLOSED_INITIALIZER_P (arg))
24232 tree elttype;
24233 tree orig_parm = parm;
24235 if (!is_std_init_list (parm)
24236 && TREE_CODE (parm) != ARRAY_TYPE)
24237 /* We can only deduce from an initializer list argument if the
24238 parameter is std::initializer_list or an array; otherwise this
24239 is a non-deduced context. */
24240 return unify_success (explain_p);
24242 if (TREE_CODE (parm) == ARRAY_TYPE)
24243 elttype = TREE_TYPE (parm);
24244 else
24246 elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
24247 /* Deduction is defined in terms of a single type, so just punt
24248 on the (bizarre) std::initializer_list<T...>. */
24249 if (PACK_EXPANSION_P (elttype))
24250 return unify_success (explain_p);
24253 if (strict != DEDUCE_EXACT
24254 && TYPE_P (elttype)
24255 && !uses_deducible_template_parms (elttype))
24256 /* If ELTTYPE has no deducible template parms, skip deduction from
24257 the list elements. */;
24258 else
24259 for (auto &e: CONSTRUCTOR_ELTS (arg))
24261 tree elt = e.value;
24262 int elt_strict = strict;
24264 if (elt == error_mark_node)
24265 return unify_invalid (explain_p);
24267 if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
24269 tree type = TREE_TYPE (elt);
24270 if (type == error_mark_node)
24271 return unify_invalid (explain_p);
24272 /* It should only be possible to get here for a call. */
24273 gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
24274 elt_strict |= maybe_adjust_types_for_deduction
24275 (tparms, DEDUCE_CALL, &elttype, &type, elt);
24276 elt = type;
24279 RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
24280 explain_p);
24283 if (TREE_CODE (parm) == ARRAY_TYPE
24284 && deducible_array_bound (TYPE_DOMAIN (parm)))
24286 /* Also deduce from the length of the initializer list. */
24287 tree max = size_int (CONSTRUCTOR_NELTS (arg));
24288 tree idx = compute_array_index_type (NULL_TREE, max, tf_none);
24289 if (idx == error_mark_node)
24290 return unify_invalid (explain_p);
24291 return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
24292 idx, explain_p);
24295 /* If the std::initializer_list<T> deduction worked, replace the
24296 deduced A with std::initializer_list<A>. */
24297 if (orig_parm != parm)
24299 idx = TEMPLATE_TYPE_IDX (orig_parm);
24300 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
24301 targ = listify (targ);
24302 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
24304 return unify_success (explain_p);
24307 /* If parm and arg aren't the same kind of thing (template, type, or
24308 expression), fail early. */
24309 if (pa_kind (parm) != pa_kind (arg))
24310 return unify_invalid (explain_p);
24312 /* Immediately reject some pairs that won't unify because of
24313 cv-qualification mismatches. */
24314 if (TREE_CODE (arg) == TREE_CODE (parm)
24315 && TYPE_P (arg)
24316 /* It is the elements of the array which hold the cv quals of an array
24317 type, and the elements might be template type parms. We'll check
24318 when we recurse. */
24319 && TREE_CODE (arg) != ARRAY_TYPE
24320 /* We check the cv-qualifiers when unifying with template type
24321 parameters below. We want to allow ARG `const T' to unify with
24322 PARM `T' for example, when computing which of two templates
24323 is more specialized, for example. */
24324 && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
24325 && !check_cv_quals_for_unify (strict_in, arg, parm))
24326 return unify_cv_qual_mismatch (explain_p, parm, arg);
24328 if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
24329 && TYPE_P (parm) && !CP_TYPE_CONST_P (parm)
24330 && !FUNC_OR_METHOD_TYPE_P (parm))
24331 strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
24332 /* PMFs recurse at the same level, so don't strip this yet. */
24333 if (!TYPE_PTRMEMFUNC_P (parm))
24334 strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
24335 strict &= ~UNIFY_ALLOW_DERIVED;
24336 strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
24337 strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
24339 switch (TREE_CODE (parm))
24341 case TYPENAME_TYPE:
24342 case SCOPE_REF:
24343 case UNBOUND_CLASS_TEMPLATE:
24344 /* In a type which contains a nested-name-specifier, template
24345 argument values cannot be deduced for template parameters used
24346 within the nested-name-specifier. */
24347 return unify_success (explain_p);
24349 case TEMPLATE_TYPE_PARM:
24350 case TEMPLATE_TEMPLATE_PARM:
24351 case BOUND_TEMPLATE_TEMPLATE_PARM:
24352 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
24353 if (error_operand_p (tparm))
24354 return unify_invalid (explain_p);
24356 if (TEMPLATE_TYPE_LEVEL (parm)
24357 != template_decl_level (tparm))
24358 /* The PARM is not one we're trying to unify. Just check
24359 to see if it matches ARG. */
24361 if (TREE_CODE (arg) == TREE_CODE (parm)
24362 && (is_auto (parm) ? is_auto (arg)
24363 : same_type_p (parm, arg)))
24364 return unify_success (explain_p);
24365 else
24366 return unify_type_mismatch (explain_p, parm, arg);
24368 idx = TEMPLATE_TYPE_IDX (parm);
24369 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
24370 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
24371 if (error_operand_p (tparm))
24372 return unify_invalid (explain_p);
24374 /* Check for mixed types and values. */
24375 if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
24376 && TREE_CODE (tparm) != TYPE_DECL)
24377 || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
24378 && TREE_CODE (tparm) != TEMPLATE_DECL))
24379 gcc_unreachable ();
24381 if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
24383 if ((strict_in & UNIFY_ALLOW_DERIVED)
24384 && CLASS_TYPE_P (arg))
24386 /* First try to match ARG directly. */
24387 tree t = try_class_unification (tparms, targs, parm, arg,
24388 explain_p);
24389 if (!t)
24391 /* Otherwise, look for a suitable base of ARG, as below. */
24392 enum template_base_result r;
24393 r = get_template_base (tparms, targs, parm, arg,
24394 explain_p, &t);
24395 if (!t)
24396 return unify_no_common_base (explain_p, r, parm, arg);
24397 arg = t;
24400 /* ARG must be constructed from a template class or a template
24401 template parameter. */
24402 else if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
24403 && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
24404 return unify_template_deduction_failure (explain_p, parm, arg);
24406 /* Deduce arguments T, i from TT<T> or TT<i>. */
24407 if (unify_bound_ttp_args (tparms, targs, parm, arg, explain_p))
24408 return 1;
24410 arg = TYPE_TI_TEMPLATE (arg);
24411 if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg))
24412 /* If the template is a template template parameter, use the
24413 TEMPLATE_TEMPLATE_PARM for matching. */
24414 arg = TREE_TYPE (arg);
24416 /* Fall through to deduce template name. */
24419 if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
24420 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
24422 /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>. */
24424 /* Simple cases: Value already set, does match or doesn't. */
24425 if (targ != NULL_TREE && template_args_equal (targ, arg))
24426 return unify_success (explain_p);
24427 else if (targ)
24428 return unify_inconsistency (explain_p, parm, targ, arg);
24430 else
24432 /* If PARM is `const T' and ARG is only `int', we don't have
24433 a match unless we are allowing additional qualification.
24434 If ARG is `const int' and PARM is just `T' that's OK;
24435 that binds `const int' to `T'. */
24436 if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
24437 arg, parm))
24438 return unify_cv_qual_mismatch (explain_p, parm, arg);
24440 /* Consider the case where ARG is `const volatile int' and
24441 PARM is `const T'. Then, T should be `volatile int'. */
24442 arg = cp_build_qualified_type
24443 (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
24444 if (arg == error_mark_node)
24445 return unify_invalid (explain_p);
24447 /* Simple cases: Value already set, does match or doesn't. */
24448 if (targ != NULL_TREE && same_type_p (targ, arg))
24449 return unify_success (explain_p);
24450 else if (targ)
24451 return unify_inconsistency (explain_p, parm, targ, arg);
24453 /* Make sure that ARG is not a variable-sized array. (Note
24454 that were talking about variable-sized arrays (like
24455 `int[n]'), rather than arrays of unknown size (like
24456 `int[]').) We'll get very confused by such a type since
24457 the bound of the array is not constant, and therefore
24458 not mangleable. Besides, such types are not allowed in
24459 ISO C++, so we can do as we please here. We do allow
24460 them for 'auto' deduction, since that isn't ABI-exposed. */
24461 if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
24462 return unify_vla_arg (explain_p, arg);
24464 /* Strip typedefs as in convert_template_argument. */
24465 arg = canonicalize_type_argument (arg, tf_none);
24468 /* If ARG is a parameter pack or an expansion, we cannot unify
24469 against it unless PARM is also a parameter pack. */
24470 if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
24471 && !template_parameter_pack_p (parm))
24472 return unify_parameter_pack_mismatch (explain_p, parm, arg);
24474 /* If the argument deduction results is a METHOD_TYPE,
24475 then there is a problem.
24476 METHOD_TYPE doesn't map to any real C++ type the result of
24477 the deduction cannot be of that type. */
24478 if (TREE_CODE (arg) == METHOD_TYPE)
24479 return unify_method_type_error (explain_p, arg);
24481 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
24482 return unify_success (explain_p);
24484 case TEMPLATE_PARM_INDEX:
24485 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
24486 if (error_operand_p (tparm))
24487 return unify_invalid (explain_p);
24489 if (TEMPLATE_PARM_LEVEL (parm)
24490 != template_decl_level (tparm))
24492 /* The PARM is not one we're trying to unify. Just check
24493 to see if it matches ARG. */
24494 int result = !(TREE_CODE (arg) == TREE_CODE (parm)
24495 && cp_tree_equal (parm, arg));
24496 if (result)
24497 unify_expression_unequal (explain_p, parm, arg);
24498 return result;
24501 idx = TEMPLATE_PARM_IDX (parm);
24502 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
24504 if (targ)
24506 if ((strict & UNIFY_ALLOW_INTEGER)
24507 && TREE_TYPE (targ) && TREE_TYPE (arg)
24508 && CP_INTEGRAL_TYPE_P (TREE_TYPE (targ)))
24509 /* We're deducing from an array bound, the type doesn't matter.
24510 This conversion should match the one below. */
24511 arg = fold (build_nop (TREE_TYPE (targ), arg));
24512 int x = !cp_tree_equal (targ, arg);
24513 if (x)
24514 unify_inconsistency (explain_p, parm, targ, arg);
24515 return x;
24518 /* [temp.deduct.type] If, in the declaration of a function template
24519 with a non-type template-parameter, the non-type
24520 template-parameter is used in an expression in the function
24521 parameter-list and, if the corresponding template-argument is
24522 deduced, the template-argument type shall match the type of the
24523 template-parameter exactly, except that a template-argument
24524 deduced from an array bound may be of any integral type.
24525 The non-type parameter might use already deduced type parameters. */
24526 tparm = TREE_TYPE (parm);
24527 if (TEMPLATE_PARM_LEVEL (parm) > TMPL_ARGS_DEPTH (targs))
24528 /* We don't have enough levels of args to do any substitution. This
24529 can happen in the context of -fnew-ttp-matching. */;
24530 else
24532 ++processing_template_decl;
24533 tparm = tsubst (tparm, targs, tf_none, NULL_TREE);
24534 --processing_template_decl;
24536 if (tree a = type_uses_auto (tparm))
24538 tparm = do_auto_deduction (tparm, arg, a,
24539 complain, adc_unify, targs,
24540 LOOKUP_NORMAL,
24541 TPARMS_PRIMARY_TEMPLATE (tparms));
24542 if (tparm == error_mark_node)
24543 return 1;
24547 if (!TREE_TYPE (arg)
24548 || TREE_CODE (TREE_TYPE (arg)) == DEPENDENT_OPERATOR_TYPE)
24549 /* Template-parameter dependent expression. Just accept it for now.
24550 It will later be processed in convert_template_argument. */
24552 else if (same_type_ignoring_top_level_qualifiers_p
24553 (non_reference (TREE_TYPE (arg)),
24554 non_reference (tparm)))
24555 /* OK. Ignore top-level quals here because a class-type template
24556 parameter object is const. */;
24557 else if ((strict & UNIFY_ALLOW_INTEGER)
24558 && CP_INTEGRAL_TYPE_P (tparm))
24559 /* Convert the ARG to the type of PARM; the deduced non-type
24560 template argument must exactly match the types of the
24561 corresponding parameter. This conversion should match the
24562 one above. */
24563 arg = fold (build_nop (tparm, arg));
24564 else if (uses_template_parms (tparm))
24566 /* We haven't deduced the type of this parameter yet. */
24567 if (cxx_dialect >= cxx17
24568 /* We deduce from array bounds in try_array_deduction. */
24569 && !(strict & UNIFY_ALLOW_INTEGER)
24570 && TEMPLATE_PARM_LEVEL (parm) <= TMPL_ARGS_DEPTH (targs))
24572 /* Deduce it from the non-type argument. As above, ignore
24573 top-level quals here too. */
24574 tree atype = cv_unqualified (TREE_TYPE (arg));
24575 RECUR_AND_CHECK_FAILURE (tparms, targs,
24576 tparm, atype,
24577 UNIFY_ALLOW_NONE, explain_p);
24578 /* Now check whether the type of this parameter is still
24579 dependent, and give up if so. */
24580 ++processing_template_decl;
24581 tparm = tsubst (TREE_TYPE (parm), targs, tf_none, NULL_TREE);
24582 --processing_template_decl;
24583 if (uses_template_parms (tparm))
24584 return unify_success (explain_p);
24586 else
24587 /* Try again later. */
24588 return unify_success (explain_p);
24590 else
24591 return unify_type_mismatch (explain_p, tparm, TREE_TYPE (arg));
24593 /* If ARG is a parameter pack or an expansion, we cannot unify
24594 against it unless PARM is also a parameter pack. */
24595 if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
24596 && !TEMPLATE_PARM_PARAMETER_PACK (parm))
24597 return unify_parameter_pack_mismatch (explain_p, parm, arg);
24600 bool removed_attr = false;
24601 arg = strip_typedefs_expr (arg, &removed_attr);
24603 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
24604 return unify_success (explain_p);
24606 case PTRMEM_CST:
24608 /* A pointer-to-member constant can be unified only with
24609 another constant. */
24610 if (TREE_CODE (arg) != PTRMEM_CST)
24611 return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
24613 /* Just unify the class member. It would be useless (and possibly
24614 wrong, depending on the strict flags) to unify also
24615 PTRMEM_CST_CLASS, because we want to be sure that both parm and
24616 arg refer to the same variable, even if through different
24617 classes. For instance:
24619 struct A { int x; };
24620 struct B : A { };
24622 Unification of &A::x and &B::x must succeed. */
24623 return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
24624 PTRMEM_CST_MEMBER (arg), strict, explain_p);
24627 case POINTER_TYPE:
24629 if (!TYPE_PTR_P (arg))
24630 return unify_type_mismatch (explain_p, parm, arg);
24632 /* [temp.deduct.call]
24634 A can be another pointer or pointer to member type that can
24635 be converted to the deduced A via a qualification
24636 conversion (_conv.qual_).
24638 We pass down STRICT here rather than UNIFY_ALLOW_NONE.
24639 This will allow for additional cv-qualification of the
24640 pointed-to types if appropriate. */
24642 if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
24643 /* The derived-to-base conversion only persists through one
24644 level of pointers. */
24645 strict |= (strict_in & UNIFY_ALLOW_DERIVED);
24647 return unify (tparms, targs, TREE_TYPE (parm),
24648 TREE_TYPE (arg), strict, explain_p);
24651 case REFERENCE_TYPE:
24652 if (!TYPE_REF_P (arg))
24653 return unify_type_mismatch (explain_p, parm, arg);
24654 return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
24655 strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
24657 case ARRAY_TYPE:
24658 if (TREE_CODE (arg) != ARRAY_TYPE)
24659 return unify_type_mismatch (explain_p, parm, arg);
24660 if ((TYPE_DOMAIN (parm) == NULL_TREE)
24661 != (TYPE_DOMAIN (arg) == NULL_TREE))
24662 return unify_type_mismatch (explain_p, parm, arg);
24663 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
24664 strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
24665 if (TYPE_DOMAIN (parm) != NULL_TREE)
24666 return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
24667 TYPE_DOMAIN (arg), explain_p);
24668 return unify_success (explain_p);
24670 case REAL_TYPE:
24671 case COMPLEX_TYPE:
24672 case VECTOR_TYPE:
24673 case INTEGER_TYPE:
24674 case BOOLEAN_TYPE:
24675 case ENUMERAL_TYPE:
24676 case VOID_TYPE:
24677 case OPAQUE_TYPE:
24678 case NULLPTR_TYPE:
24679 if (TREE_CODE (arg) != TREE_CODE (parm))
24680 return unify_type_mismatch (explain_p, parm, arg);
24682 /* We have already checked cv-qualification at the top of the
24683 function. */
24684 if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
24685 return unify_type_mismatch (explain_p, parm, arg);
24687 /* As far as unification is concerned, this wins. Later checks
24688 will invalidate it if necessary. */
24689 return unify_success (explain_p);
24691 /* Types INTEGER_CST and MINUS_EXPR can come from array bounds. */
24692 /* Type INTEGER_CST can come from ordinary constant template args. */
24693 case INTEGER_CST:
24694 case REAL_CST:
24695 while (CONVERT_EXPR_P (arg))
24696 arg = TREE_OPERAND (arg, 0);
24698 if (TREE_CODE (arg) != TREE_CODE (parm))
24699 return unify_template_argument_mismatch (explain_p, parm, arg);
24700 return (simple_cst_equal (parm, arg)
24701 ? unify_success (explain_p)
24702 : unify_template_argument_mismatch (explain_p, parm, arg));
24704 case TREE_VEC:
24706 int i, len, argslen;
24707 int parm_variadic_p = 0;
24709 if (TREE_CODE (arg) != TREE_VEC)
24710 return unify_template_argument_mismatch (explain_p, parm, arg);
24712 len = TREE_VEC_LENGTH (parm);
24713 argslen = TREE_VEC_LENGTH (arg);
24715 /* Check for pack expansions in the parameters. */
24716 for (i = 0; i < len; ++i)
24718 if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
24720 if (i == len - 1)
24721 /* We can unify against something with a trailing
24722 parameter pack. */
24723 parm_variadic_p = 1;
24724 else
24725 /* [temp.deduct.type]/9: If the template argument list of
24726 P contains a pack expansion that is not the last
24727 template argument, the entire template argument list
24728 is a non-deduced context. */
24729 return unify_success (explain_p);
24733 /* If we don't have enough arguments to satisfy the parameters
24734 (not counting the pack expression at the end), or we have
24735 too many arguments for a parameter list that doesn't end in
24736 a pack expression, we can't unify. */
24737 if (parm_variadic_p
24738 ? argslen < len - parm_variadic_p
24739 : argslen != len)
24740 return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
24742 /* Unify all of the parameters that precede the (optional)
24743 pack expression. */
24744 for (i = 0; i < len - parm_variadic_p; ++i)
24746 RECUR_AND_CHECK_FAILURE (tparms, targs,
24747 TREE_VEC_ELT (parm, i),
24748 TREE_VEC_ELT (arg, i),
24749 UNIFY_ALLOW_NONE, explain_p);
24751 if (parm_variadic_p)
24752 return unify_pack_expansion (tparms, targs, parm, arg,
24753 DEDUCE_EXACT,
24754 /*subr=*/true, explain_p);
24755 return unify_success (explain_p);
24758 case RECORD_TYPE:
24759 case UNION_TYPE:
24760 if (TREE_CODE (arg) != TREE_CODE (parm))
24761 return unify_type_mismatch (explain_p, parm, arg);
24763 if (TYPE_PTRMEMFUNC_P (parm))
24765 if (!TYPE_PTRMEMFUNC_P (arg))
24766 return unify_type_mismatch (explain_p, parm, arg);
24768 return unify (tparms, targs,
24769 TYPE_PTRMEMFUNC_FN_TYPE (parm),
24770 TYPE_PTRMEMFUNC_FN_TYPE (arg),
24771 strict, explain_p);
24773 else if (TYPE_PTRMEMFUNC_P (arg))
24774 return unify_type_mismatch (explain_p, parm, arg);
24776 if (CLASSTYPE_TEMPLATE_INFO (parm))
24778 tree t = NULL_TREE;
24780 if (strict_in & UNIFY_ALLOW_DERIVED)
24782 /* First, we try to unify the PARM and ARG directly. */
24783 t = try_class_unification (tparms, targs,
24784 parm, arg, explain_p);
24786 if (!t)
24788 /* Fallback to the special case allowed in
24789 [temp.deduct.call]:
24791 If P is a class, and P has the form
24792 template-id, then A can be a derived class of
24793 the deduced A. Likewise, if P is a pointer to
24794 a class of the form template-id, A can be a
24795 pointer to a derived class pointed to by the
24796 deduced A. */
24797 enum template_base_result r;
24798 r = get_template_base (tparms, targs, parm, arg,
24799 explain_p, &t);
24801 if (!t)
24803 /* Don't give the derived diagnostic if we're
24804 already dealing with the same template. */
24805 bool same_template
24806 = (CLASSTYPE_TEMPLATE_INFO (arg)
24807 && (CLASSTYPE_TI_TEMPLATE (parm)
24808 == CLASSTYPE_TI_TEMPLATE (arg)));
24809 return unify_no_common_base (explain_p && !same_template,
24810 r, parm, arg);
24814 else if (CLASSTYPE_TEMPLATE_INFO (arg)
24815 && (CLASSTYPE_TI_TEMPLATE (parm)
24816 == CLASSTYPE_TI_TEMPLATE (arg)))
24817 /* Perhaps PARM is something like S<U> and ARG is S<int>.
24818 Then, we should unify `int' and `U'. */
24819 t = arg;
24820 else
24821 /* There's no chance of unification succeeding. */
24822 return unify_type_mismatch (explain_p, parm, arg);
24824 if (PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)))
24825 return unify (tparms, targs,
24826 INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (parm)),
24827 INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (t)),
24828 UNIFY_ALLOW_NONE, explain_p);
24829 else
24830 return unify_success (explain_p);
24832 else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
24833 return unify_type_mismatch (explain_p, parm, arg);
24834 return unify_success (explain_p);
24836 case METHOD_TYPE:
24837 case FUNCTION_TYPE:
24839 unsigned int nargs;
24840 tree *args;
24841 tree a;
24842 unsigned int i;
24844 if (TREE_CODE (arg) != TREE_CODE (parm))
24845 return unify_type_mismatch (explain_p, parm, arg);
24847 /* CV qualifications for methods can never be deduced, they must
24848 match exactly. We need to check them explicitly here,
24849 because type_unification_real treats them as any other
24850 cv-qualified parameter. */
24851 if (TREE_CODE (parm) == METHOD_TYPE
24852 && (!check_cv_quals_for_unify
24853 (UNIFY_ALLOW_NONE,
24854 class_of_this_parm (arg),
24855 class_of_this_parm (parm))))
24856 return unify_cv_qual_mismatch (explain_p, parm, arg);
24857 if (TREE_CODE (arg) == FUNCTION_TYPE
24858 && type_memfn_quals (parm) != type_memfn_quals (arg))
24859 return unify_cv_qual_mismatch (explain_p, parm, arg);
24860 if (type_memfn_rqual (parm) != type_memfn_rqual (arg))
24861 return unify_type_mismatch (explain_p, parm, arg);
24863 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
24864 TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
24866 nargs = list_length (TYPE_ARG_TYPES (arg));
24867 args = XALLOCAVEC (tree, nargs);
24868 for (a = TYPE_ARG_TYPES (arg), i = 0;
24869 a != NULL_TREE && a != void_list_node;
24870 a = TREE_CHAIN (a), ++i)
24871 args[i] = TREE_VALUE (a);
24872 nargs = i;
24874 if (type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
24875 args, nargs, 1, DEDUCE_EXACT,
24876 NULL, explain_p))
24877 return 1;
24879 if (flag_noexcept_type)
24881 tree pspec = TYPE_RAISES_EXCEPTIONS (parm);
24882 tree aspec = canonical_eh_spec (TYPE_RAISES_EXCEPTIONS (arg));
24883 if (pspec == NULL_TREE) pspec = noexcept_false_spec;
24884 if (aspec == NULL_TREE) aspec = noexcept_false_spec;
24885 if (TREE_PURPOSE (pspec) && TREE_PURPOSE (aspec)
24886 && uses_template_parms (TREE_PURPOSE (pspec)))
24887 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_PURPOSE (pspec),
24888 TREE_PURPOSE (aspec),
24889 UNIFY_ALLOW_NONE, explain_p);
24890 else
24892 bool pn = nothrow_spec_p (pspec);
24893 bool an = nothrow_spec_p (aspec);
24894 /* Here "less cv-qual" means the deduced arg (i.e. parm) has
24895 /more/ noexcept, since function pointer conversions are the
24896 reverse of qualification conversions. */
24897 if (an == pn
24898 || (an < pn && (strict & UNIFY_ALLOW_LESS_CV_QUAL))
24899 || (an > pn && (strict & UNIFY_ALLOW_MORE_CV_QUAL)))
24900 /* OK. */;
24901 else
24902 return unify_type_mismatch (explain_p, parm, arg);
24905 if (flag_tm)
24907 /* As for noexcept. */
24908 bool pn = tx_safe_fn_type_p (parm);
24909 bool an = tx_safe_fn_type_p (arg);
24910 if (an == pn
24911 || (an < pn && (strict & UNIFY_ALLOW_LESS_CV_QUAL))
24912 || (an > pn && (strict & UNIFY_ALLOW_MORE_CV_QUAL)))
24913 /* OK. */;
24914 else
24915 return unify_type_mismatch (explain_p, parm, arg);
24918 return 0;
24921 case OFFSET_TYPE:
24922 /* Unify a pointer to member with a pointer to member function, which
24923 deduces the type of the member as a function type. */
24924 if (TYPE_PTRMEMFUNC_P (arg))
24926 /* Check top-level cv qualifiers */
24927 if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
24928 return unify_cv_qual_mismatch (explain_p, parm, arg);
24930 RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
24931 TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
24932 UNIFY_ALLOW_NONE, explain_p);
24934 /* Determine the type of the function we are unifying against. */
24935 tree fntype = static_fn_type (arg);
24937 return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
24940 if (TREE_CODE (arg) != OFFSET_TYPE)
24941 return unify_type_mismatch (explain_p, parm, arg);
24942 RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
24943 TYPE_OFFSET_BASETYPE (arg),
24944 UNIFY_ALLOW_NONE, explain_p);
24945 return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
24946 strict, explain_p);
24948 case CONST_DECL:
24949 /* CONST_DECL should already have been folded to its DECL_INITIAL. */
24950 gcc_unreachable ();
24952 case FIELD_DECL:
24953 case TEMPLATE_DECL:
24954 /* Matched cases are handled by the ARG == PARM test above. */
24955 return unify_template_argument_mismatch (explain_p, parm, arg);
24957 case VAR_DECL:
24958 /* We might get a variable as a non-type template argument in parm if the
24959 corresponding parameter is type-dependent. Make any necessary
24960 adjustments based on whether arg is a reference. */
24961 if (CONSTANT_CLASS_P (arg))
24962 parm = fold_non_dependent_expr (parm, complain);
24963 else if (REFERENCE_REF_P (arg))
24965 tree sub = TREE_OPERAND (arg, 0);
24966 STRIP_NOPS (sub);
24967 if (TREE_CODE (sub) == ADDR_EXPR)
24968 arg = TREE_OPERAND (sub, 0);
24970 /* Now use the normal expression code to check whether they match. */
24971 goto expr;
24973 case TYPE_ARGUMENT_PACK:
24974 case NONTYPE_ARGUMENT_PACK:
24975 return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
24976 ARGUMENT_PACK_ARGS (arg), strict, explain_p);
24978 case TYPEOF_TYPE:
24979 case DECLTYPE_TYPE:
24980 case TRAIT_TYPE:
24981 /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
24982 or TRAIT_TYPE nodes. */
24983 return unify_success (explain_p);
24985 case ERROR_MARK:
24986 /* Unification fails if we hit an error node. */
24987 return unify_invalid (explain_p);
24989 case INDIRECT_REF:
24990 if (REFERENCE_REF_P (parm))
24992 bool pexp = PACK_EXPANSION_P (arg);
24993 if (pexp)
24994 arg = PACK_EXPANSION_PATTERN (arg);
24995 if (REFERENCE_REF_P (arg))
24996 arg = TREE_OPERAND (arg, 0);
24997 if (pexp)
24998 arg = make_pack_expansion (arg, complain);
24999 return unify (tparms, targs, TREE_OPERAND (parm, 0), arg,
25000 strict, explain_p);
25002 /* FALLTHRU */
25004 default:
25005 /* An unresolved overload is a nondeduced context. */
25006 if (is_overloaded_fn (parm) || type_unknown_p (parm))
25007 return unify_success (explain_p);
25008 gcc_assert (EXPR_P (parm)
25009 || TREE_CODE (parm) == CONSTRUCTOR
25010 || TREE_CODE (parm) == TRAIT_EXPR);
25011 expr:
25012 /* We must be looking at an expression. This can happen with
25013 something like:
25015 template <int I>
25016 void foo(S<I>, S<I + 2>);
25020 template<typename T>
25021 void foo(A<T, T{}>);
25023 This is a "non-deduced context":
25025 [deduct.type]
25027 The non-deduced contexts are:
25029 --A non-type template argument or an array bound in which
25030 a subexpression references a template parameter.
25032 In these cases, we assume deduction succeeded, but don't
25033 actually infer any unifications. */
25035 if (!uses_template_parms (parm)
25036 && !template_args_equal (parm, arg))
25037 return unify_expression_unequal (explain_p, parm, arg);
25038 else
25039 return unify_success (explain_p);
25042 #undef RECUR_AND_CHECK_FAILURE
25044 /* Note that DECL can be defined in this translation unit, if
25045 required. */
25047 static void
25048 mark_definable (tree decl)
25050 tree clone;
25051 DECL_NOT_REALLY_EXTERN (decl) = 1;
25052 FOR_EACH_CLONE (clone, decl)
25053 DECL_NOT_REALLY_EXTERN (clone) = 1;
25056 /* Called if RESULT is explicitly instantiated, or is a member of an
25057 explicitly instantiated class. */
25059 void
25060 mark_decl_instantiated (tree result, int extern_p)
25062 SET_DECL_EXPLICIT_INSTANTIATION (result);
25064 /* If this entity has already been written out, it's too late to
25065 make any modifications. */
25066 if (TREE_ASM_WRITTEN (result))
25067 return;
25069 /* consteval functions are never emitted. */
25070 if (TREE_CODE (result) == FUNCTION_DECL
25071 && DECL_IMMEDIATE_FUNCTION_P (result))
25072 return;
25074 /* For anonymous namespace we don't need to do anything. */
25075 if (decl_internal_context_p (result))
25077 gcc_assert (!TREE_PUBLIC (result));
25078 return;
25081 if (TREE_CODE (result) != FUNCTION_DECL)
25082 /* The TREE_PUBLIC flag for function declarations will have been
25083 set correctly by tsubst. */
25084 TREE_PUBLIC (result) = 1;
25086 if (extern_p)
25088 DECL_EXTERNAL (result) = 1;
25089 DECL_NOT_REALLY_EXTERN (result) = 0;
25091 else
25093 mark_definable (result);
25094 mark_needed (result);
25095 /* Always make artificials weak. */
25096 if (DECL_ARTIFICIAL (result) && flag_weak)
25097 comdat_linkage (result);
25098 /* For WIN32 we also want to put explicit instantiations in
25099 linkonce sections. */
25100 else if (TREE_PUBLIC (result))
25101 maybe_make_one_only (result);
25102 if (TREE_CODE (result) == FUNCTION_DECL
25103 && DECL_TEMPLATE_INSTANTIATED (result))
25104 /* If the function has already been instantiated, clear DECL_EXTERNAL,
25105 since start_preparsed_function wouldn't have if we had an earlier
25106 extern explicit instantiation. */
25107 DECL_EXTERNAL (result) = 0;
25110 /* If EXTERN_P, then this function will not be emitted -- unless
25111 followed by an explicit instantiation, at which point its linkage
25112 will be adjusted. If !EXTERN_P, then this function will be
25113 emitted here. In neither circumstance do we want
25114 import_export_decl to adjust the linkage. */
25115 DECL_INTERFACE_KNOWN (result) = 1;
25118 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
25119 important template arguments. If any are missing, we check whether
25120 they're important by using error_mark_node for substituting into any
25121 args that were used for partial ordering (the ones between ARGS and END)
25122 and seeing if it bubbles up. */
25124 static bool
25125 check_undeduced_parms (tree targs, tree args, tree end)
25127 bool found = false;
25128 for (tree& targ : tree_vec_range (targs))
25129 if (targ == NULL_TREE)
25131 found = true;
25132 targ = error_mark_node;
25134 if (found)
25136 tree substed = tsubst_arg_types (args, targs, end, tf_none, NULL_TREE);
25137 if (substed == error_mark_node)
25138 return true;
25140 return false;
25143 /* Given two function templates PAT1 and PAT2, return:
25145 1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
25146 -1 if PAT2 is more specialized than PAT1.
25147 0 if neither is more specialized.
25149 LEN indicates the number of parameters we should consider
25150 (defaulted parameters should not be considered).
25152 The 1998 std underspecified function template partial ordering, and
25153 DR214 addresses the issue. We take pairs of arguments, one from
25154 each of the templates, and deduce them against each other. One of
25155 the templates will be more specialized if all the *other*
25156 template's arguments deduce against its arguments and at least one
25157 of its arguments *does* *not* deduce against the other template's
25158 corresponding argument. Deduction is done as for class templates.
25159 The arguments used in deduction have reference and top level cv
25160 qualifiers removed. Iff both arguments were originally reference
25161 types *and* deduction succeeds in both directions, an lvalue reference
25162 wins against an rvalue reference and otherwise the template
25163 with the more cv-qualified argument wins for that pairing (if
25164 neither is more cv-qualified, they both are equal). Unlike regular
25165 deduction, after all the arguments have been deduced in this way,
25166 we do *not* verify the deduced template argument values can be
25167 substituted into non-deduced contexts.
25169 The logic can be a bit confusing here, because we look at deduce1 and
25170 targs1 to see if pat2 is at least as specialized, and vice versa; if we
25171 can find template arguments for pat1 to make arg1 look like arg2, that
25172 means that arg2 is at least as specialized as arg1. */
25175 more_specialized_fn (tree pat1, tree pat2, int len)
25177 tree decl1 = DECL_TEMPLATE_RESULT (pat1);
25178 tree decl2 = DECL_TEMPLATE_RESULT (pat2);
25179 tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
25180 tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
25181 tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
25182 tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
25183 tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
25184 tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
25185 tree origs1, origs2;
25186 bool lose1 = false;
25187 bool lose2 = false;
25189 /* Remove the this parameter from non-static member functions. If
25190 one is a non-static member function and the other is not a static
25191 member function, remove the first parameter from that function
25192 also. This situation occurs for operator functions where we
25193 locate both a member function (with this pointer) and non-member
25194 operator (with explicit first operand). */
25195 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
25197 len--; /* LEN is the number of significant arguments for DECL1 */
25198 args1 = TREE_CHAIN (args1);
25199 if (!DECL_STATIC_FUNCTION_P (decl2))
25200 args2 = TREE_CHAIN (args2);
25202 else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
25204 args2 = TREE_CHAIN (args2);
25205 if (!DECL_STATIC_FUNCTION_P (decl1))
25207 len--;
25208 args1 = TREE_CHAIN (args1);
25212 /* If only one is a conversion operator, they are unordered. */
25213 if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
25214 return 0;
25216 /* Consider the return type for a conversion function */
25217 if (DECL_CONV_FN_P (decl1))
25219 args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
25220 args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
25221 len++;
25224 processing_template_decl++;
25226 origs1 = args1;
25227 origs2 = args2;
25229 while (len--
25230 /* Stop when an ellipsis is seen. */
25231 && args1 != NULL_TREE && args2 != NULL_TREE)
25233 tree arg1 = TREE_VALUE (args1);
25234 tree arg2 = TREE_VALUE (args2);
25235 int deduce1, deduce2;
25236 int quals1 = -1;
25237 int quals2 = -1;
25238 int ref1 = 0;
25239 int ref2 = 0;
25241 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
25242 && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25244 /* When both arguments are pack expansions, we need only
25245 unify the patterns themselves. */
25246 arg1 = PACK_EXPANSION_PATTERN (arg1);
25247 arg2 = PACK_EXPANSION_PATTERN (arg2);
25249 /* This is the last comparison we need to do. */
25250 len = 0;
25253 if (TYPE_REF_P (arg1))
25255 ref1 = TYPE_REF_IS_RVALUE (arg1) + 1;
25256 arg1 = TREE_TYPE (arg1);
25257 quals1 = cp_type_quals (arg1);
25260 if (TYPE_REF_P (arg2))
25262 ref2 = TYPE_REF_IS_RVALUE (arg2) + 1;
25263 arg2 = TREE_TYPE (arg2);
25264 quals2 = cp_type_quals (arg2);
25267 arg1 = TYPE_MAIN_VARIANT (arg1);
25268 arg2 = TYPE_MAIN_VARIANT (arg2);
25270 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
25272 int i, len2 = remaining_arguments (args2);
25273 tree parmvec = make_tree_vec (1);
25274 tree argvec = make_tree_vec (len2);
25275 tree ta = args2;
25277 /* Setup the parameter vector, which contains only ARG1. */
25278 TREE_VEC_ELT (parmvec, 0) = arg1;
25280 /* Setup the argument vector, which contains the remaining
25281 arguments. */
25282 for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
25283 TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
25285 deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
25286 argvec, DEDUCE_EXACT,
25287 /*subr=*/true, /*explain_p=*/false)
25288 == 0);
25290 /* We cannot deduce in the other direction, because ARG1 is
25291 a pack expansion but ARG2 is not. */
25292 deduce2 = 0;
25294 else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25296 int i, len1 = remaining_arguments (args1);
25297 tree parmvec = make_tree_vec (1);
25298 tree argvec = make_tree_vec (len1);
25299 tree ta = args1;
25301 /* Setup the parameter vector, which contains only ARG1. */
25302 TREE_VEC_ELT (parmvec, 0) = arg2;
25304 /* Setup the argument vector, which contains the remaining
25305 arguments. */
25306 for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
25307 TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
25309 deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
25310 argvec, DEDUCE_EXACT,
25311 /*subr=*/true, /*explain_p=*/false)
25312 == 0);
25314 /* We cannot deduce in the other direction, because ARG2 is
25315 a pack expansion but ARG1 is not.*/
25316 deduce1 = 0;
25319 else
25321 /* The normal case, where neither argument is a pack
25322 expansion. */
25323 deduce1 = (unify (tparms1, targs1, arg1, arg2,
25324 UNIFY_ALLOW_NONE, /*explain_p=*/false)
25325 == 0);
25326 deduce2 = (unify (tparms2, targs2, arg2, arg1,
25327 UNIFY_ALLOW_NONE, /*explain_p=*/false)
25328 == 0);
25331 /* If we couldn't deduce arguments for tparms1 to make arg1 match
25332 arg2, then arg2 is not as specialized as arg1. */
25333 if (!deduce1)
25334 lose2 = true;
25335 if (!deduce2)
25336 lose1 = true;
25338 /* "If, for a given type, deduction succeeds in both directions
25339 (i.e., the types are identical after the transformations above)
25340 and both P and A were reference types (before being replaced with
25341 the type referred to above):
25342 - if the type from the argument template was an lvalue reference and
25343 the type from the parameter template was not, the argument type is
25344 considered to be more specialized than the other; otherwise,
25345 - if the type from the argument template is more cv-qualified
25346 than the type from the parameter template (as described above),
25347 the argument type is considered to be more specialized than the other;
25348 otherwise,
25349 - neither type is more specialized than the other." */
25351 if (deduce1 && deduce2)
25353 if (ref1 && ref2 && ref1 != ref2)
25355 if (ref1 > ref2)
25356 lose1 = true;
25357 else
25358 lose2 = true;
25360 else if (quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
25362 if ((quals1 & quals2) == quals2)
25363 lose2 = true;
25364 if ((quals1 & quals2) == quals1)
25365 lose1 = true;
25369 if (lose1 && lose2)
25370 /* We've failed to deduce something in either direction.
25371 These must be unordered. */
25372 break;
25374 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
25375 || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25376 /* We have already processed all of the arguments in our
25377 handing of the pack expansion type. */
25378 len = 0;
25380 args1 = TREE_CHAIN (args1);
25381 args2 = TREE_CHAIN (args2);
25384 /* "In most cases, all template parameters must have values in order for
25385 deduction to succeed, but for partial ordering purposes a template
25386 parameter may remain without a value provided it is not used in the
25387 types being used for partial ordering."
25389 Thus, if we are missing any of the targs1 we need to substitute into
25390 origs1, then pat2 is not as specialized as pat1. This can happen when
25391 there is a nondeduced context. */
25392 if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
25393 lose2 = true;
25394 if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
25395 lose1 = true;
25397 processing_template_decl--;
25399 /* If both deductions succeed, the partial ordering selects the more
25400 constrained template. */
25401 /* P2113: If the corresponding template-parameters of the
25402 template-parameter-lists are not equivalent ([temp.over.link]) or if
25403 the function parameters that positionally correspond between the two
25404 templates are not of the same type, neither template is more
25405 specialized than the other. */
25406 if (!lose1 && !lose2
25407 && comp_template_parms (DECL_TEMPLATE_PARMS (pat1),
25408 DECL_TEMPLATE_PARMS (pat2))
25409 && compparms (origs1, origs2))
25411 int winner = more_constrained (decl1, decl2);
25412 if (winner > 0)
25413 lose2 = true;
25414 else if (winner < 0)
25415 lose1 = true;
25418 /* All things being equal, if the next argument is a pack expansion
25419 for one function but not for the other, prefer the
25420 non-variadic function. FIXME this is bogus; see c++/41958. */
25421 if (lose1 == lose2
25422 && args1 && TREE_VALUE (args1)
25423 && args2 && TREE_VALUE (args2))
25425 lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
25426 lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
25429 if (lose1 == lose2)
25430 return 0;
25431 else if (!lose1)
25432 return 1;
25433 else
25434 return -1;
25437 /* Determine which of two partial specializations of TMPL is more
25438 specialized.
25440 PAT1 is a TREE_LIST whose TREE_VALUE is the TEMPLATE_DECL corresponding
25441 to the first partial specialization. The TREE_PURPOSE is the
25442 innermost set of template parameters for the partial
25443 specialization. PAT2 is similar, but for the second template.
25445 Return 1 if the first partial specialization is more specialized;
25446 -1 if the second is more specialized; 0 if neither is more
25447 specialized.
25449 See [temp.class.order] for information about determining which of
25450 two templates is more specialized. */
25452 static int
25453 more_specialized_partial_spec (tree tmpl, tree pat1, tree pat2)
25455 tree targs;
25456 int winner = 0;
25457 bool any_deductions = false;
25459 tree tmpl1 = TREE_VALUE (pat1);
25460 tree tmpl2 = TREE_VALUE (pat2);
25461 tree specargs1 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl1)));
25462 tree specargs2 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl2)));
25464 /* Just like what happens for functions, if we are ordering between
25465 different template specializations, we may encounter dependent
25466 types in the arguments, and we need our dependency check functions
25467 to behave correctly. */
25468 ++processing_template_decl;
25469 targs = get_partial_spec_bindings (tmpl, tmpl1, specargs2);
25470 if (targs)
25472 --winner;
25473 any_deductions = true;
25476 targs = get_partial_spec_bindings (tmpl, tmpl2, specargs1);
25477 if (targs)
25479 ++winner;
25480 any_deductions = true;
25482 --processing_template_decl;
25484 /* If both deductions succeed, the partial ordering selects the more
25485 constrained template. */
25486 if (!winner && any_deductions)
25487 winner = more_constrained (tmpl1, tmpl2);
25489 /* In the case of a tie where at least one of the templates
25490 has a parameter pack at the end, the template with the most
25491 non-packed parameters wins. */
25492 if (winner == 0
25493 && any_deductions
25494 && (template_args_variadic_p (TREE_PURPOSE (pat1))
25495 || template_args_variadic_p (TREE_PURPOSE (pat2))))
25497 tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
25498 tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
25499 int len1 = TREE_VEC_LENGTH (args1);
25500 int len2 = TREE_VEC_LENGTH (args2);
25502 /* We don't count the pack expansion at the end. */
25503 if (template_args_variadic_p (TREE_PURPOSE (pat1)))
25504 --len1;
25505 if (template_args_variadic_p (TREE_PURPOSE (pat2)))
25506 --len2;
25508 if (len1 > len2)
25509 return 1;
25510 else if (len1 < len2)
25511 return -1;
25514 return winner;
25517 /* Return the template arguments that will produce the function signature
25518 DECL from the function template FN, with the explicit template
25519 arguments EXPLICIT_ARGS. If CHECK_RETTYPE is true, the return type must
25520 also match. Return NULL_TREE if no satisfactory arguments could be
25521 found. */
25523 static tree
25524 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
25526 int ntparms = DECL_NTPARMS (fn);
25527 tree targs = make_tree_vec (ntparms);
25528 tree decl_type = TREE_TYPE (decl);
25529 tree decl_arg_types;
25530 tree *args;
25531 unsigned int nargs, ix;
25532 tree arg;
25534 gcc_assert (decl != DECL_TEMPLATE_RESULT (fn));
25536 /* Never do unification on the 'this' parameter. */
25537 decl_arg_types = skip_artificial_parms_for (decl,
25538 TYPE_ARG_TYPES (decl_type));
25540 nargs = list_length (decl_arg_types);
25541 args = XALLOCAVEC (tree, nargs);
25542 for (arg = decl_arg_types, ix = 0;
25543 arg != NULL_TREE;
25544 arg = TREE_CHAIN (arg), ++ix)
25545 args[ix] = TREE_VALUE (arg);
25547 if (fn_type_unification (fn, explicit_args, targs,
25548 args, ix,
25549 (check_rettype || DECL_CONV_FN_P (fn)
25550 ? TREE_TYPE (decl_type) : NULL_TREE),
25551 DEDUCE_EXACT, LOOKUP_NORMAL, NULL,
25552 /*explain_p=*/false,
25553 /*decltype*/false)
25554 == error_mark_node)
25555 return NULL_TREE;
25557 return targs;
25560 /* Return the innermost template arguments that, when applied to a partial
25561 specialization SPEC_TMPL of TMPL, yield the ARGS.
25563 For example, suppose we have:
25565 template <class T, class U> struct S {};
25566 template <class T> struct S<T*, int> {};
25568 Then, suppose we want to get `S<double*, int>'. SPEC_TMPL will be the
25569 partial specialization and the ARGS will be {double*, int}. The resulting
25570 vector will be {double}, indicating that `T' is bound to `double'. */
25572 static tree
25573 get_partial_spec_bindings (tree tmpl, tree spec_tmpl, tree args)
25575 tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (spec_tmpl);
25576 tree spec_args
25577 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (spec_tmpl)));
25578 int i, ntparms = TREE_VEC_LENGTH (tparms);
25579 tree deduced_args;
25580 tree innermost_deduced_args;
25582 innermost_deduced_args = make_tree_vec (ntparms);
25583 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
25585 deduced_args = copy_node (args);
25586 SET_TMPL_ARGS_LEVEL (deduced_args,
25587 TMPL_ARGS_DEPTH (deduced_args),
25588 innermost_deduced_args);
25590 else
25591 deduced_args = innermost_deduced_args;
25593 bool tried_array_deduction = (cxx_dialect < cxx17);
25594 again:
25595 if (unify (tparms, deduced_args,
25596 INNERMOST_TEMPLATE_ARGS (spec_args),
25597 INNERMOST_TEMPLATE_ARGS (args),
25598 UNIFY_ALLOW_NONE, /*explain_p=*/false))
25599 return NULL_TREE;
25601 for (i = 0; i < ntparms; ++i)
25602 if (! TREE_VEC_ELT (innermost_deduced_args, i))
25604 if (!tried_array_deduction)
25606 try_array_deduction (tparms, innermost_deduced_args,
25607 INNERMOST_TEMPLATE_ARGS (spec_args));
25608 tried_array_deduction = true;
25609 if (TREE_VEC_ELT (innermost_deduced_args, i))
25610 goto again;
25612 return NULL_TREE;
25615 if (!push_tinst_level (spec_tmpl, deduced_args))
25617 excessive_deduction_depth = true;
25618 return NULL_TREE;
25621 /* Verify that nondeduced template arguments agree with the type
25622 obtained from argument deduction.
25624 For example:
25626 struct A { typedef int X; };
25627 template <class T, class U> struct C {};
25628 template <class T> struct C<T, typename T::X> {};
25630 Then with the instantiation `C<A, int>', we can deduce that
25631 `T' is `A' but unify () does not check whether `typename T::X'
25632 is `int'. */
25633 spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
25635 if (spec_args != error_mark_node)
25636 spec_args = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
25637 INNERMOST_TEMPLATE_ARGS (spec_args),
25638 tmpl, tf_none, false);
25640 pop_tinst_level ();
25642 if (spec_args == error_mark_node
25643 /* We only need to check the innermost arguments; the other
25644 arguments will always agree. */
25645 || !comp_template_args_porder (INNERMOST_TEMPLATE_ARGS (spec_args),
25646 INNERMOST_TEMPLATE_ARGS (args)))
25647 return NULL_TREE;
25649 /* Now that we have bindings for all of the template arguments,
25650 ensure that the arguments deduced for the template template
25651 parameters have compatible template parameter lists. See the use
25652 of template_template_parm_bindings_ok_p in fn_type_unification
25653 for more information. */
25654 if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
25655 return NULL_TREE;
25657 return deduced_args;
25660 // Compare two function templates T1 and T2 by deducing bindings
25661 // from one against the other. If both deductions succeed, compare
25662 // constraints to see which is more constrained.
25663 static int
25664 more_specialized_inst (tree t1, tree t2)
25666 int fate = 0;
25667 int count = 0;
25669 if (get_bindings (t1, DECL_TEMPLATE_RESULT (t2), NULL_TREE, true))
25671 --fate;
25672 ++count;
25675 if (get_bindings (t2, DECL_TEMPLATE_RESULT (t1), NULL_TREE, true))
25677 ++fate;
25678 ++count;
25681 // If both deductions succeed, then one may be more constrained.
25682 if (count == 2 && fate == 0)
25683 fate = more_constrained (t1, t2);
25685 return fate;
25688 /* TEMPLATES is a TREE_LIST. Each TREE_VALUE is a TEMPLATE_DECL.
25689 Return the TREE_LIST node with the most specialized template, if
25690 any. If there is no most specialized template, the error_mark_node
25691 is returned.
25693 Note that this function does not look at, or modify, the
25694 TREE_PURPOSE or TREE_TYPE of any of the nodes. Since the node
25695 returned is one of the elements of INSTANTIATIONS, callers may
25696 store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
25697 and retrieve it from the value returned. */
25699 tree
25700 most_specialized_instantiation (tree templates)
25702 tree fn, champ;
25704 ++processing_template_decl;
25706 champ = templates;
25707 for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
25709 gcc_assert (TREE_VALUE (champ) != TREE_VALUE (fn));
25710 int fate = more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn));
25711 if (fate == -1)
25712 champ = fn;
25713 else if (!fate)
25715 /* Equally specialized, move to next function. If there
25716 is no next function, nothing's most specialized. */
25717 fn = TREE_CHAIN (fn);
25718 champ = fn;
25719 if (!fn)
25720 break;
25724 if (champ)
25725 /* Now verify that champ is better than everything earlier in the
25726 instantiation list. */
25727 for (fn = templates; fn != champ; fn = TREE_CHAIN (fn)) {
25728 if (more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn)) != 1)
25730 champ = NULL_TREE;
25731 break;
25735 processing_template_decl--;
25737 if (!champ)
25738 return error_mark_node;
25740 return champ;
25743 /* If DECL is a specialization of some template, return the most
25744 general such template. Otherwise, returns NULL_TREE.
25746 For example, given:
25748 template <class T> struct S { template <class U> void f(U); };
25750 if TMPL is `template <class U> void S<int>::f(U)' this will return
25751 the full template. This function will not trace past partial
25752 specializations, however. For example, given in addition:
25754 template <class T> struct S<T*> { template <class U> void f(U); };
25756 if TMPL is `template <class U> void S<int*>::f(U)' this will return
25757 `template <class T> template <class U> S<T*>::f(U)'. */
25759 tree
25760 most_general_template (tree decl)
25762 if (TREE_CODE (decl) != TEMPLATE_DECL)
25764 if (tree tinfo = get_template_info (decl))
25765 decl = TI_TEMPLATE (tinfo);
25766 /* The TI_TEMPLATE can be an IDENTIFIER_NODE for a
25767 template friend, or a FIELD_DECL for a capture pack. */
25768 if (TREE_CODE (decl) != TEMPLATE_DECL)
25769 return NULL_TREE;
25772 if (DECL_TEMPLATE_TEMPLATE_PARM_P (decl))
25773 return DECL_TI_TEMPLATE (DECL_TEMPLATE_RESULT (decl));
25775 /* Look for more and more general templates. */
25776 while (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
25778 /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
25779 (See cp-tree.h for details.) */
25780 if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
25781 break;
25783 if (CLASS_TYPE_P (TREE_TYPE (decl))
25784 && !TYPE_DECL_ALIAS_P (TYPE_NAME (TREE_TYPE (decl)))
25785 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
25786 break;
25788 /* Stop if we run into an explicitly specialized class template. */
25789 if (!DECL_NAMESPACE_SCOPE_P (decl)
25790 && DECL_CONTEXT (decl)
25791 && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
25792 break;
25794 decl = DECL_TI_TEMPLATE (decl);
25797 return decl;
25800 /* Return the most specialized of the template partial specializations
25801 which can produce TARGET, a specialization of some class or variable
25802 template. The value returned is a TEMPLATE_INFO; the TI_TEMPLATE is a
25803 TEMPLATE_DECL node corresponding to the partial specialization, while
25804 the TI_ARGS is the set of template arguments that must be substituted
25805 into the template pattern in order to generate TARGET. The result is
25806 cached in the TI_PARTIAL_INFO of the corresponding TEMPLATE_INFO unless
25807 RECHECKING is true.
25809 If the choice of partial specialization is ambiguous, a diagnostic
25810 is issued, and the error_mark_node is returned. If there are no
25811 partial specializations matching TARGET, then NULL_TREE is
25812 returned, indicating that the primary template should be used. */
25814 tree
25815 most_specialized_partial_spec (tree target, tsubst_flags_t complain,
25816 bool rechecking /* = false */)
25818 tree tinfo = NULL_TREE;
25819 tree tmpl, args, decl;
25820 if (TYPE_P (target))
25822 tinfo = CLASSTYPE_TEMPLATE_INFO (target);
25823 tmpl = TI_TEMPLATE (tinfo);
25824 args = TI_ARGS (tinfo);
25825 decl = TYPE_NAME (target);
25827 else if (TREE_CODE (target) == TEMPLATE_ID_EXPR)
25829 tmpl = TREE_OPERAND (target, 0);
25830 args = TREE_OPERAND (target, 1);
25831 decl = DECL_TEMPLATE_RESULT (tmpl);
25833 else if (VAR_P (target))
25835 tinfo = DECL_TEMPLATE_INFO (target);
25836 tmpl = TI_TEMPLATE (tinfo);
25837 args = TI_ARGS (tinfo);
25838 decl = target;
25840 else
25841 gcc_unreachable ();
25843 if (!PRIMARY_TEMPLATE_P (tmpl))
25844 return NULL_TREE;
25846 if (!rechecking
25847 && tinfo
25848 && (VAR_P (target) || COMPLETE_TYPE_P (target)))
25849 return TI_PARTIAL_INFO (tinfo);
25851 tree main_tmpl = most_general_template (tmpl);
25852 tree specs = DECL_TEMPLATE_SPECIALIZATIONS (main_tmpl);
25853 if (!specs)
25854 /* There are no partial specializations of this template. */
25855 return NULL_TREE;
25857 push_access_scope_guard pas (decl);
25858 deferring_access_check_sentinel acs (dk_no_deferred);
25860 /* For determining which partial specialization to use, only the
25861 innermost args are interesting. */
25862 tree outer_args = NULL_TREE;
25863 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
25865 outer_args = strip_innermost_template_args (args, 1);
25866 args = INNERMOST_TEMPLATE_ARGS (args);
25869 /* The caller hasn't called push_to_top_level yet, but we need
25870 get_partial_spec_bindings to be done in non-template context so that we'll
25871 fully resolve everything. */
25872 processing_template_decl_sentinel ptds;
25874 tree list = NULL_TREE;
25875 for (tree t = specs; t; t = TREE_CHAIN (t))
25877 const tree ospec_tmpl = TREE_VALUE (t);
25879 tree spec_tmpl;
25880 if (outer_args)
25882 /* Substitute in the template args from the enclosing class. */
25883 ++processing_template_decl;
25884 spec_tmpl = tsubst (ospec_tmpl, outer_args, tf_none, NULL_TREE);
25885 --processing_template_decl;
25886 if (spec_tmpl == error_mark_node)
25887 return error_mark_node;
25889 else
25890 spec_tmpl = ospec_tmpl;
25892 tree spec_args = get_partial_spec_bindings (tmpl, spec_tmpl, args);
25893 if (spec_args)
25895 if (outer_args)
25896 spec_args = add_to_template_args (outer_args, spec_args);
25898 /* Keep the candidate only if its constraints are satisfied. */
25899 if (constraints_satisfied_p (ospec_tmpl, spec_args))
25900 list = tree_cons (spec_args, ospec_tmpl, list);
25904 if (! list)
25905 return NULL_TREE;
25907 tree champ = list;
25908 bool ambiguous_p = false;
25909 for (tree t = TREE_CHAIN (list); t; t = TREE_CHAIN (t))
25911 int fate = more_specialized_partial_spec (tmpl, champ, t);
25912 if (fate == 1)
25914 else
25916 if (fate == 0)
25918 t = TREE_CHAIN (t);
25919 if (! t)
25921 ambiguous_p = true;
25922 break;
25925 champ = t;
25929 if (!ambiguous_p)
25930 for (tree t = list; t && t != champ; t = TREE_CHAIN (t))
25932 int fate = more_specialized_partial_spec (tmpl, champ, t);
25933 if (fate != 1)
25935 ambiguous_p = true;
25936 break;
25940 if (ambiguous_p)
25942 const char *str;
25943 char *spaces = NULL;
25944 if (!(complain & tf_error))
25945 return error_mark_node;
25946 if (TYPE_P (target))
25947 error ("ambiguous template instantiation for %q#T", target);
25948 else
25949 error ("ambiguous template instantiation for %q#D", target);
25950 str = ngettext ("candidate is:", "candidates are:", list_length (list));
25951 for (tree t = list; t; t = TREE_CHAIN (t))
25953 tree subst = build_tree_list (TREE_VALUE (t), TREE_PURPOSE (t));
25954 inform (DECL_SOURCE_LOCATION (TREE_VALUE (t)),
25955 "%s %#qS", spaces ? spaces : str, subst);
25956 spaces = spaces ? spaces : get_spaces (str);
25958 free (spaces);
25959 return error_mark_node;
25962 tree result = build_template_info (TREE_VALUE (champ), TREE_PURPOSE (champ));
25963 if (!rechecking && tinfo)
25964 TI_PARTIAL_INFO (tinfo) = result;
25965 return result;
25968 /* Explicitly instantiate DECL. */
25970 void
25971 do_decl_instantiation (tree decl, tree storage)
25973 tree result = NULL_TREE;
25974 int extern_p = 0;
25976 if (!decl || decl == error_mark_node)
25977 /* An error occurred, for which grokdeclarator has already issued
25978 an appropriate message. */
25979 return;
25980 else if (! DECL_LANG_SPECIFIC (decl))
25982 error ("explicit instantiation of non-template %q#D", decl);
25983 return;
25985 else if (DECL_DECLARED_CONCEPT_P (decl))
25987 if (VAR_P (decl))
25988 error ("explicit instantiation of variable concept %q#D", decl);
25989 else
25990 error ("explicit instantiation of function concept %q#D", decl);
25991 return;
25994 bool var_templ = (DECL_TEMPLATE_INFO (decl)
25995 && variable_template_p (DECL_TI_TEMPLATE (decl)));
25997 if (VAR_P (decl) && !var_templ)
25999 /* There is an asymmetry here in the way VAR_DECLs and
26000 FUNCTION_DECLs are handled by grokdeclarator. In the case of
26001 the latter, the DECL we get back will be marked as a
26002 template instantiation, and the appropriate
26003 DECL_TEMPLATE_INFO will be set up. This does not happen for
26004 VAR_DECLs so we do the lookup here. Probably, grokdeclarator
26005 should handle VAR_DECLs as it currently handles
26006 FUNCTION_DECLs. */
26007 if (!DECL_CLASS_SCOPE_P (decl))
26009 error ("%qD is not a static data member of a class template", decl);
26010 return;
26012 result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
26013 if (!result || !VAR_P (result))
26015 error ("no matching template for %qD found", decl);
26016 return;
26018 if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
26020 error ("type %qT for explicit instantiation %qD does not match "
26021 "declared type %qT", TREE_TYPE (result), decl,
26022 TREE_TYPE (decl));
26023 return;
26026 else if (TREE_CODE (decl) != FUNCTION_DECL && !var_templ)
26028 error ("explicit instantiation of %q#D", decl);
26029 return;
26031 else
26032 result = decl;
26034 /* Check for various error cases. Note that if the explicit
26035 instantiation is valid the RESULT will currently be marked as an
26036 *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
26037 until we get here. */
26039 if (DECL_TEMPLATE_SPECIALIZATION (result))
26041 /* DR 259 [temp.spec].
26043 Both an explicit instantiation and a declaration of an explicit
26044 specialization shall not appear in a program unless the explicit
26045 instantiation follows a declaration of the explicit specialization.
26047 For a given set of template parameters, if an explicit
26048 instantiation of a template appears after a declaration of an
26049 explicit specialization for that template, the explicit
26050 instantiation has no effect. */
26051 return;
26053 else if (DECL_EXPLICIT_INSTANTIATION (result))
26055 /* [temp.spec]
26057 No program shall explicitly instantiate any template more
26058 than once.
26060 We check DECL_NOT_REALLY_EXTERN so as not to complain when
26061 the first instantiation was `extern' and the second is not,
26062 and EXTERN_P for the opposite case. */
26063 if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
26064 permerror (input_location, "duplicate explicit instantiation of %q#D", result);
26065 /* If an "extern" explicit instantiation follows an ordinary
26066 explicit instantiation, the template is instantiated. */
26067 if (extern_p)
26068 return;
26070 else if (!DECL_IMPLICIT_INSTANTIATION (result))
26072 error ("no matching template for %qD found", result);
26073 return;
26075 else if (!DECL_TEMPLATE_INFO (result))
26077 permerror (input_location, "explicit instantiation of non-template %q#D", result);
26078 return;
26081 if (storage == NULL_TREE)
26083 else if (storage == ridpointers[(int) RID_EXTERN])
26085 if (cxx_dialect == cxx98)
26086 pedwarn (input_location, OPT_Wpedantic,
26087 "ISO C++ 1998 forbids the use of %<extern%> on explicit "
26088 "instantiations");
26089 extern_p = 1;
26091 else
26092 error ("storage class %qD applied to template instantiation", storage);
26094 check_explicit_instantiation_namespace (result);
26095 mark_decl_instantiated (result, extern_p);
26096 if (! extern_p)
26097 instantiate_decl (result, /*defer_ok=*/true,
26098 /*expl_inst_class_mem_p=*/false);
26101 static void
26102 mark_class_instantiated (tree t, int extern_p)
26104 SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
26105 SET_CLASSTYPE_INTERFACE_KNOWN (t);
26106 CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
26107 TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
26108 if (! extern_p)
26110 CLASSTYPE_DEBUG_REQUESTED (t) = 1;
26111 rest_of_type_compilation (t, 1);
26115 /* Perform an explicit instantiation of template class T. STORAGE, if
26116 non-null, is the RID for extern, inline or static. COMPLAIN is
26117 nonzero if this is called from the parser, zero if called recursively,
26118 since the standard is unclear (as detailed below). */
26120 void
26121 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
26123 if (!(CLASS_TYPE_P (t) && CLASSTYPE_TEMPLATE_INFO (t)))
26125 if (tree ti = TYPE_TEMPLATE_INFO (t))
26126 error ("explicit instantiation of non-class template %qD",
26127 TI_TEMPLATE (ti));
26128 else
26129 error ("explicit instantiation of non-template type %qT", t);
26130 return;
26133 complete_type (t);
26135 if (!COMPLETE_TYPE_P (t))
26137 if (complain & tf_error)
26138 error ("explicit instantiation of %q#T before definition of template",
26140 return;
26143 /* At most one of these will be true. */
26144 bool extern_p = false;
26145 bool nomem_p = false;
26146 bool static_p = false;
26148 if (storage != NULL_TREE)
26150 if (storage == ridpointers[(int) RID_EXTERN])
26152 if (cxx_dialect == cxx98)
26153 pedwarn (input_location, OPT_Wpedantic,
26154 "ISO C++ 1998 forbids the use of %<extern%> on "
26155 "explicit instantiations");
26157 else
26158 pedwarn (input_location, OPT_Wpedantic,
26159 "ISO C++ forbids the use of %qE"
26160 " on explicit instantiations", storage);
26162 if (storage == ridpointers[(int) RID_INLINE])
26163 nomem_p = true;
26164 else if (storage == ridpointers[(int) RID_EXTERN])
26165 extern_p = true;
26166 else if (storage == ridpointers[(int) RID_STATIC])
26167 static_p = true;
26168 else
26169 error ("storage class %qD applied to template instantiation",
26170 storage);
26173 if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
26174 /* DR 259 [temp.spec].
26176 Both an explicit instantiation and a declaration of an explicit
26177 specialization shall not appear in a program unless the
26178 explicit instantiation follows a declaration of the explicit
26179 specialization.
26181 For a given set of template parameters, if an explicit
26182 instantiation of a template appears after a declaration of an
26183 explicit specialization for that template, the explicit
26184 instantiation has no effect. */
26185 return;
26187 if (CLASSTYPE_EXPLICIT_INSTANTIATION (t) && !CLASSTYPE_INTERFACE_ONLY (t))
26189 /* We've already instantiated the template. */
26191 /* [temp.spec]
26193 No program shall explicitly instantiate any template more
26194 than once.
26196 If EXTERN_P then this is ok. */
26197 if (!extern_p && (complain & tf_error))
26198 permerror (input_location,
26199 "duplicate explicit instantiation of %q#T", t);
26201 return;
26204 check_explicit_instantiation_namespace (TYPE_NAME (t));
26205 mark_class_instantiated (t, extern_p);
26207 if (nomem_p)
26208 return;
26210 /* In contrast to implicit instantiation, where only the
26211 declarations, and not the definitions, of members are
26212 instantiated, we have here:
26214 [temp.explicit]
26216 An explicit instantiation that names a class template
26217 specialization is also an explicit instantiation of the same
26218 kind (declaration or definition) of each of its members (not
26219 including members inherited from base classes and members
26220 that are templates) that has not been previously explicitly
26221 specialized in the translation unit containing the explicit
26222 instantiation, provided that the associated constraints, if
26223 any, of that member are satisfied by the template arguments
26224 of the explicit instantiation. */
26225 for (tree fld = TYPE_FIELDS (t); fld; fld = DECL_CHAIN (fld))
26226 if ((VAR_P (fld)
26227 || (TREE_CODE (fld) == FUNCTION_DECL
26228 && !static_p
26229 && user_provided_p (fld)))
26230 && DECL_TEMPLATE_INSTANTIATION (fld)
26231 && constraints_satisfied_p (fld))
26233 mark_decl_instantiated (fld, extern_p);
26234 if (! extern_p)
26235 instantiate_decl (fld, /*defer_ok=*/true,
26236 /*expl_inst_class_mem_p=*/true);
26238 else if (DECL_IMPLICIT_TYPEDEF_P (fld))
26240 tree type = TREE_TYPE (fld);
26242 if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
26243 && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
26244 do_type_instantiation (type, storage, 0);
26248 /* Given a function DECL, which is a specialization of TMPL, modify
26249 DECL to be a re-instantiation of TMPL with the same template
26250 arguments. TMPL should be the template into which tsubst'ing
26251 should occur for DECL, not the most general template.
26253 One reason for doing this is a scenario like this:
26255 template <class T>
26256 void f(const T&, int i);
26258 void g() { f(3, 7); }
26260 template <class T>
26261 void f(const T& t, const int i) { }
26263 Note that when the template is first instantiated, with
26264 instantiate_template, the resulting DECL will have no name for the
26265 first parameter, and the wrong type for the second. So, when we go
26266 to instantiate the DECL, we regenerate it. */
26268 static void
26269 regenerate_decl_from_template (tree decl, tree tmpl, tree args)
26271 /* The arguments used to instantiate DECL, from the most general
26272 template. */
26273 tree code_pattern = DECL_TEMPLATE_RESULT (tmpl);
26275 /* Make sure that we can see identifiers, and compute access correctly. */
26276 push_access_scope (decl);
26278 if (TREE_CODE (decl) == FUNCTION_DECL)
26280 tree specs;
26281 int args_depth;
26282 int parms_depth;
26284 /* Don't bother with this for unique friends that can't be redeclared and
26285 might change type if regenerated (PR69836). */
26286 if (DECL_UNIQUE_FRIEND_P (decl))
26287 goto done;
26289 /* Use the source location of the definition. */
26290 DECL_SOURCE_LOCATION (decl) = DECL_SOURCE_LOCATION (tmpl);
26292 args_depth = TMPL_ARGS_DEPTH (args);
26293 parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
26294 if (args_depth > parms_depth)
26295 args = get_innermost_template_args (args, parms_depth);
26297 /* Instantiate a dynamic exception-specification. noexcept will be
26298 handled below. */
26299 if (tree raises = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (code_pattern)))
26300 if (TREE_VALUE (raises))
26302 specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
26303 args, tf_error, NULL_TREE,
26304 /*defer_ok*/false);
26305 if (specs && specs != error_mark_node)
26306 TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
26307 specs);
26310 /* Merge parameter declarations. */
26311 if (tree pattern_parm
26312 = skip_artificial_parms_for (code_pattern,
26313 DECL_ARGUMENTS (code_pattern)))
26315 tree *p = &DECL_ARGUMENTS (decl);
26316 for (int skip = num_artificial_parms_for (decl); skip; --skip)
26317 p = &DECL_CHAIN (*p);
26318 *p = tsubst_decl (pattern_parm, args, tf_error);
26319 for (tree t = *p; t; t = DECL_CHAIN (t))
26320 DECL_CONTEXT (t) = decl;
26323 if (DECL_CONTRACTS (decl))
26325 /* If we're regenerating a specialization, the contracts will have
26326 been copied from the most general template. Replace those with
26327 the ones from the actual specialization. */
26328 tree tmpl = DECL_TI_TEMPLATE (decl);
26329 if (DECL_TEMPLATE_SPECIALIZATION (tmpl))
26331 remove_contract_attributes (decl);
26332 copy_contract_attributes (decl, code_pattern);
26335 tsubst_contract_attributes (decl, args, tf_warning_or_error, code_pattern);
26338 /* Merge additional specifiers from the CODE_PATTERN. */
26339 if (DECL_DECLARED_INLINE_P (code_pattern)
26340 && !DECL_DECLARED_INLINE_P (decl))
26341 DECL_DECLARED_INLINE_P (decl) = 1;
26343 maybe_instantiate_noexcept (decl, tf_error);
26345 else if (VAR_P (decl))
26347 start_lambda_scope (decl);
26348 DECL_INITIAL (decl) =
26349 tsubst_init (DECL_INITIAL (code_pattern), decl, args,
26350 tf_error, DECL_TI_TEMPLATE (decl));
26351 finish_lambda_scope ();
26352 if (VAR_HAD_UNKNOWN_BOUND (decl))
26353 TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
26354 tf_error, DECL_TI_TEMPLATE (decl));
26356 else
26357 gcc_unreachable ();
26359 done:
26360 pop_access_scope (decl);
26363 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
26364 substituted to get DECL. */
26366 tree
26367 template_for_substitution (tree decl)
26369 tree tmpl = DECL_TI_TEMPLATE (decl);
26371 /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
26372 for the instantiation. This is not always the most general
26373 template. Consider, for example:
26375 template <class T>
26376 struct S { template <class U> void f();
26377 template <> void f<int>(); };
26379 and an instantiation of S<double>::f<int>. We want TD to be the
26380 specialization S<T>::f<int>, not the more general S<T>::f<U>. */
26381 while (/* An instantiation cannot have a definition, so we need a
26382 more general template. */
26383 DECL_TEMPLATE_INSTANTIATION (tmpl)
26384 /* We must also deal with friend templates. Given:
26386 template <class T> struct S {
26387 template <class U> friend void f() {};
26390 S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
26391 so far as the language is concerned, but that's still
26392 where we get the pattern for the instantiation from. On
26393 other hand, if the definition comes outside the class, say:
26395 template <class T> struct S {
26396 template <class U> friend void f();
26398 template <class U> friend void f() {}
26400 we don't need to look any further. That's what the check for
26401 DECL_INITIAL is for. */
26402 || (TREE_CODE (decl) == FUNCTION_DECL
26403 && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
26404 && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
26406 /* The present template, TD, should not be a definition. If it
26407 were a definition, we should be using it! Note that we
26408 cannot restructure the loop to just keep going until we find
26409 a template with a definition, since that might go too far if
26410 a specialization was declared, but not defined. */
26412 /* Fetch the more general template. */
26413 tmpl = DECL_TI_TEMPLATE (tmpl);
26416 return tmpl;
26419 /* Returns true if we need to instantiate this template instance even if we
26420 know we aren't going to emit it. */
26422 bool
26423 always_instantiate_p (tree decl)
26425 /* We always instantiate inline functions so that we can inline them. An
26426 explicit instantiation declaration prohibits implicit instantiation of
26427 non-inline functions. With high levels of optimization, we would
26428 normally inline non-inline functions -- but we're not allowed to do
26429 that for "extern template" functions. Therefore, we check
26430 DECL_DECLARED_INLINE_P, rather than possibly_inlined_p. */
26431 return ((TREE_CODE (decl) == FUNCTION_DECL
26432 && (DECL_DECLARED_INLINE_P (decl)
26433 || type_uses_auto (TREE_TYPE (TREE_TYPE (decl)))))
26434 /* And we need to instantiate static data members so that
26435 their initializers are available in integral constant
26436 expressions. */
26437 || (VAR_P (decl)
26438 && decl_maybe_constant_var_p (decl)));
26441 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
26442 instantiate it now, modifying TREE_TYPE (fn). Returns false on
26443 error, true otherwise. */
26445 bool
26446 maybe_instantiate_noexcept (tree fn, tsubst_flags_t complain)
26448 if (fn == error_mark_node)
26449 return false;
26451 /* Don't instantiate a noexcept-specification from template context. */
26452 if (processing_template_decl
26453 && (!flag_noexcept_type || type_dependent_expression_p (fn)))
26454 return true;
26456 tree fntype = TREE_TYPE (fn);
26457 tree spec = TYPE_RAISES_EXCEPTIONS (fntype);
26459 if ((!spec || UNEVALUATED_NOEXCEPT_SPEC_P (spec))
26460 && DECL_MAYBE_DELETED (fn))
26462 if (fn == current_function_decl)
26463 /* We're in start_preparsed_function, keep going. */
26464 return true;
26466 ++function_depth;
26467 maybe_synthesize_method (fn);
26468 --function_depth;
26469 return !DECL_DELETED_FN (fn);
26472 if (!spec || !TREE_PURPOSE (spec))
26473 return true;
26475 tree noex = TREE_PURPOSE (spec);
26476 if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
26477 && TREE_CODE (noex) != DEFERRED_PARSE)
26478 return true;
26480 tree orig_fn = NULL_TREE;
26481 /* For a member friend template we can get a TEMPLATE_DECL. Let's use
26482 its FUNCTION_DECL for the rest of this function -- push_access_scope
26483 doesn't accept TEMPLATE_DECLs. */
26484 if (DECL_FUNCTION_TEMPLATE_P (fn))
26486 orig_fn = fn;
26487 fn = DECL_TEMPLATE_RESULT (fn);
26490 if (DECL_CLONED_FUNCTION_P (fn))
26492 tree prime = DECL_CLONED_FUNCTION (fn);
26493 if (!maybe_instantiate_noexcept (prime, complain))
26494 return false;
26495 spec = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (prime));
26497 else if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
26499 static hash_set<tree>* fns = new hash_set<tree>;
26500 bool added = false;
26501 if (DEFERRED_NOEXCEPT_PATTERN (noex) == NULL_TREE)
26503 spec = get_defaulted_eh_spec (fn, complain);
26504 if (spec == error_mark_node)
26505 /* This might have failed because of an unparsed DMI, so
26506 let's try again later. */
26507 return false;
26509 else if (!(added = !fns->add (fn)))
26511 /* If hash_set::add returns true, the element was already there. */
26512 location_t loc = cp_expr_loc_or_loc (DEFERRED_NOEXCEPT_PATTERN (noex),
26513 DECL_SOURCE_LOCATION (fn));
26514 error_at (loc,
26515 "exception specification of %qD depends on itself",
26516 fn);
26517 spec = noexcept_false_spec;
26519 else if (push_tinst_level (fn))
26521 push_to_top_level ();
26522 push_access_scope (fn);
26523 push_deferring_access_checks (dk_no_deferred);
26524 input_location = DECL_SOURCE_LOCATION (fn);
26526 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
26527 && !DECL_LOCAL_DECL_P (fn))
26529 /* If needed, set current_class_ptr for the benefit of
26530 tsubst_copy/PARM_DECL. */
26531 tree this_parm = DECL_ARGUMENTS (fn);
26532 current_class_ptr = NULL_TREE;
26533 current_class_ref = cp_build_fold_indirect_ref (this_parm);
26534 current_class_ptr = this_parm;
26537 /* If this function is represented by a TEMPLATE_DECL, then
26538 the deferred noexcept-specification might still contain
26539 dependent types, even after substitution. And we need the
26540 dependency check functions to work in build_noexcept_spec. */
26541 if (orig_fn)
26542 ++processing_template_decl;
26544 /* Do deferred instantiation of the noexcept-specifier. */
26545 noex = tsubst_expr (DEFERRED_NOEXCEPT_PATTERN (noex),
26546 DEFERRED_NOEXCEPT_ARGS (noex),
26547 tf_warning_or_error, fn);
26549 /* Build up the noexcept-specification. */
26550 spec = build_noexcept_spec (noex, tf_warning_or_error);
26552 if (orig_fn)
26553 --processing_template_decl;
26555 pop_deferring_access_checks ();
26556 pop_access_scope (fn);
26557 pop_tinst_level ();
26558 pop_from_top_level ();
26560 else
26561 spec = noexcept_false_spec;
26563 if (added)
26564 fns->remove (fn);
26567 if (spec == error_mark_node)
26569 /* This failed with a hard error, so let's go with false. */
26570 gcc_assert (seen_error ());
26571 spec = noexcept_false_spec;
26574 TREE_TYPE (fn) = build_exception_variant (fntype, spec);
26575 if (orig_fn)
26576 TREE_TYPE (orig_fn) = TREE_TYPE (fn);
26578 return true;
26581 /* We're starting to process the function INST, an instantiation of PATTERN;
26582 add their parameters to local_specializations. */
26584 void
26585 register_parameter_specializations (tree pattern, tree inst)
26587 tree tmpl_parm = DECL_ARGUMENTS (pattern);
26588 tree spec_parm = DECL_ARGUMENTS (inst);
26589 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (inst))
26591 register_local_specialization (spec_parm, tmpl_parm);
26592 spec_parm = skip_artificial_parms_for (inst, spec_parm);
26593 tmpl_parm = skip_artificial_parms_for (pattern, tmpl_parm);
26595 for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
26597 if (!DECL_PACK_P (tmpl_parm))
26599 register_local_specialization (spec_parm, tmpl_parm);
26600 spec_parm = DECL_CHAIN (spec_parm);
26602 else
26604 /* Register the (value) argument pack as a specialization of
26605 TMPL_PARM, then move on. */
26606 tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
26607 register_local_specialization (argpack, tmpl_parm);
26610 gcc_assert (!spec_parm);
26613 /* Instantiate the body of D using PATTERN with ARGS. We have
26614 already determined PATTERN is the correct template to use.
26615 NESTED_P is true if this is a nested function, in which case
26616 PATTERN will be a FUNCTION_DECL not a TEMPLATE_DECL. */
26618 static void
26619 instantiate_body (tree pattern, tree args, tree d, bool nested_p)
26621 tree td = NULL_TREE;
26622 tree code_pattern = pattern;
26624 if (!nested_p)
26626 td = pattern;
26627 code_pattern = DECL_TEMPLATE_RESULT (td);
26629 else
26630 /* Only OMP reductions are nested. */
26631 gcc_checking_assert (DECL_OMP_DECLARE_REDUCTION_P (code_pattern));
26633 vec<tree> omp_privatization_save;
26634 if (current_function_decl)
26635 save_omp_privatization_clauses (omp_privatization_save);
26637 bool push_to_top = maybe_push_to_top_level (d);
26639 mark_template_arguments_used (pattern, args);
26641 if (VAR_P (d))
26643 /* The variable might be a lambda's extra scope, and that
26644 lambda's visibility depends on D's. */
26645 maybe_commonize_var (d);
26646 determine_visibility (d);
26649 /* Mark D as instantiated so that recursive calls to
26650 instantiate_decl do not try to instantiate it again. */
26651 DECL_TEMPLATE_INSTANTIATED (d) = 1;
26653 if (td)
26654 /* Regenerate the declaration in case the template has been modified
26655 by a subsequent redeclaration. */
26656 regenerate_decl_from_template (d, td, args);
26658 /* We already set the file and line above. Reset them now in case
26659 they changed as a result of calling regenerate_decl_from_template. */
26660 input_location = DECL_SOURCE_LOCATION (d);
26662 if (VAR_P (d))
26664 /* Clear out DECL_RTL; whatever was there before may not be right
26665 since we've reset the type of the declaration. */
26666 SET_DECL_RTL (d, NULL);
26667 DECL_IN_AGGR_P (d) = 0;
26669 /* The initializer is placed in DECL_INITIAL by
26670 regenerate_decl_from_template so we don't need to
26671 push/pop_access_scope again here. Pull it out so that
26672 cp_finish_decl can process it. */
26673 bool const_init = false;
26674 tree init = DECL_INITIAL (d);
26675 DECL_INITIAL (d) = NULL_TREE;
26676 DECL_INITIALIZED_P (d) = 0;
26678 /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
26679 initializer. That function will defer actual emission until
26680 we have a chance to determine linkage. */
26681 DECL_EXTERNAL (d) = 0;
26683 /* Enter the scope of D so that access-checking works correctly. */
26684 bool enter_context = DECL_CLASS_SCOPE_P (d);
26685 if (enter_context)
26686 push_nested_class (DECL_CONTEXT (d));
26688 const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
26689 cp_finish_decl (d, init, const_init, NULL_TREE, 0);
26691 if (enter_context)
26692 pop_nested_class ();
26694 else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
26695 synthesize_method (d);
26696 else if (TREE_CODE (d) == FUNCTION_DECL)
26698 /* Set up the list of local specializations. */
26699 local_specialization_stack lss (push_to_top ? lss_blank : lss_copy);
26700 tree block = NULL_TREE;
26702 /* Set up context. */
26703 if (nested_p)
26704 block = push_stmt_list ();
26705 else
26707 start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
26709 perform_instantiation_time_access_checks (code_pattern, args);
26712 /* Create substitution entries for the parameters. */
26713 register_parameter_specializations (code_pattern, d);
26715 /* Substitute into the body of the function. */
26716 if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
26717 tsubst_omp_udr (DECL_SAVED_TREE (code_pattern), args,
26718 tf_warning_or_error, d);
26719 else
26721 tsubst_stmt (DECL_SAVED_TREE (code_pattern), args,
26722 tf_warning_or_error, DECL_TI_TEMPLATE (d));
26724 /* Set the current input_location to the end of the function
26725 so that finish_function knows where we are. */
26726 input_location
26727 = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
26729 /* Remember if we saw an infinite loop in the template. */
26730 current_function_infinite_loop
26731 = DECL_STRUCT_FUNCTION (code_pattern)->language->infinite_loop;
26734 /* Finish the function. */
26735 if (nested_p)
26736 DECL_SAVED_TREE (d) = pop_stmt_list (block);
26737 else
26739 d = finish_function (/*inline_p=*/false);
26740 expand_or_defer_fn (d);
26743 if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
26744 cp_check_omp_declare_reduction (d);
26747 /* We're not deferring instantiation any more. */
26748 if (!nested_p)
26749 TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
26751 maybe_pop_from_top_level (push_to_top);
26753 if (current_function_decl)
26754 restore_omp_privatization_clauses (omp_privatization_save);
26757 /* Produce the definition of D, a _DECL generated from a template. If
26758 DEFER_OK is true, then we don't have to actually do the
26759 instantiation now; we just have to do it sometime. Normally it is
26760 an error if this is an explicit instantiation but D is undefined.
26761 EXPL_INST_CLASS_MEM_P is true iff D is a member of an explicitly
26762 instantiated class template. */
26764 tree
26765 instantiate_decl (tree d, bool defer_ok, bool expl_inst_class_mem_p)
26767 tree tmpl = DECL_TI_TEMPLATE (d);
26768 tree gen_args;
26769 tree args;
26770 tree td;
26771 tree code_pattern;
26772 tree spec;
26773 tree gen_tmpl;
26774 bool pattern_defined;
26775 location_t saved_loc = input_location;
26776 int saved_unevaluated_operand = cp_unevaluated_operand;
26777 int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
26778 bool external_p;
26779 bool deleted_p;
26781 /* This function should only be used to instantiate templates for
26782 functions and static member variables. */
26783 gcc_assert (VAR_OR_FUNCTION_DECL_P (d));
26785 /* A concept is never instantiated. */
26786 gcc_assert (!DECL_DECLARED_CONCEPT_P (d));
26788 gcc_checking_assert (!DECL_FUNCTION_SCOPE_P (d));
26790 if (modules_p ())
26791 /* We may have a pending instantiation of D itself. */
26792 lazy_load_pendings (d);
26794 /* Variables are never deferred; if instantiation is required, they
26795 are instantiated right away. That allows for better code in the
26796 case that an expression refers to the value of the variable --
26797 if the variable has a constant value the referring expression can
26798 take advantage of that fact. */
26799 if (VAR_P (d))
26800 defer_ok = false;
26802 /* Don't instantiate cloned functions. Instead, instantiate the
26803 functions they cloned. */
26804 if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
26805 d = DECL_CLONED_FUNCTION (d);
26807 if (DECL_TEMPLATE_INSTANTIATED (d)
26808 || TREE_TYPE (d) == error_mark_node
26809 || (TREE_CODE (d) == FUNCTION_DECL
26810 && DECL_DEFAULTED_FN (d) && DECL_INITIAL (d))
26811 || DECL_TEMPLATE_SPECIALIZATION (d))
26812 /* D has already been instantiated or explicitly specialized, so
26813 there's nothing for us to do here.
26815 It might seem reasonable to check whether or not D is an explicit
26816 instantiation, and, if so, stop here. But when an explicit
26817 instantiation is deferred until the end of the compilation,
26818 DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
26819 the instantiation. */
26820 return d;
26822 /* Check to see whether we know that this template will be
26823 instantiated in some other file, as with "extern template"
26824 extension. */
26825 external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
26827 /* In general, we do not instantiate such templates. */
26828 if (external_p && !always_instantiate_p (d))
26829 return d;
26831 gen_tmpl = most_general_template (tmpl);
26832 gen_args = DECL_TI_ARGS (d);
26834 /* We should already have the extra args. */
26835 gcc_checking_assert (tmpl == gen_tmpl
26836 || (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
26837 == TMPL_ARGS_DEPTH (gen_args)));
26838 /* And what's in the hash table should match D. */
26839 gcc_checking_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0))
26840 == d
26841 || spec == NULL_TREE);
26843 /* This needs to happen before any tsubsting. */
26844 if (! push_tinst_level (d))
26845 return d;
26847 auto_timevar tv (TV_TEMPLATE_INST);
26849 /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
26850 for the instantiation. */
26851 td = template_for_substitution (d);
26852 args = gen_args;
26854 if (variable_template_specialization_p (d))
26856 /* Look up an explicit specialization, if any. */
26857 tree partial_ti = most_specialized_partial_spec (d, tf_warning_or_error);
26858 if (partial_ti && partial_ti != error_mark_node)
26860 td = TI_TEMPLATE (partial_ti);
26861 args = TI_ARGS (partial_ti);
26865 code_pattern = DECL_TEMPLATE_RESULT (td);
26867 /* We should never be trying to instantiate a member of a class
26868 template or partial specialization. */
26869 gcc_assert (d != code_pattern);
26871 if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
26872 || DECL_TEMPLATE_SPECIALIZATION (td))
26873 /* In the case of a friend template whose definition is provided
26874 outside the class, we may have too many arguments. Drop the
26875 ones we don't need. The same is true for specializations. */
26876 args = get_innermost_template_args
26877 (args, TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (td)));
26879 if (TREE_CODE (d) == FUNCTION_DECL)
26881 deleted_p = DECL_DELETED_FN (code_pattern);
26882 pattern_defined = ((DECL_SAVED_TREE (code_pattern) != NULL_TREE
26883 && DECL_INITIAL (code_pattern) != error_mark_node)
26884 || DECL_DEFAULTED_FN (code_pattern)
26885 || deleted_p);
26887 else
26889 deleted_p = false;
26890 if (DECL_CLASS_SCOPE_P (code_pattern))
26891 pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
26892 else
26893 pattern_defined = ! DECL_EXTERNAL (code_pattern);
26896 /* We may be in the middle of deferred access check. Disable it now. */
26897 push_deferring_access_checks (dk_no_deferred);
26899 /* Unless an explicit instantiation directive has already determined
26900 the linkage of D, remember that a definition is available for
26901 this entity. */
26902 if (pattern_defined
26903 && !DECL_INTERFACE_KNOWN (d)
26904 && !DECL_NOT_REALLY_EXTERN (d))
26905 mark_definable (d);
26907 DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
26908 DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
26909 input_location = DECL_SOURCE_LOCATION (d);
26911 /* If D is a member of an explicitly instantiated class template,
26912 and no definition is available, treat it like an implicit
26913 instantiation. */
26914 if (!pattern_defined && expl_inst_class_mem_p
26915 && DECL_EXPLICIT_INSTANTIATION (d))
26917 /* Leave linkage flags alone on instantiations with anonymous
26918 visibility. */
26919 if (TREE_PUBLIC (d))
26921 DECL_NOT_REALLY_EXTERN (d) = 0;
26922 DECL_INTERFACE_KNOWN (d) = 0;
26924 SET_DECL_IMPLICIT_INSTANTIATION (d);
26927 /* Defer all other templates, unless we have been explicitly
26928 forbidden from doing so. */
26929 if (/* If there is no definition, we cannot instantiate the
26930 template. */
26931 ! pattern_defined
26932 /* If it's OK to postpone instantiation, do so. */
26933 || defer_ok
26934 /* If this is a static data member that will be defined
26935 elsewhere, we don't want to instantiate the entire data
26936 member, but we do want to instantiate the initializer so that
26937 we can substitute that elsewhere. */
26938 || (external_p && VAR_P (d))
26939 /* Handle here a deleted function too, avoid generating
26940 its body (c++/61080). */
26941 || deleted_p)
26943 /* The definition of the static data member is now required so
26944 we must substitute the initializer. */
26945 if (VAR_P (d)
26946 && !DECL_INITIAL (d)
26947 && DECL_INITIAL (code_pattern))
26949 tree ns;
26950 tree init;
26951 bool const_init = false;
26952 bool enter_context = DECL_CLASS_SCOPE_P (d);
26954 ns = decl_namespace_context (d);
26955 push_nested_namespace (ns);
26956 if (enter_context)
26957 push_nested_class (DECL_CONTEXT (d));
26958 init = tsubst_expr (DECL_INITIAL (code_pattern),
26959 args,
26960 tf_warning_or_error, NULL_TREE);
26961 /* If instantiating the initializer involved instantiating this
26962 again, don't call cp_finish_decl twice. */
26963 if (!DECL_INITIAL (d))
26965 /* Make sure the initializer is still constant, in case of
26966 circular dependency (template/instantiate6.C). */
26967 const_init
26968 = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
26969 cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
26970 /*asmspec_tree=*/NULL_TREE, 0);
26972 if (enter_context)
26973 pop_nested_class ();
26974 pop_nested_namespace (ns);
26977 /* We restore the source position here because it's used by
26978 add_pending_template. */
26979 input_location = saved_loc;
26981 if (at_eof && !pattern_defined
26982 && DECL_EXPLICIT_INSTANTIATION (d)
26983 && DECL_NOT_REALLY_EXTERN (d))
26984 /* [temp.explicit]
26986 The definition of a non-exported function template, a
26987 non-exported member function template, or a non-exported
26988 member function or static data member of a class template
26989 shall be present in every translation unit in which it is
26990 explicitly instantiated. */
26991 permerror (input_location, "explicit instantiation of %qD "
26992 "but no definition available", d);
26994 /* If we're in unevaluated context, we just wanted to get the
26995 constant value; this isn't an odr use, so don't queue
26996 a full instantiation. */
26997 if (!cp_unevaluated_operand
26998 /* ??? Historically, we have instantiated inline functions, even
26999 when marked as "extern template". */
27000 && !(external_p && VAR_P (d)))
27001 add_pending_template (d);
27003 else
27005 set_instantiating_module (d);
27006 if (variable_template_p (gen_tmpl))
27007 note_variable_template_instantiation (d);
27008 instantiate_body (td, args, d, false);
27011 pop_deferring_access_checks ();
27012 pop_tinst_level ();
27013 input_location = saved_loc;
27014 cp_unevaluated_operand = saved_unevaluated_operand;
27015 c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
27017 return d;
27020 /* Run through the list of templates that we wish we could
27021 instantiate, and instantiate any we can. RETRIES is the
27022 number of times we retry pending template instantiation. */
27024 void
27025 instantiate_pending_templates (int retries)
27027 int reconsider;
27028 location_t saved_loc = input_location;
27030 /* Instantiating templates may trigger vtable generation. This in turn
27031 may require further template instantiations. We place a limit here
27032 to avoid infinite loop. */
27033 if (pending_templates && retries >= max_tinst_depth)
27035 tree decl = pending_templates->tinst->maybe_get_node ();
27037 fatal_error (input_location,
27038 "template instantiation depth exceeds maximum of %d"
27039 " instantiating %q+D, possibly from virtual table generation"
27040 " (use %<-ftemplate-depth=%> to increase the maximum)",
27041 max_tinst_depth, decl);
27042 if (TREE_CODE (decl) == FUNCTION_DECL)
27043 /* Pretend that we defined it. */
27044 DECL_INITIAL (decl) = error_mark_node;
27045 return;
27050 struct pending_template **t = &pending_templates;
27051 struct pending_template *last = NULL;
27052 reconsider = 0;
27053 while (*t)
27055 tree instantiation = reopen_tinst_level ((*t)->tinst);
27056 bool complete = false;
27058 if (TYPE_P (instantiation))
27060 if (!COMPLETE_TYPE_P (instantiation))
27062 instantiate_class_template (instantiation);
27063 if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
27064 for (tree fld = TYPE_FIELDS (instantiation);
27065 fld; fld = TREE_CHAIN (fld))
27066 if ((VAR_P (fld)
27067 || (TREE_CODE (fld) == FUNCTION_DECL
27068 && !DECL_ARTIFICIAL (fld)))
27069 && DECL_TEMPLATE_INSTANTIATION (fld))
27070 instantiate_decl (fld,
27071 /*defer_ok=*/false,
27072 /*expl_inst_class_mem_p=*/false);
27074 if (COMPLETE_TYPE_P (instantiation))
27075 reconsider = 1;
27078 complete = COMPLETE_TYPE_P (instantiation);
27080 else
27082 if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
27083 && !DECL_TEMPLATE_INSTANTIATED (instantiation))
27085 instantiation
27086 = instantiate_decl (instantiation,
27087 /*defer_ok=*/false,
27088 /*expl_inst_class_mem_p=*/false);
27089 if (DECL_TEMPLATE_INSTANTIATED (instantiation))
27090 reconsider = 1;
27093 complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
27094 || DECL_TEMPLATE_INSTANTIATED (instantiation));
27097 if (complete)
27099 /* If INSTANTIATION has been instantiated, then we don't
27100 need to consider it again in the future. */
27101 struct pending_template *drop = *t;
27102 *t = (*t)->next;
27103 set_refcount_ptr (drop->tinst);
27104 pending_template_freelist ().free (drop);
27106 else
27108 last = *t;
27109 t = &(*t)->next;
27111 tinst_depth = 0;
27112 set_refcount_ptr (current_tinst_level);
27114 last_pending_template = last;
27116 while (reconsider);
27118 input_location = saved_loc;
27121 /* Substitute ARGVEC into T, which is a list of initializers for
27122 either base class or a non-static data member. The TREE_PURPOSEs
27123 are DECLs, and the TREE_VALUEs are the initializer values. Used by
27124 instantiate_decl. */
27126 static tree
27127 tsubst_initializer_list (tree t, tree argvec)
27129 tree inits = NULL_TREE;
27130 tree target_ctor = error_mark_node;
27132 for (; t; t = TREE_CHAIN (t))
27134 tree decl;
27135 tree init;
27136 tree expanded_bases = NULL_TREE;
27137 tree expanded_arguments = NULL_TREE;
27138 int i, len = 1;
27140 if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
27142 tree expr;
27143 tree arg;
27145 /* Expand the base class expansion type into separate base
27146 classes. */
27147 expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
27148 tf_warning_or_error,
27149 NULL_TREE);
27150 if (expanded_bases == error_mark_node)
27151 continue;
27153 /* We'll be building separate TREE_LISTs of arguments for
27154 each base. */
27155 len = TREE_VEC_LENGTH (expanded_bases);
27156 expanded_arguments = make_tree_vec (len);
27157 for (i = 0; i < len; i++)
27158 TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
27160 /* Build a dummy EXPR_PACK_EXPANSION that will be used to
27161 expand each argument in the TREE_VALUE of t. */
27162 expr = make_node (EXPR_PACK_EXPANSION);
27163 PACK_EXPANSION_LOCAL_P (expr) = true;
27164 PACK_EXPANSION_PARAMETER_PACKS (expr) =
27165 PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
27167 if (TREE_VALUE (t) == void_type_node)
27168 /* VOID_TYPE_NODE is used to indicate
27169 value-initialization. */
27171 for (i = 0; i < len; i++)
27172 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
27174 else
27176 /* Substitute parameter packs into each argument in the
27177 TREE_LIST. */
27178 in_base_initializer = 1;
27179 for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
27181 tree expanded_exprs;
27183 /* Expand the argument. */
27184 tree value;
27185 if (TREE_CODE (TREE_VALUE (arg)) == EXPR_PACK_EXPANSION)
27186 value = TREE_VALUE (arg);
27187 else
27189 value = expr;
27190 PACK_EXPANSION_PATTERN (value) = TREE_VALUE (arg);
27192 expanded_exprs
27193 = tsubst_pack_expansion (value, argvec,
27194 tf_warning_or_error,
27195 NULL_TREE);
27196 if (expanded_exprs == error_mark_node)
27197 continue;
27199 /* Prepend each of the expanded expressions to the
27200 corresponding TREE_LIST in EXPANDED_ARGUMENTS. */
27201 for (i = 0; i < len; i++)
27202 if (TREE_CODE (TREE_VALUE (arg)) == EXPR_PACK_EXPANSION)
27203 for (int j = 0; j < TREE_VEC_LENGTH (expanded_exprs); j++)
27204 TREE_VEC_ELT (expanded_arguments, i)
27205 = tree_cons (NULL_TREE,
27206 TREE_VEC_ELT (expanded_exprs, j),
27207 TREE_VEC_ELT (expanded_arguments, i));
27208 else
27209 TREE_VEC_ELT (expanded_arguments, i)
27210 = tree_cons (NULL_TREE,
27211 TREE_VEC_ELT (expanded_exprs, i),
27212 TREE_VEC_ELT (expanded_arguments, i));
27214 in_base_initializer = 0;
27216 /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
27217 since we built them backwards. */
27218 for (i = 0; i < len; i++)
27220 TREE_VEC_ELT (expanded_arguments, i) =
27221 nreverse (TREE_VEC_ELT (expanded_arguments, i));
27226 for (i = 0; i < len; ++i)
27228 if (expanded_bases)
27230 decl = TREE_VEC_ELT (expanded_bases, i);
27231 decl = expand_member_init (decl);
27232 init = TREE_VEC_ELT (expanded_arguments, i);
27234 else
27236 tree tmp;
27237 if (TYPE_P (TREE_PURPOSE (t)))
27238 decl = tsubst (TREE_PURPOSE (t), argvec,
27239 tf_warning_or_error, NULL_TREE);
27240 else
27241 decl = tsubst_expr (TREE_PURPOSE (t), argvec,
27242 tf_warning_or_error, NULL_TREE);
27244 decl = expand_member_init (decl);
27245 if (decl && !DECL_P (decl))
27246 in_base_initializer = 1;
27248 init = TREE_VALUE (t);
27249 tmp = init;
27250 if (init != void_type_node)
27251 init = tsubst_expr (init, argvec,
27252 tf_warning_or_error, NULL_TREE);
27253 if (init == NULL_TREE && tmp != NULL_TREE)
27254 /* If we had an initializer but it instantiated to nothing,
27255 value-initialize the object. This will only occur when
27256 the initializer was a pack expansion where the parameter
27257 packs used in that expansion were of length zero. */
27258 init = void_type_node;
27259 in_base_initializer = 0;
27262 if (target_ctor != error_mark_node
27263 && init != error_mark_node)
27265 error ("mem-initializer for %qD follows constructor delegation",
27266 decl);
27267 return inits;
27269 /* Look for a target constructor. */
27270 if (init != error_mark_node
27271 && decl && CLASS_TYPE_P (decl)
27272 && same_type_p (decl, current_class_type))
27274 maybe_warn_cpp0x (CPP0X_DELEGATING_CTORS);
27275 if (inits)
27277 error ("constructor delegation follows mem-initializer for %qD",
27278 TREE_PURPOSE (inits));
27279 continue;
27281 target_ctor = init;
27284 if (decl)
27286 init = build_tree_list (decl, init);
27287 /* Carry over the dummy TREE_TYPE node containing the source
27288 location. */
27289 TREE_TYPE (init) = TREE_TYPE (t);
27290 TREE_CHAIN (init) = inits;
27291 inits = init;
27295 return inits;
27298 /* Instantiate an enumerated type. TAG is the template type, NEWTAG
27299 is the instantiation (which should have been created with
27300 start_enum) and ARGS are the template arguments to use. */
27302 static void
27303 tsubst_enum (tree tag, tree newtag, tree args)
27305 tree e;
27307 if (SCOPED_ENUM_P (newtag))
27308 begin_scope (sk_scoped_enum, newtag);
27310 for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
27312 tree value;
27313 tree decl = TREE_VALUE (e);
27315 /* Note that in a template enum, the TREE_VALUE is the
27316 CONST_DECL, not the corresponding INTEGER_CST. */
27317 value = tsubst_expr (DECL_INITIAL (decl),
27318 args, tf_warning_or_error, NULL_TREE);
27320 /* Give this enumeration constant the correct access. */
27321 set_current_access_from_decl (decl);
27323 /* Actually build the enumerator itself. Here we're assuming that
27324 enumerators can't have dependent attributes. */
27325 tree newdecl = build_enumerator (DECL_NAME (decl), value, newtag,
27326 DECL_ATTRIBUTES (decl),
27327 DECL_SOURCE_LOCATION (decl));
27328 /* Attribute deprecated without an argument isn't sticky: it'll
27329 melt into a tree flag, so we need to propagate the flag here,
27330 since we just created a new enumerator. */
27331 TREE_DEPRECATED (newdecl) = TREE_DEPRECATED (decl);
27332 TREE_UNAVAILABLE (newdecl) = TREE_UNAVAILABLE (decl);
27335 if (SCOPED_ENUM_P (newtag))
27336 finish_scope ();
27338 finish_enum_value_list (newtag);
27339 finish_enum (newtag);
27341 DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
27342 = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
27343 TREE_DEPRECATED (newtag) = TREE_DEPRECATED (tag);
27344 TREE_UNAVAILABLE (newtag) = TREE_UNAVAILABLE (tag);
27347 /* DECL is a FUNCTION_DECL that is a template specialization. Return
27348 its type -- but without substituting the innermost set of template
27349 arguments. So, innermost set of template parameters will appear in
27350 the type. */
27352 tree
27353 get_mostly_instantiated_function_type (tree decl)
27355 /* For a function, DECL_TI_TEMPLATE is partially instantiated. */
27356 return TREE_TYPE (DECL_TI_TEMPLATE (decl));
27359 /* Return truthvalue if we're processing a template different from
27360 the last one involved in diagnostics. */
27361 bool
27362 problematic_instantiation_changed (void)
27364 return current_tinst_level != last_error_tinst_level;
27367 /* Remember current template involved in diagnostics. */
27368 void
27369 record_last_problematic_instantiation (void)
27371 set_refcount_ptr (last_error_tinst_level, current_tinst_level);
27374 struct tinst_level *
27375 current_instantiation (void)
27377 return current_tinst_level;
27380 /* Return TRUE if current_function_decl is being instantiated, false
27381 otherwise. */
27383 bool
27384 instantiating_current_function_p (void)
27386 return (current_instantiation ()
27387 && (current_instantiation ()->maybe_get_node ()
27388 == current_function_decl));
27391 /* [temp.param] Check that template non-type parm TYPE is of an allowable
27392 type. Return false for ok, true for disallowed. Issue error and
27393 inform messages under control of COMPLAIN. */
27395 static bool
27396 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
27398 if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
27399 return false;
27400 else if (TYPE_PTR_P (type))
27401 return false;
27402 else if (TYPE_REF_P (type)
27403 && !TYPE_REF_IS_RVALUE (type))
27404 return false;
27405 else if (TYPE_PTRMEM_P (type))
27406 return false;
27407 else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
27409 if (CLASS_PLACEHOLDER_TEMPLATE (type) && cxx_dialect < cxx20)
27411 if (complain & tf_error)
27412 error ("non-type template parameters of deduced class type only "
27413 "available with %<-std=c++20%> or %<-std=gnu++20%>");
27414 return true;
27416 return false;
27418 else if (TREE_CODE (type) == NULLPTR_TYPE)
27419 return false;
27420 else if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM
27421 && cxx_dialect < cxx11)
27422 /* Fall through; before C++11 alias templates, a bound ttp
27423 always instantiates into a class type. */;
27424 else if (WILDCARD_TYPE_P (type))
27425 /* Any other wildcard type not already handled above is allowed. */
27426 return false;
27427 else if (TREE_CODE (type) == COMPLEX_TYPE)
27428 /* Fall through. */;
27429 else if (VOID_TYPE_P (type))
27430 /* Fall through. */;
27431 else if (cxx_dialect >= cxx20)
27433 if (dependent_type_p (type))
27434 return false;
27435 if (!complete_type_or_maybe_complain (type, NULL_TREE, complain))
27436 return true;
27437 if (structural_type_p (type))
27438 return false;
27439 if (complain & tf_error)
27441 auto_diagnostic_group d;
27442 error ("%qT is not a valid type for a template non-type "
27443 "parameter because it is not structural", type);
27444 structural_type_p (type, true);
27446 return true;
27448 else if (CLASS_TYPE_P (type))
27450 if (complain & tf_error)
27451 error ("non-type template parameters of class type only available "
27452 "with %<-std=c++20%> or %<-std=gnu++20%>");
27453 return true;
27456 if (complain & tf_error)
27458 if (type == error_mark_node)
27459 inform (input_location, "invalid template non-type parameter");
27460 else
27461 error ("%q#T is not a valid type for a template non-type parameter",
27462 type);
27464 return true;
27467 /* Returns true iff the noexcept-specifier for TYPE is value-dependent. */
27469 static bool
27470 value_dependent_noexcept_spec_p (tree type)
27472 if (tree spec = TYPE_RAISES_EXCEPTIONS (type))
27473 if (tree noex = TREE_PURPOSE (spec))
27474 /* Treat DEFERRED_NOEXCEPT as non-dependent, since it doesn't
27475 affect overload resolution and treating it as dependent breaks
27476 things. Same for an unparsed noexcept expression. */
27477 if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
27478 && TREE_CODE (noex) != DEFERRED_PARSE
27479 && value_dependent_expression_p (noex))
27480 return true;
27482 return false;
27485 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
27486 Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
27488 static bool
27489 dependent_type_p_r (tree type)
27491 tree scope;
27493 /* [temp.dep.type]
27495 A type is dependent if it is:
27497 -- a template parameter. Template template parameters are types
27498 for us (since TYPE_P holds true for them) so we handle
27499 them here. */
27500 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
27501 || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
27502 return true;
27503 /* -- a qualified-id with a nested-name-specifier which contains a
27504 class-name that names a dependent type or whose unqualified-id
27505 names a dependent type. */
27506 if (TREE_CODE (type) == TYPENAME_TYPE)
27507 return true;
27509 /* An alias template specialization can be dependent even if the
27510 resulting type is not. */
27511 if (dependent_alias_template_spec_p (type, nt_transparent))
27512 return true;
27514 /* -- a cv-qualified type where the cv-unqualified type is
27515 dependent.
27516 No code is necessary for this bullet; the code below handles
27517 cv-qualified types, and we don't want to strip aliases with
27518 TYPE_MAIN_VARIANT because of DR 1558. */
27519 /* -- a compound type constructed from any dependent type. */
27520 if (TYPE_PTRMEM_P (type))
27521 return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
27522 || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
27523 (type)));
27524 else if (INDIRECT_TYPE_P (type))
27525 return dependent_type_p (TREE_TYPE (type));
27526 else if (FUNC_OR_METHOD_TYPE_P (type))
27528 tree arg_type;
27530 if (dependent_type_p (TREE_TYPE (type)))
27531 return true;
27532 for (arg_type = TYPE_ARG_TYPES (type);
27533 arg_type;
27534 arg_type = TREE_CHAIN (arg_type))
27535 if (dependent_type_p (TREE_VALUE (arg_type)))
27536 return true;
27537 if (cxx_dialect >= cxx17
27538 && value_dependent_noexcept_spec_p (type))
27539 /* A value-dependent noexcept-specifier makes the type dependent. */
27540 return true;
27541 return false;
27543 /* -- an array type constructed from any dependent type or whose
27544 size is specified by a constant expression that is
27545 value-dependent.
27547 We checked for type- and value-dependence of the bounds in
27548 compute_array_index_type, so TYPE_DEPENDENT_P is already set. */
27549 if (TREE_CODE (type) == ARRAY_TYPE)
27551 if (TYPE_DOMAIN (type)
27552 && dependent_type_p (TYPE_DOMAIN (type)))
27553 return true;
27554 return dependent_type_p (TREE_TYPE (type));
27557 /* -- a template-id in which either the template name is a template
27558 parameter ... */
27559 if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
27560 return true;
27561 /* ... or any of the template arguments is a dependent type or
27562 an expression that is type-dependent or value-dependent. */
27563 else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
27564 && (any_dependent_template_arguments_p
27565 (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
27566 return true;
27568 /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and TRAIT_TYPEs are
27569 dependent; if the argument of the `typeof' expression is not
27570 type-dependent, then it should already been have resolved. */
27571 if (TREE_CODE (type) == TYPEOF_TYPE
27572 || TREE_CODE (type) == DECLTYPE_TYPE
27573 || TREE_CODE (type) == TRAIT_TYPE)
27574 return true;
27576 /* A template argument pack is dependent if any of its packed
27577 arguments are. */
27578 if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
27580 tree args = ARGUMENT_PACK_ARGS (type);
27581 for (tree arg : tree_vec_range (args))
27582 if (dependent_template_arg_p (arg))
27583 return true;
27586 /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
27587 be template parameters. */
27588 if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
27589 return true;
27591 if (TREE_CODE (type) == DEPENDENT_OPERATOR_TYPE)
27592 return true;
27594 if (any_dependent_type_attributes_p (TYPE_ATTRIBUTES (type)))
27595 return true;
27597 /* The standard does not specifically mention types that are local
27598 to template functions or local classes, but they should be
27599 considered dependent too. For example:
27601 template <int I> void f() {
27602 enum E { a = I };
27603 S<sizeof (E)> s;
27606 The size of `E' cannot be known until the value of `I' has been
27607 determined. Therefore, `E' must be considered dependent. */
27608 scope = TYPE_CONTEXT (type);
27609 if (scope && TYPE_P (scope))
27610 return dependent_type_p (scope);
27611 /* Don't use type_dependent_expression_p here, as it can lead
27612 to infinite recursion trying to determine whether a lambda
27613 nested in a lambda is dependent (c++/47687). */
27614 else if (scope && TREE_CODE (scope) == FUNCTION_DECL
27615 && DECL_LANG_SPECIFIC (scope)
27616 && DECL_TEMPLATE_INFO (scope)
27617 && (any_dependent_template_arguments_p
27618 (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
27619 return true;
27621 /* Other types are non-dependent. */
27622 return false;
27625 /* Returns TRUE if TYPE is dependent, in the sense of
27626 [temp.dep.type]. Note that a NULL type is considered dependent. */
27628 bool
27629 dependent_type_p (tree type)
27631 /* If there are no template parameters in scope, then there can't be
27632 any dependent types. */
27633 if (!processing_template_decl)
27635 /* If we are not processing a template, then nobody should be
27636 providing us with a dependent type. */
27637 gcc_assert (type);
27638 gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
27639 return false;
27642 /* If the type is NULL, we have not computed a type for the entity
27643 in question; in that case, the type is dependent. */
27644 if (!type)
27645 return true;
27647 /* Erroneous types can be considered non-dependent. */
27648 if (type == error_mark_node)
27649 return false;
27651 /* If we have not already computed the appropriate value for TYPE,
27652 do so now. */
27653 if (!TYPE_DEPENDENT_P_VALID (type))
27655 TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
27656 TYPE_DEPENDENT_P_VALID (type) = 1;
27659 return TYPE_DEPENDENT_P (type);
27662 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
27663 lookup. In other words, a dependent type that is not the current
27664 instantiation. */
27666 bool
27667 dependent_scope_p (tree scope)
27669 return (scope && TYPE_P (scope) && dependent_type_p (scope)
27670 && !currently_open_class (scope));
27673 /* True if we might find more declarations in SCOPE during instantiation than
27674 we can when parsing the template. */
27676 bool
27677 dependentish_scope_p (tree scope)
27679 return dependent_scope_p (scope) || any_dependent_bases_p (scope);
27682 /* T is a SCOPE_REF. Return whether it represents a non-static member of
27683 an unknown base of 'this' (and is therefore instantiation-dependent). */
27685 static bool
27686 unknown_base_ref_p (tree t)
27688 if (!current_class_ptr)
27689 return false;
27691 tree mem = TREE_OPERAND (t, 1);
27692 if (shared_member_p (mem))
27693 return false;
27695 tree cur = current_nonlambda_class_type ();
27696 if (!any_dependent_bases_p (cur))
27697 return false;
27699 tree ctx = TREE_OPERAND (t, 0);
27700 if (DERIVED_FROM_P (ctx, cur))
27701 return false;
27703 return true;
27706 /* T is a SCOPE_REF; return whether we need to consider it
27707 instantiation-dependent so that we can check access at instantiation
27708 time even though we know which member it resolves to. */
27710 static bool
27711 instantiation_dependent_scope_ref_p (tree t)
27713 if (DECL_P (TREE_OPERAND (t, 1))
27714 && CLASS_TYPE_P (TREE_OPERAND (t, 0))
27715 && !dependent_scope_p (TREE_OPERAND (t, 0))
27716 && !unknown_base_ref_p (t)
27717 && accessible_in_template_p (TREE_OPERAND (t, 0),
27718 TREE_OPERAND (t, 1)))
27719 return false;
27720 else
27721 return true;
27724 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
27725 [temp.dep.constexpr]. EXPRESSION is already known to be a constant
27726 expression. */
27728 /* Note that this predicate is not appropriate for general expressions;
27729 only constant expressions (that satisfy potential_constant_expression)
27730 can be tested for value dependence. */
27732 bool
27733 value_dependent_expression_p (tree expression)
27735 if (!processing_template_decl || expression == NULL_TREE)
27736 return false;
27738 /* A type-dependent expression is also value-dependent. */
27739 if (type_dependent_expression_p (expression))
27740 return true;
27742 switch (TREE_CODE (expression))
27744 case BASELINK:
27745 /* A dependent member function of the current instantiation. */
27746 return dependent_type_p (BINFO_TYPE (BASELINK_BINFO (expression)));
27748 case FUNCTION_DECL:
27749 /* A dependent member function of the current instantiation. */
27750 if (DECL_CLASS_SCOPE_P (expression)
27751 && dependent_type_p (DECL_CONTEXT (expression)))
27752 return true;
27753 break;
27755 case IDENTIFIER_NODE:
27756 /* A name that has not been looked up -- must be dependent. */
27757 return true;
27759 case TEMPLATE_PARM_INDEX:
27760 /* A non-type template parm. */
27761 return true;
27763 case CONST_DECL:
27764 /* A non-type template parm. */
27765 if (DECL_TEMPLATE_PARM_P (expression))
27766 return true;
27767 return value_dependent_expression_p (DECL_INITIAL (expression));
27769 case VAR_DECL:
27770 /* A constant with literal type and is initialized
27771 with an expression that is value-dependent. */
27772 if (DECL_DEPENDENT_INIT_P (expression))
27773 return true;
27774 if (DECL_HAS_VALUE_EXPR_P (expression))
27776 tree value_expr = DECL_VALUE_EXPR (expression);
27777 if (value_dependent_expression_p (value_expr)
27778 /* __PRETTY_FUNCTION__ inside a template function is dependent
27779 on the name of the function. */
27780 || (DECL_PRETTY_FUNCTION_P (expression)
27781 /* It might be used in a template, but not a template
27782 function, in which case its DECL_VALUE_EXPR will be
27783 "top level". */
27784 && value_expr == error_mark_node))
27785 return true;
27787 else if (TYPE_REF_P (TREE_TYPE (expression)))
27788 /* FIXME cp_finish_decl doesn't fold reference initializers. */
27789 return true;
27790 /* We have a constexpr variable and we're processing a template. When
27791 there's lifetime extension involved (for which finish_compound_literal
27792 used to create a temporary), we'll not be able to evaluate the
27793 variable until instantiating, so pretend it's value-dependent. */
27794 else if (DECL_DECLARED_CONSTEXPR_P (expression)
27795 && !TREE_CONSTANT (expression))
27796 return true;
27797 return false;
27799 case DYNAMIC_CAST_EXPR:
27800 case STATIC_CAST_EXPR:
27801 case CONST_CAST_EXPR:
27802 case REINTERPRET_CAST_EXPR:
27803 case CAST_EXPR:
27804 case IMPLICIT_CONV_EXPR:
27805 /* These expressions are value-dependent if the type to which
27806 the cast occurs is dependent or the expression being casted
27807 is value-dependent. */
27809 tree type = TREE_TYPE (expression);
27811 if (dependent_type_p (type))
27812 return true;
27814 /* A functional cast has a list of operands. */
27815 expression = TREE_OPERAND (expression, 0);
27816 if (!expression)
27818 /* If there are no operands, it must be an expression such
27819 as "int()". This should not happen for aggregate types
27820 because it would form non-constant expressions. */
27821 gcc_assert (cxx_dialect >= cxx11
27822 || INTEGRAL_OR_ENUMERATION_TYPE_P (type));
27824 return false;
27827 if (TREE_CODE (expression) == TREE_LIST)
27828 return any_value_dependent_elements_p (expression);
27830 if (TREE_CODE (type) == REFERENCE_TYPE
27831 && has_value_dependent_address (expression))
27832 return true;
27834 return value_dependent_expression_p (expression);
27837 case SIZEOF_EXPR:
27838 if (SIZEOF_EXPR_TYPE_P (expression))
27839 return dependent_type_p (TREE_TYPE (TREE_OPERAND (expression, 0)));
27840 /* FALLTHRU */
27841 case ALIGNOF_EXPR:
27842 case TYPEID_EXPR:
27843 /* A `sizeof' expression is value-dependent if the operand is
27844 type-dependent or is a pack expansion. */
27845 expression = TREE_OPERAND (expression, 0);
27846 if (PACK_EXPANSION_P (expression))
27847 return true;
27848 else if (TYPE_P (expression))
27849 return dependent_type_p (expression);
27850 return instantiation_dependent_uneval_expression_p (expression);
27852 case AT_ENCODE_EXPR:
27853 /* An 'encode' expression is value-dependent if the operand is
27854 type-dependent. */
27855 expression = TREE_OPERAND (expression, 0);
27856 return dependent_type_p (expression);
27858 case NOEXCEPT_EXPR:
27859 expression = TREE_OPERAND (expression, 0);
27860 return instantiation_dependent_uneval_expression_p (expression);
27862 case SCOPE_REF:
27863 /* All instantiation-dependent expressions should also be considered
27864 value-dependent. */
27865 return instantiation_dependent_scope_ref_p (expression);
27867 case COMPONENT_REF:
27868 return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
27869 || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
27871 case NONTYPE_ARGUMENT_PACK:
27872 /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
27873 is value-dependent. */
27874 for (tree arg : tree_vec_range (ARGUMENT_PACK_ARGS (expression)))
27875 if (value_dependent_expression_p (arg))
27876 return true;
27877 return false;
27879 case TRAIT_EXPR:
27881 if (dependent_type_p (TRAIT_EXPR_TYPE1 (expression)))
27882 return true;
27884 tree type2 = TRAIT_EXPR_TYPE2 (expression);
27885 if (!type2)
27886 return false;
27888 if (TREE_CODE (type2) != TREE_VEC)
27889 return dependent_type_p (type2);
27891 for (tree arg : tree_vec_range (type2))
27892 if (dependent_type_p (arg))
27893 return true;
27895 return false;
27898 case MODOP_EXPR:
27899 return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
27900 || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
27902 case ARRAY_REF:
27903 return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
27904 || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
27906 case ADDR_EXPR:
27908 tree op = TREE_OPERAND (expression, 0);
27909 return (value_dependent_expression_p (op)
27910 || has_value_dependent_address (op));
27913 case REQUIRES_EXPR:
27914 /* Treat all requires-expressions as value-dependent so
27915 we don't try to fold them. */
27916 return true;
27918 case TYPE_REQ:
27919 return dependent_type_p (TREE_OPERAND (expression, 0));
27921 case CALL_EXPR:
27923 if (value_dependent_expression_p (CALL_EXPR_FN (expression)))
27924 return true;
27925 tree fn = get_callee_fndecl (expression);
27926 int i, nargs;
27927 nargs = call_expr_nargs (expression);
27928 for (i = 0; i < nargs; ++i)
27930 tree op = CALL_EXPR_ARG (expression, i);
27931 /* In a call to a constexpr member function, look through the
27932 implicit ADDR_EXPR on the object argument so that it doesn't
27933 cause the call to be considered value-dependent. We also
27934 look through it in potential_constant_expression. */
27935 if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
27936 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
27937 && TREE_CODE (op) == ADDR_EXPR)
27938 op = TREE_OPERAND (op, 0);
27939 if (value_dependent_expression_p (op))
27940 return true;
27942 return false;
27945 case TEMPLATE_ID_EXPR:
27946 return concept_definition_p (TREE_OPERAND (expression, 0))
27947 && any_dependent_template_arguments_p (TREE_OPERAND (expression, 1));
27949 case CONSTRUCTOR:
27951 unsigned ix;
27952 tree val;
27953 if (dependent_type_p (TREE_TYPE (expression)))
27954 return true;
27955 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
27956 if (value_dependent_expression_p (val))
27957 return true;
27958 return false;
27961 case STMT_EXPR:
27962 /* Treat a GNU statement expression as dependent to avoid crashing
27963 under instantiate_non_dependent_expr; it can't be constant. */
27964 return true;
27966 case NEW_EXPR:
27967 case VEC_NEW_EXPR:
27968 /* The second operand is a type, which type_dependent_expression_p
27969 (and therefore value_dependent_expression_p) doesn't want to see. */
27970 return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
27971 || value_dependent_expression_p (TREE_OPERAND (expression, 2))
27972 || value_dependent_expression_p (TREE_OPERAND (expression, 3)));
27974 default:
27975 /* A constant expression is value-dependent if any subexpression is
27976 value-dependent. */
27977 switch (TREE_CODE_CLASS (TREE_CODE (expression)))
27979 case tcc_reference:
27980 case tcc_unary:
27981 case tcc_comparison:
27982 case tcc_binary:
27983 case tcc_expression:
27984 case tcc_vl_exp:
27986 int i, len = cp_tree_operand_length (expression);
27988 for (i = 0; i < len; i++)
27990 tree t = TREE_OPERAND (expression, i);
27992 /* In some cases, some of the operands may be missing.
27993 (For example, in the case of PREDECREMENT_EXPR, the
27994 amount to increment by may be missing.) That doesn't
27995 make the expression dependent. */
27996 if (t && value_dependent_expression_p (t))
27997 return true;
28000 break;
28001 default:
28002 break;
28004 break;
28007 /* The expression is not value-dependent. */
28008 return false;
28011 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
28012 [temp.dep.expr]. Note that an expression with no type is
28013 considered dependent. Other parts of the compiler arrange for an
28014 expression with type-dependent subexpressions to have no type, so
28015 this function doesn't have to be fully recursive. */
28017 bool
28018 type_dependent_expression_p (tree expression)
28020 if (!processing_template_decl)
28021 return false;
28023 if (expression == NULL_TREE || expression == error_mark_node)
28024 return false;
28026 gcc_checking_assert (!TYPE_P (expression));
28028 STRIP_ANY_LOCATION_WRAPPER (expression);
28030 /* An unresolved name is always dependent. */
28031 if (identifier_p (expression)
28032 || TREE_CODE (expression) == USING_DECL
28033 || TREE_CODE (expression) == WILDCARD_DECL)
28034 return true;
28036 /* A lambda-expression in template context is dependent. dependent_type_p is
28037 true for a lambda in the scope of a class or function template, but that
28038 doesn't cover all template contexts, like a default template argument. */
28039 if (TREE_CODE (expression) == LAMBDA_EXPR)
28040 return true;
28042 /* A fold expression is type-dependent. */
28043 if (TREE_CODE (expression) == UNARY_LEFT_FOLD_EXPR
28044 || TREE_CODE (expression) == UNARY_RIGHT_FOLD_EXPR
28045 || TREE_CODE (expression) == BINARY_LEFT_FOLD_EXPR
28046 || TREE_CODE (expression) == BINARY_RIGHT_FOLD_EXPR)
28047 return true;
28049 /* Some expression forms are never type-dependent. */
28050 if (TREE_CODE (expression) == SIZEOF_EXPR
28051 || TREE_CODE (expression) == ALIGNOF_EXPR
28052 || TREE_CODE (expression) == AT_ENCODE_EXPR
28053 || TREE_CODE (expression) == NOEXCEPT_EXPR
28054 || TREE_CODE (expression) == TRAIT_EXPR
28055 || TREE_CODE (expression) == TYPEID_EXPR
28056 || TREE_CODE (expression) == DELETE_EXPR
28057 || TREE_CODE (expression) == VEC_DELETE_EXPR
28058 || TREE_CODE (expression) == THROW_EXPR
28059 || TREE_CODE (expression) == REQUIRES_EXPR)
28060 return false;
28062 /* The types of these expressions depends only on the type to which
28063 the cast occurs. */
28064 if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
28065 || TREE_CODE (expression) == STATIC_CAST_EXPR
28066 || TREE_CODE (expression) == CONST_CAST_EXPR
28067 || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
28068 || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
28069 || TREE_CODE (expression) == CAST_EXPR)
28070 return dependent_type_p (TREE_TYPE (expression));
28072 /* The types of these expressions depends only on the type created
28073 by the expression. */
28074 if (TREE_CODE (expression) == NEW_EXPR
28075 || TREE_CODE (expression) == VEC_NEW_EXPR)
28077 /* For NEW_EXPR tree nodes created inside a template, either
28078 the object type itself or a TREE_LIST may appear as the
28079 operand 1. */
28080 tree type = TREE_OPERAND (expression, 1);
28081 if (TREE_CODE (type) == TREE_LIST)
28082 /* This is an array type. We need to check array dimensions
28083 as well. */
28084 return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
28085 || value_dependent_expression_p
28086 (TREE_OPERAND (TREE_VALUE (type), 1));
28087 /* Array type whose dimension has to be deduced. */
28088 else if (TREE_CODE (type) == ARRAY_TYPE
28089 && TREE_OPERAND (expression, 2) == NULL_TREE)
28090 return true;
28091 else
28092 return dependent_type_p (type);
28095 if (TREE_CODE (expression) == SCOPE_REF)
28097 tree scope = TREE_OPERAND (expression, 0);
28098 tree name = TREE_OPERAND (expression, 1);
28100 /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
28101 contains an identifier associated by name lookup with one or more
28102 declarations declared with a dependent type, or...a
28103 nested-name-specifier or qualified-id that names a member of an
28104 unknown specialization. */
28105 return (type_dependent_expression_p (name)
28106 || dependent_scope_p (scope));
28109 if (TREE_CODE (expression) == TEMPLATE_DECL
28110 && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
28111 return uses_outer_template_parms (expression);
28113 if (TREE_CODE (expression) == STMT_EXPR)
28114 expression = stmt_expr_value_expr (expression);
28116 if (BRACE_ENCLOSED_INITIALIZER_P (expression))
28118 for (auto &elt : CONSTRUCTOR_ELTS (expression))
28119 if (type_dependent_expression_p (elt.value))
28120 return true;
28121 return false;
28124 /* A static data member of the current instantiation with incomplete
28125 array type is type-dependent, as the definition and specializations
28126 can have different bounds. */
28127 if (VAR_P (expression)
28128 && DECL_CLASS_SCOPE_P (expression)
28129 && dependent_type_p (DECL_CONTEXT (expression))
28130 && VAR_HAD_UNKNOWN_BOUND (expression))
28131 return true;
28133 /* An array of unknown bound depending on a variadic parameter, eg:
28135 template<typename... Args>
28136 void foo (Args... args)
28138 int arr[] = { args... };
28141 template<int... vals>
28142 void bar ()
28144 int arr[] = { vals... };
28147 If the array has no length and has an initializer, it must be that
28148 we couldn't determine its length in cp_complete_array_type because
28149 it is dependent. */
28150 if (((VAR_P (expression) && DECL_INITIAL (expression))
28151 || COMPOUND_LITERAL_P (expression))
28152 && TREE_TYPE (expression) != NULL_TREE
28153 && TREE_CODE (TREE_TYPE (expression)) == ARRAY_TYPE
28154 && !TYPE_DOMAIN (TREE_TYPE (expression)))
28155 return true;
28157 /* Pull a FUNCTION_DECL out of a BASELINK if we can. */
28158 if (BASELINK_P (expression))
28160 if (BASELINK_OPTYPE (expression)
28161 && dependent_type_p (BASELINK_OPTYPE (expression)))
28162 return true;
28163 expression = BASELINK_FUNCTIONS (expression);
28166 /* A function or variable template-id is type-dependent if it has any
28167 dependent template arguments. */
28168 if (VAR_OR_FUNCTION_DECL_P (expression)
28169 && DECL_LANG_SPECIFIC (expression)
28170 && DECL_TEMPLATE_INFO (expression))
28172 /* Consider the innermost template arguments, since those are the ones
28173 that come from the template-id; the template arguments for the
28174 enclosing class do not make it type-dependent unless they are used in
28175 the type of the decl. */
28176 if (instantiates_primary_template_p (expression)
28177 && (any_dependent_template_arguments_p
28178 (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
28179 return true;
28182 /* Otherwise, if the function decl isn't from a dependent scope, it can't be
28183 type-dependent. Checking this is important for functions with auto return
28184 type, which looks like a dependent type. */
28185 if (TREE_CODE (expression) == FUNCTION_DECL
28186 && !(DECL_CLASS_SCOPE_P (expression)
28187 && dependent_type_p (DECL_CONTEXT (expression)))
28188 && !(DECL_LANG_SPECIFIC (expression)
28189 && DECL_UNIQUE_FRIEND_P (expression)
28190 && (!DECL_FRIEND_CONTEXT (expression)
28191 || dependent_type_p (DECL_FRIEND_CONTEXT (expression))))
28192 && !DECL_LOCAL_DECL_P (expression))
28194 gcc_assert (!dependent_type_p (TREE_TYPE (expression))
28195 || undeduced_auto_decl (expression));
28196 return false;
28199 /* Otherwise, its constraints could still depend on outer template parameters
28200 from its (dependent) scope. */
28201 if (TREE_CODE (expression) == FUNCTION_DECL
28202 /* As an optimization, check this cheaper sufficient condition first.
28203 (At this point we've established that we're looking at a member of
28204 a dependent class, so it makes sense to start treating say undeduced
28205 auto as dependent.) */
28206 && !dependent_type_p (TREE_TYPE (expression))
28207 && uses_outer_template_parms_in_constraints (expression))
28208 return true;
28210 /* Always dependent, on the number of arguments if nothing else. */
28211 if (TREE_CODE (expression) == EXPR_PACK_EXPANSION)
28212 return true;
28214 if (TREE_TYPE (expression) == unknown_type_node)
28216 if (TREE_CODE (expression) == ADDR_EXPR)
28217 return type_dependent_expression_p (TREE_OPERAND (expression, 0));
28218 if (TREE_CODE (expression) == COMPONENT_REF
28219 || TREE_CODE (expression) == OFFSET_REF)
28221 if (type_dependent_object_expression_p (TREE_OPERAND (expression, 0)))
28222 return true;
28223 expression = TREE_OPERAND (expression, 1);
28224 if (identifier_p (expression))
28225 return false;
28227 /* SCOPE_REF with non-null TREE_TYPE is always non-dependent. */
28228 if (TREE_CODE (expression) == SCOPE_REF)
28229 return false;
28231 /* CO_AWAIT/YIELD_EXPR with unknown type is always dependent. */
28232 if (TREE_CODE (expression) == CO_AWAIT_EXPR
28233 || TREE_CODE (expression) == CO_YIELD_EXPR)
28234 return true;
28236 if (BASELINK_P (expression))
28238 if (BASELINK_OPTYPE (expression)
28239 && dependent_type_p (BASELINK_OPTYPE (expression)))
28240 return true;
28241 expression = BASELINK_FUNCTIONS (expression);
28244 if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
28246 if (any_dependent_template_arguments_p
28247 (TREE_OPERAND (expression, 1)))
28248 return true;
28249 expression = TREE_OPERAND (expression, 0);
28250 if (identifier_p (expression))
28251 return true;
28254 gcc_assert (OVL_P (expression));
28256 for (lkp_iterator iter (expression); iter; ++iter)
28257 if (type_dependent_expression_p (*iter))
28258 return true;
28260 return false;
28263 /* The type of a non-type template parm declared with a placeholder type
28264 depends on the corresponding template argument, even though
28265 placeholders are not normally considered dependent. */
28266 if (TREE_CODE (expression) == TEMPLATE_PARM_INDEX
28267 && is_auto (TREE_TYPE (expression)))
28268 return true;
28270 gcc_assert (TREE_CODE (expression) != TYPE_DECL);
28272 /* Dependent type attributes might not have made it from the decl to
28273 the type yet. */
28274 if (DECL_P (expression)
28275 && any_dependent_type_attributes_p (DECL_ATTRIBUTES (expression)))
28276 return true;
28278 return (dependent_type_p (TREE_TYPE (expression)));
28281 /* [temp.dep.expr]/5: A class member access expression (5.2.5) is
28282 type-dependent if the expression refers to a member of the current
28283 instantiation and the type of the referenced member is dependent, or the
28284 class member access expression refers to a member of an unknown
28285 specialization.
28287 This function returns true if the OBJECT in such a class member access
28288 expression is of an unknown specialization. */
28290 bool
28291 type_dependent_object_expression_p (tree object)
28293 /* An IDENTIFIER_NODE can sometimes have a TREE_TYPE, but it's still
28294 dependent. */
28295 if (TREE_CODE (object) == IDENTIFIER_NODE)
28296 return true;
28297 tree scope = TREE_TYPE (object);
28298 return (!scope || dependent_scope_p (scope));
28301 /* walk_tree callback function for instantiation_dependent_expression_p,
28302 below. Returns non-zero if a dependent subexpression is found. */
28304 static tree
28305 instantiation_dependent_r (tree *tp, int *walk_subtrees,
28306 void * /*data*/)
28308 if (TYPE_P (*tp))
28310 /* We don't have to worry about decltype currently because decltype
28311 of an instantiation-dependent expr is a dependent type. This
28312 might change depending on the resolution of DR 1172. */
28313 *walk_subtrees = false;
28314 return NULL_TREE;
28316 enum tree_code code = TREE_CODE (*tp);
28317 switch (code)
28319 /* Don't treat an argument list as dependent just because it has no
28320 TREE_TYPE. */
28321 case TREE_LIST:
28322 case TREE_VEC:
28323 case NONTYPE_ARGUMENT_PACK:
28324 return NULL_TREE;
28326 case TEMPLATE_PARM_INDEX:
28327 if (dependent_type_p (TREE_TYPE (*tp)))
28328 return *tp;
28329 if (TEMPLATE_PARM_PARAMETER_PACK (*tp))
28330 return *tp;
28331 /* We'll check value-dependence separately. */
28332 return NULL_TREE;
28334 /* Handle expressions with type operands. */
28335 case SIZEOF_EXPR:
28336 case ALIGNOF_EXPR:
28337 case TYPEID_EXPR:
28338 case AT_ENCODE_EXPR:
28340 tree op = TREE_OPERAND (*tp, 0);
28341 if (code == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (*tp))
28342 op = TREE_TYPE (op);
28343 if (TYPE_P (op))
28345 if (dependent_type_p (op))
28346 return *tp;
28347 else
28349 *walk_subtrees = false;
28350 return NULL_TREE;
28353 break;
28356 case COMPONENT_REF:
28357 if (identifier_p (TREE_OPERAND (*tp, 1)))
28358 /* In a template, finish_class_member_access_expr creates a
28359 COMPONENT_REF with an IDENTIFIER_NODE for op1 even if it isn't
28360 type-dependent, so that we can check access control at
28361 instantiation time (PR 42277). See also Core issue 1273. */
28362 return *tp;
28363 break;
28365 case SCOPE_REF:
28366 if (instantiation_dependent_scope_ref_p (*tp))
28367 return *tp;
28368 else
28369 break;
28371 /* Treat statement-expressions as dependent. */
28372 case BIND_EXPR:
28373 return *tp;
28375 /* Treat requires-expressions as dependent. */
28376 case REQUIRES_EXPR:
28377 return *tp;
28379 case CONSTRUCTOR:
28380 if (CONSTRUCTOR_IS_DEPENDENT (*tp))
28381 return *tp;
28382 break;
28384 case TEMPLATE_DECL:
28385 case FUNCTION_DECL:
28386 /* Before C++17, a noexcept-specifier isn't part of the function type
28387 so it doesn't affect type dependence, but we still want to consider it
28388 for instantiation dependence. */
28389 if (cxx_dialect < cxx17
28390 && DECL_DECLARES_FUNCTION_P (*tp)
28391 && value_dependent_noexcept_spec_p (TREE_TYPE (*tp)))
28392 return *tp;
28393 break;
28395 default:
28396 break;
28399 if (type_dependent_expression_p (*tp))
28400 return *tp;
28401 else
28402 return NULL_TREE;
28405 /* Returns TRUE if the EXPRESSION is instantiation-dependent, in the
28406 sense defined by the ABI:
28408 "An expression is instantiation-dependent if it is type-dependent
28409 or value-dependent, or it has a subexpression that is type-dependent
28410 or value-dependent."
28412 Except don't actually check value-dependence for unevaluated expressions,
28413 because in sizeof(i) we don't care about the value of i. Checking
28414 type-dependence will in turn check value-dependence of array bounds/template
28415 arguments as needed. */
28417 bool
28418 instantiation_dependent_uneval_expression_p (tree expression)
28420 tree result;
28422 if (!processing_template_decl)
28423 return false;
28425 if (expression == error_mark_node)
28426 return false;
28428 result = cp_walk_tree_without_duplicates (&expression,
28429 instantiation_dependent_r, NULL);
28430 return result != NULL_TREE;
28433 /* As above, but also check value-dependence of the expression as a whole. */
28435 bool
28436 instantiation_dependent_expression_p (tree expression)
28438 return (instantiation_dependent_uneval_expression_p (expression)
28439 || (processing_template_decl
28440 && potential_constant_expression (expression)
28441 && value_dependent_expression_p (expression)));
28444 /* Like type_dependent_expression_p, but it also works while not processing
28445 a template definition, i.e. during substitution or mangling. */
28447 bool
28448 type_dependent_expression_p_push (tree expr)
28450 bool b;
28451 ++processing_template_decl;
28452 b = type_dependent_expression_p (expr);
28453 --processing_template_decl;
28454 return b;
28457 /* Returns TRUE if ARGS contains a type-dependent expression. */
28459 bool
28460 any_type_dependent_arguments_p (const vec<tree, va_gc> *args)
28462 if (!processing_template_decl || !args)
28463 return false;
28465 for (tree arg : *args)
28466 if (type_dependent_expression_p (arg))
28467 return true;
28469 return false;
28472 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
28473 expressions) contains any type-dependent expressions. */
28475 bool
28476 any_type_dependent_elements_p (const_tree list)
28478 for (; list; list = TREE_CHAIN (list))
28479 if (type_dependent_expression_p (TREE_VALUE (list)))
28480 return true;
28482 return false;
28485 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
28486 expressions) contains any value-dependent expressions. */
28488 bool
28489 any_value_dependent_elements_p (const_tree list)
28491 for (; list; list = TREE_CHAIN (list))
28492 if (value_dependent_expression_p (TREE_VALUE (list)))
28493 return true;
28495 return false;
28498 /* Returns TRUE if the ARG (a template argument) is dependent. */
28500 bool
28501 dependent_template_arg_p (tree arg)
28503 if (!processing_template_decl)
28504 return false;
28506 /* Assume a template argument that was wrongly written by the user
28507 is dependent. This is consistent with what
28508 any_dependent_template_arguments_p [that calls this function]
28509 does. */
28510 if (!arg || arg == error_mark_node)
28511 return true;
28513 if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
28514 arg = argument_pack_select_arg (arg);
28516 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
28517 return true;
28518 if (TREE_CODE (arg) == TEMPLATE_DECL)
28520 if (DECL_TEMPLATE_PARM_P (arg))
28521 return true;
28522 /* A member template of a dependent class is not necessarily
28523 type-dependent, but it is a dependent template argument because it
28524 will be a member of an unknown specialization to that template. */
28525 tree scope = CP_DECL_CONTEXT (arg);
28526 return TYPE_P (scope) && dependent_type_p (scope);
28528 else if (ARGUMENT_PACK_P (arg))
28530 tree args = ARGUMENT_PACK_ARGS (arg);
28531 for (tree arg : tree_vec_range (args))
28532 if (dependent_template_arg_p (arg))
28533 return true;
28534 return false;
28536 else if (TYPE_P (arg))
28537 return dependent_type_p (arg);
28538 else
28539 return value_dependent_expression_p (arg);
28542 /* Identify any expressions that use function parms. */
28544 static tree
28545 find_parm_usage_r (tree *tp, int *walk_subtrees, void*)
28547 tree t = *tp;
28548 if (TREE_CODE (t) == PARM_DECL)
28550 *walk_subtrees = 0;
28551 return t;
28553 return NULL_TREE;
28556 /* Returns true if a type specialization formed using the template
28557 arguments ARGS needs to use structural equality. */
28559 bool
28560 any_template_arguments_need_structural_equality_p (tree args)
28562 int i;
28563 int j;
28565 if (!args)
28566 return false;
28567 if (args == error_mark_node)
28568 return true;
28570 for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
28572 tree level = TMPL_ARGS_LEVEL (args, i + 1);
28573 for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
28575 tree arg = TREE_VEC_ELT (level, j);
28576 tree packed_args = NULL_TREE;
28577 int k, len = 1;
28579 if (ARGUMENT_PACK_P (arg))
28581 /* Look inside the argument pack. */
28582 packed_args = ARGUMENT_PACK_ARGS (arg);
28583 len = TREE_VEC_LENGTH (packed_args);
28586 for (k = 0; k < len; ++k)
28588 if (packed_args)
28589 arg = TREE_VEC_ELT (packed_args, k);
28591 if (error_operand_p (arg))
28592 return true;
28593 else if (TREE_CODE (arg) == TEMPLATE_DECL)
28594 continue;
28595 else if (arg == any_targ_node)
28596 /* An any_targ_node argument (added by add_defaults_to_ttp)
28597 makes the corresponding specialization not canonicalizable,
28598 since template_args_equal always return true for it. We
28599 may see this when called from bind_template_template_parm. */
28600 return true;
28601 /* Checking current_function_decl because this structural
28602 comparison is only necessary for redeclaration. */
28603 else if (!current_function_decl
28604 && dependent_template_arg_p (arg)
28605 && (cp_walk_tree_without_duplicates
28606 (&arg, find_parm_usage_r, NULL)))
28607 /* The identity of a class template specialization that uses
28608 a function parameter depends on the identity of the function.
28609 And if this specialization appeared in the trailing return
28610 type thereof, we don't know the identity of the function
28611 (e.g. if it's a redeclaration or a new function) until we
28612 form its signature and go through duplicate_decls. Thus
28613 it's unsafe to decide on a canonical type now (which depends
28614 on the DECL_CONTEXT of the function parameter, which can get
28615 mutated after the fact by duplicate_decls), so just require
28616 structural equality in this case (PR52830). */
28617 return true;
28622 return false;
28625 /* Returns true if ARGS (a collection of template arguments) contains
28626 any dependent arguments. */
28628 bool
28629 any_dependent_template_arguments_p (const_tree args)
28631 if (args == error_mark_node)
28632 return true;
28633 if (!processing_template_decl || !args)
28634 return false;
28636 for (int i = 0, depth = TMPL_ARGS_DEPTH (args); i < depth; ++i)
28638 const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
28639 for (tree arg : tree_vec_range (CONST_CAST_TREE (level)))
28640 if (dependent_template_arg_p (arg))
28641 return true;
28644 return false;
28647 /* Returns true if ARGS contains any errors. */
28649 bool
28650 any_erroneous_template_args_p (const_tree args)
28652 int i;
28653 int j;
28655 if (args == error_mark_node)
28656 return true;
28658 if (args && TREE_CODE (args) != TREE_VEC)
28660 if (tree ti = get_template_info (args))
28661 args = TI_ARGS (ti);
28662 else
28663 args = NULL_TREE;
28666 if (!args)
28667 return false;
28669 for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
28671 const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
28672 for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
28673 if (error_operand_p (TREE_VEC_ELT (level, j)))
28674 return true;
28677 return false;
28680 /* Returns TRUE if the template TMPL is type-dependent. */
28682 bool
28683 dependent_template_p (tree tmpl)
28685 if (TREE_CODE (tmpl) == OVERLOAD)
28687 for (lkp_iterator iter (tmpl); iter; ++iter)
28688 if (dependent_template_p (*iter))
28689 return true;
28690 return false;
28693 /* Template template parameters are dependent. */
28694 if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
28695 || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
28696 return true;
28697 /* So are names that have not been looked up. */
28698 if (TREE_CODE (tmpl) == SCOPE_REF || identifier_p (tmpl))
28699 return true;
28700 return false;
28703 /* Returns TRUE if the specialization TMPL<ARGS> is dependent. */
28705 bool
28706 dependent_template_id_p (tree tmpl, tree args)
28708 return (dependent_template_p (tmpl)
28709 || any_dependent_template_arguments_p (args));
28712 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
28713 are dependent. */
28715 bool
28716 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
28718 int i;
28720 if (!processing_template_decl)
28721 return false;
28723 for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
28725 tree decl = TREE_VEC_ELT (declv, i);
28726 tree init = TREE_VEC_ELT (initv, i);
28727 tree cond = TREE_VEC_ELT (condv, i);
28728 tree incr = TREE_VEC_ELT (incrv, i);
28730 if (type_dependent_expression_p (decl)
28731 || TREE_CODE (decl) == SCOPE_REF)
28732 return true;
28734 if (init && type_dependent_expression_p (init))
28735 return true;
28737 if (cond == global_namespace)
28738 return true;
28740 if (type_dependent_expression_p (cond))
28741 return true;
28743 if (COMPARISON_CLASS_P (cond)
28744 && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
28745 || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
28746 return true;
28748 if (TREE_CODE (incr) == MODOP_EXPR)
28750 if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
28751 || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
28752 return true;
28754 else if (type_dependent_expression_p (incr))
28755 return true;
28756 else if (TREE_CODE (incr) == MODIFY_EXPR)
28758 if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
28759 return true;
28760 else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
28762 tree t = TREE_OPERAND (incr, 1);
28763 if (type_dependent_expression_p (TREE_OPERAND (t, 0))
28764 || type_dependent_expression_p (TREE_OPERAND (t, 1)))
28765 return true;
28767 /* If this loop has a class iterator with != comparison
28768 with increment other than i++/++i/i--/--i, make sure the
28769 increment is constant. */
28770 if (CLASS_TYPE_P (TREE_TYPE (decl))
28771 && TREE_CODE (cond) == NE_EXPR)
28773 if (TREE_OPERAND (t, 0) == decl)
28774 t = TREE_OPERAND (t, 1);
28775 else
28776 t = TREE_OPERAND (t, 0);
28777 if (TREE_CODE (t) != INTEGER_CST)
28778 return true;
28784 return false;
28787 /* TYPE is a TYPENAME_TYPE. Returns the ordinary TYPE to which the
28788 TYPENAME_TYPE corresponds. Returns the original TYPENAME_TYPE if
28789 no such TYPE can be found. Note that this function peers inside
28790 uninstantiated templates and therefore should be used only in
28791 extremely limited situations. ONLY_CURRENT_P restricts this
28792 peering to the currently open classes hierarchy (which is required
28793 when comparing types). */
28795 tree
28796 resolve_typename_type (tree type, bool only_current_p)
28798 tree scope;
28799 tree name;
28800 tree decl;
28801 int quals;
28802 tree pushed_scope;
28803 tree result;
28805 gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
28807 scope = TYPE_CONTEXT (type);
28808 /* We shouldn't have built a TYPENAME_TYPE with a non-dependent scope. */
28809 gcc_checking_assert (uses_template_parms (scope));
28811 /* Usually the non-qualified identifier of a TYPENAME_TYPE is
28812 TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of a
28813 TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL
28814 representing the typedef. In that case TYPE_IDENTIFIER (type) is
28815 not the non-qualified identifier of the TYPENAME_TYPE anymore.
28816 So by getting the TYPE_IDENTIFIER of the _main declaration_ of
28817 the TYPENAME_TYPE instead, we avoid messing up with a possible
28818 typedef variant case. */
28819 name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
28821 /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
28822 it first before we can figure out what NAME refers to. */
28823 if (TREE_CODE (scope) == TYPENAME_TYPE)
28825 if (TYPENAME_IS_RESOLVING_P (scope))
28826 /* Given a class template A with a dependent base with nested type C,
28827 typedef typename A::C::C C will land us here, as trying to resolve
28828 the initial A::C leads to the local C typedef, which leads back to
28829 A::C::C. So we break the recursion now. */
28830 return type;
28831 else
28832 scope = resolve_typename_type (scope, only_current_p);
28834 /* If we don't know what SCOPE refers to, then we cannot resolve the
28835 TYPENAME_TYPE. */
28836 if (!CLASS_TYPE_P (scope))
28837 return type;
28838 /* If this is a typedef, we don't want to look inside (c++/11987). */
28839 if (typedef_variant_p (type))
28840 return type;
28841 /* If SCOPE isn't the template itself, it will not have a valid
28842 TYPE_FIELDS list. */
28843 if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
28844 /* scope is either the template itself or a compatible instantiation
28845 like X<T>, so look up the name in the original template. */
28846 scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
28847 /* If scope has no fields, it can't be a current instantiation. Check this
28848 before currently_open_class to avoid infinite recursion (71515). */
28849 if (!TYPE_FIELDS (scope))
28850 return type;
28851 /* If the SCOPE is not the current instantiation, there's no reason
28852 to look inside it. */
28853 if (only_current_p && !currently_open_class (scope))
28854 return type;
28855 /* Enter the SCOPE so that name lookup will be resolved as if we
28856 were in the class definition. In particular, SCOPE will no
28857 longer be considered a dependent type. */
28858 pushed_scope = push_scope (scope);
28859 /* Look up the declaration. */
28860 decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true,
28861 tf_warning_or_error);
28863 result = NULL_TREE;
28865 /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
28866 find a TEMPLATE_DECL. Otherwise, we want to find a TYPE_DECL. */
28867 tree fullname = TYPENAME_TYPE_FULLNAME (type);
28868 if (!decl)
28869 /*nop*/;
28870 else if (identifier_p (fullname)
28871 && TREE_CODE (decl) == TYPE_DECL)
28873 result = TREE_TYPE (decl);
28874 if (result == error_mark_node)
28875 result = NULL_TREE;
28877 else if (TREE_CODE (fullname) == TEMPLATE_ID_EXPR
28878 && DECL_CLASS_TEMPLATE_P (decl))
28880 /* Obtain the template and the arguments. */
28881 tree tmpl = TREE_OPERAND (fullname, 0);
28882 if (TREE_CODE (tmpl) == IDENTIFIER_NODE)
28884 /* We get here with a plain identifier because a previous tentative
28885 parse of the nested-name-specifier as part of a ptr-operator saw
28886 ::template X<A>. The use of ::template is necessary in a
28887 ptr-operator, but wrong in a declarator-id.
28889 [temp.names]: In a qualified-id of a declarator-id, the keyword
28890 template shall not appear at the top level. */
28891 pedwarn (cp_expr_loc_or_input_loc (fullname), OPT_Wpedantic,
28892 "keyword %<template%> not allowed in declarator-id");
28893 tmpl = decl;
28895 tree args = TREE_OPERAND (fullname, 1);
28896 /* Instantiate the template. */
28897 result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
28898 /*entering_scope=*/true,
28899 tf_error | tf_user);
28900 if (result == error_mark_node)
28901 result = NULL_TREE;
28904 /* Leave the SCOPE. */
28905 if (pushed_scope)
28906 pop_scope (pushed_scope);
28908 /* If we failed to resolve it, return the original typename. */
28909 if (!result)
28910 return type;
28912 /* If lookup found a typename type, resolve that too. */
28913 if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
28915 /* Ill-formed programs can cause infinite recursion here, so we
28916 must catch that. */
28917 TYPENAME_IS_RESOLVING_P (result) = 1;
28918 result = resolve_typename_type (result, only_current_p);
28919 TYPENAME_IS_RESOLVING_P (result) = 0;
28922 /* Qualify the resulting type. */
28923 quals = cp_type_quals (type);
28924 if (quals)
28925 result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
28927 return result;
28930 /* Returns a type which represents 'auto' or 'decltype(auto)'. We use a
28931 TEMPLATE_TYPE_PARM with a level one deeper than the actual template parms,
28932 by default. If set_canonical is true, we set TYPE_CANONICAL on it. */
28934 static tree
28935 make_auto_1 (tree name, bool set_canonical, int level = -1)
28937 if (level == -1)
28938 level = current_template_depth + 1;
28939 tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
28940 TYPE_NAME (au) = build_decl (input_location, TYPE_DECL, name, au);
28941 TYPE_STUB_DECL (au) = TYPE_NAME (au);
28942 TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
28943 (0, level, level, TYPE_NAME (au), NULL_TREE);
28944 if (set_canonical)
28945 TYPE_CANONICAL (au) = canonical_type_parameter (au);
28946 DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
28947 SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
28948 if (name == decltype_auto_identifier)
28949 AUTO_IS_DECLTYPE (au) = true;
28951 return au;
28954 tree
28955 make_decltype_auto (void)
28957 return make_auto_1 (decltype_auto_identifier, true);
28960 tree
28961 make_auto (void)
28963 return make_auto_1 (auto_identifier, true);
28966 /* Return a C++17 deduction placeholder for class template TMPL.
28967 There are represented as an 'auto' with the special level 0 and
28968 CLASS_PLACEHOLDER_TEMPLATE set. */
28970 tree
28971 make_template_placeholder (tree tmpl)
28973 tree t = make_auto_1 (auto_identifier, false, /*level=*/0);
28974 CLASS_PLACEHOLDER_TEMPLATE (t) = tmpl;
28975 /* Our canonical type depends on the placeholder. */
28976 TYPE_CANONICAL (t) = canonical_type_parameter (t);
28977 return t;
28980 /* True iff T is a C++17 class template deduction placeholder. */
28982 bool
28983 template_placeholder_p (tree t)
28985 return is_auto (t) && CLASS_PLACEHOLDER_TEMPLATE (t);
28988 /* Make a "constrained auto" type-specifier. This is an auto or
28989 decltype(auto) type with constraints that must be associated after
28990 deduction. The constraint is formed from the given concept CON
28991 and its optional sequence of template arguments ARGS.
28993 TYPE must be the result of make_auto_type or make_decltype_auto_type. */
28995 static tree
28996 make_constrained_placeholder_type (tree type, tree con, tree args)
28998 /* Build the constraint. */
28999 tree tmpl = DECL_TI_TEMPLATE (con);
29000 tree expr = tmpl;
29001 if (TREE_CODE (con) == FUNCTION_DECL)
29002 expr = ovl_make (tmpl);
29003 ++processing_template_decl;
29004 expr = build_concept_check (expr, type, args, tf_warning_or_error);
29005 --processing_template_decl;
29007 PLACEHOLDER_TYPE_CONSTRAINTS_INFO (type)
29008 = build_tree_list (current_template_parms, expr);
29010 /* Our canonical type depends on the constraint. */
29011 TYPE_CANONICAL (type) = canonical_type_parameter (type);
29013 /* Attach the constraint to the type declaration. */
29014 return TYPE_NAME (type);
29017 /* Make a "constrained auto" type-specifier. */
29019 tree
29020 make_constrained_auto (tree con, tree args)
29022 tree type = make_auto_1 (auto_identifier, false);
29023 return make_constrained_placeholder_type (type, con, args);
29026 /* Make a "constrained decltype(auto)" type-specifier. */
29028 tree
29029 make_constrained_decltype_auto (tree con, tree args)
29031 tree type = make_auto_1 (decltype_auto_identifier, false);
29032 return make_constrained_placeholder_type (type, con, args);
29035 /* Returns true if the placeholder type constraint T has any dependent
29036 (explicit) template arguments. */
29038 static bool
29039 placeholder_type_constraint_dependent_p (tree t)
29041 tree id = unpack_concept_check (t);
29042 tree args = TREE_OPERAND (id, 1);
29043 tree first = TREE_VEC_ELT (args, 0);
29044 if (ARGUMENT_PACK_P (first))
29046 args = expand_template_argument_pack (args);
29047 first = TREE_VEC_ELT (args, 0);
29049 gcc_checking_assert (TREE_CODE (first) == WILDCARD_DECL
29050 || is_auto (first));
29051 for (int i = 1; i < TREE_VEC_LENGTH (args); ++i)
29052 if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
29053 return true;
29054 return false;
29057 /* Build and return a concept definition. Like other templates, the
29058 CONCEPT_DECL node is wrapped by a TEMPLATE_DECL. This returns the
29059 the TEMPLATE_DECL. */
29061 tree
29062 finish_concept_definition (cp_expr id, tree init, tree attrs)
29064 gcc_assert (identifier_p (id));
29065 gcc_assert (processing_template_decl);
29067 location_t loc = id.get_location();
29069 /* A concept-definition shall not have associated constraints. */
29070 if (TEMPLATE_PARMS_CONSTRAINTS (current_template_parms))
29072 error_at (loc, "a concept cannot be constrained");
29073 TEMPLATE_PARMS_CONSTRAINTS (current_template_parms) = NULL_TREE;
29076 /* A concept-definition shall appear in namespace scope. Templates
29077 aren't allowed in block scope, so we only need to check for class
29078 scope. */
29079 if (TYPE_P (current_scope()) || !DECL_NAMESPACE_SCOPE_P (current_scope ()))
29081 error_at (loc, "concept %qE not in namespace scope", *id);
29082 return error_mark_node;
29085 if (current_template_depth > 1)
29087 error_at (loc, "concept %qE has multiple template parameter lists", *id);
29088 return error_mark_node;
29091 /* Initially build the concept declaration; its type is bool. */
29092 tree decl = build_lang_decl_loc (loc, CONCEPT_DECL, *id, boolean_type_node);
29093 DECL_CONTEXT (decl) = current_scope ();
29094 DECL_INITIAL (decl) = init;
29096 if (attrs)
29097 cplus_decl_attributes (&decl, attrs, 0);
29099 set_originating_module (decl, false);
29101 /* Push the enclosing template. */
29102 return push_template_decl (decl);
29105 /* Given type ARG, return std::initializer_list<ARG>. */
29107 static tree
29108 listify (tree arg)
29110 tree std_init_list = lookup_qualified_name (std_node, init_list_identifier);
29112 if (std_init_list == error_mark_node
29113 || !DECL_CLASS_TEMPLATE_P (std_init_list))
29115 gcc_rich_location richloc (input_location);
29116 maybe_add_include_fixit (&richloc, "<initializer_list>", false);
29117 error_at (&richloc,
29118 "deducing from brace-enclosed initializer list"
29119 " requires %<#include <initializer_list>%>");
29121 return error_mark_node;
29123 tree argvec = make_tree_vec (1);
29124 TREE_VEC_ELT (argvec, 0) = arg;
29126 return lookup_template_class (std_init_list, argvec, NULL_TREE,
29127 NULL_TREE, 0, tf_warning_or_error);
29130 /* Replace auto in TYPE with std::initializer_list<auto>. */
29132 static tree
29133 listify_autos (tree type, tree auto_node)
29135 tree init_auto = listify (strip_top_quals (auto_node));
29136 tree argvec = make_tree_vec (1);
29137 TREE_VEC_ELT (argvec, 0) = init_auto;
29138 if (processing_template_decl)
29139 argvec = add_to_template_args (current_template_args (), argvec);
29140 return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
29143 /* Hash traits for hashing possibly constrained 'auto'
29144 TEMPLATE_TYPE_PARMs for use by do_auto_deduction. */
29146 struct auto_hash : default_hash_traits<tree>
29148 static inline hashval_t hash (tree);
29149 static inline bool equal (tree, tree);
29152 /* Hash the 'auto' T. */
29154 inline hashval_t
29155 auto_hash::hash (tree t)
29157 if (tree c = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (t)))
29158 /* Matching constrained-type-specifiers denote the same template
29159 parameter, so hash the constraint. */
29160 return hash_placeholder_constraint (c);
29161 else
29162 /* But unconstrained autos are all separate, so just hash the pointer. */
29163 return iterative_hash_object (t, 0);
29166 /* Compare two 'auto's. */
29168 inline bool
29169 auto_hash::equal (tree t1, tree t2)
29171 if (t1 == t2)
29172 return true;
29174 tree c1 = PLACEHOLDER_TYPE_CONSTRAINTS (t1);
29175 tree c2 = PLACEHOLDER_TYPE_CONSTRAINTS (t2);
29177 /* Two unconstrained autos are distinct. */
29178 if (!c1 || !c2)
29179 return false;
29181 return equivalent_placeholder_constraints (c1, c2);
29184 /* for_each_template_parm callback for extract_autos: if t is a (possibly
29185 constrained) auto, add it to the vector. */
29187 static int
29188 extract_autos_r (tree t, void *data)
29190 hash_table<auto_hash> &hash = *(hash_table<auto_hash>*)data;
29191 if (is_auto (t) && !template_placeholder_p (t))
29193 /* All the autos were built with index 0; fix that up now. */
29194 tree *p = hash.find_slot (t, INSERT);
29195 int idx;
29196 if (*p)
29197 /* If this is a repeated constrained-type-specifier, use the index we
29198 chose before. */
29199 idx = TEMPLATE_TYPE_IDX (*p);
29200 else
29202 /* Otherwise this is new, so use the current count. */
29203 *p = t;
29204 idx = hash.elements () - 1;
29206 if (idx != TEMPLATE_TYPE_IDX (t))
29208 gcc_checking_assert (TEMPLATE_TYPE_IDX (t) == 0);
29209 gcc_checking_assert (TYPE_CANONICAL (t) != t);
29210 TEMPLATE_TYPE_IDX (t) = idx;
29211 TYPE_CANONICAL (t) = canonical_type_parameter (t);
29215 /* Always keep walking. */
29216 return 0;
29219 /* Return a TREE_VEC of the 'auto's used in type under the Concepts TS, which
29220 says they can appear anywhere in the type. */
29222 static tree
29223 extract_autos (tree type)
29225 hash_set<tree> visited;
29226 hash_table<auto_hash> hash (2);
29228 for_each_template_parm (type, extract_autos_r, &hash, &visited, true);
29230 tree tree_vec = make_tree_vec (hash.elements());
29231 for (tree elt : hash)
29233 unsigned i = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (elt));
29234 TREE_VEC_ELT (tree_vec, i)
29235 = build_tree_list (NULL_TREE, TYPE_NAME (elt));
29238 return tree_vec;
29241 /* The stem for deduction guide names. */
29242 const char *const dguide_base = "__dguide_";
29244 /* Return the name for a deduction guide for class template TMPL. */
29246 tree
29247 dguide_name (tree tmpl)
29249 tree type = (TYPE_P (tmpl) ? tmpl : TREE_TYPE (tmpl));
29250 tree tname = TYPE_IDENTIFIER (type);
29251 char *buf = (char *) alloca (1 + strlen (dguide_base)
29252 + IDENTIFIER_LENGTH (tname));
29253 memcpy (buf, dguide_base, strlen (dguide_base));
29254 memcpy (buf + strlen (dguide_base), IDENTIFIER_POINTER (tname),
29255 IDENTIFIER_LENGTH (tname) + 1);
29256 tree dname = get_identifier (buf);
29257 TREE_TYPE (dname) = type;
29258 return dname;
29261 /* True if NAME is the name of a deduction guide. */
29263 bool
29264 dguide_name_p (tree name)
29266 return (TREE_CODE (name) == IDENTIFIER_NODE
29267 && TREE_TYPE (name)
29268 && startswith (IDENTIFIER_POINTER (name), dguide_base));
29271 /* True if FN is a deduction guide. */
29273 bool
29274 deduction_guide_p (const_tree fn)
29276 if (DECL_P (fn))
29277 if (tree name = DECL_NAME (fn))
29278 return dguide_name_p (name);
29279 return false;
29282 /* True if FN is the copy deduction guide, i.e. A(A)->A. */
29284 bool
29285 copy_guide_p (const_tree fn)
29287 gcc_assert (deduction_guide_p (fn));
29288 if (!DECL_ARTIFICIAL (fn))
29289 return false;
29290 tree parms = FUNCTION_FIRST_USER_PARMTYPE (DECL_TI_TEMPLATE (fn));
29291 return (TREE_CHAIN (parms) == void_list_node
29292 && same_type_p (TREE_VALUE (parms), TREE_TYPE (DECL_NAME (fn))));
29295 /* True if FN is a guide generated from a constructor template. */
29297 bool
29298 template_guide_p (const_tree fn)
29300 gcc_assert (deduction_guide_p (fn));
29301 if (!DECL_ARTIFICIAL (fn))
29302 return false;
29303 tree tmpl = DECL_TI_TEMPLATE (fn);
29304 if (tree org = DECL_ABSTRACT_ORIGIN (tmpl))
29305 return PRIMARY_TEMPLATE_P (org);
29306 return false;
29309 /* True if FN is an aggregate initialization guide or the copy deduction
29310 guide. */
29312 bool
29313 builtin_guide_p (const_tree fn)
29315 if (!deduction_guide_p (fn))
29316 return false;
29317 if (!DECL_ARTIFICIAL (fn))
29318 /* Explicitly declared. */
29319 return false;
29320 if (DECL_ABSTRACT_ORIGIN (fn))
29321 /* Derived from a constructor. */
29322 return false;
29323 return true;
29326 /* OLDDECL is a _DECL for a template parameter. Return a similar parameter at
29327 LEVEL:INDEX, using tsubst_args and complain for substitution into non-type
29328 template parameter types. Note that the handling of template template
29329 parameters relies on current_template_parms being set appropriately for the
29330 new template. */
29332 static tree
29333 rewrite_template_parm (tree olddecl, unsigned index, unsigned level,
29334 tree tsubst_args, tsubst_flags_t complain)
29336 if (olddecl == error_mark_node)
29337 return error_mark_node;
29339 tree oldidx = get_template_parm_index (olddecl);
29341 tree newtype;
29342 if (TREE_CODE (olddecl) == TYPE_DECL
29343 || TREE_CODE (olddecl) == TEMPLATE_DECL)
29345 tree oldtype = TREE_TYPE (olddecl);
29346 newtype = cxx_make_type (TREE_CODE (oldtype));
29347 TYPE_MAIN_VARIANT (newtype) = newtype;
29349 else
29351 newtype = TREE_TYPE (olddecl);
29352 if (type_uses_auto (newtype))
29354 // Substitute once to fix references to other template parameters.
29355 newtype = tsubst (newtype, tsubst_args,
29356 complain|tf_partial, NULL_TREE);
29357 // Now substitute again to reduce the level of the auto.
29358 newtype = tsubst (newtype, current_template_args (),
29359 complain, NULL_TREE);
29361 else
29362 newtype = tsubst (newtype, tsubst_args,
29363 complain, NULL_TREE);
29366 tree newdecl
29367 = build_decl (DECL_SOURCE_LOCATION (olddecl), TREE_CODE (olddecl),
29368 DECL_NAME (olddecl), newtype);
29369 SET_DECL_TEMPLATE_PARM_P (newdecl);
29371 tree newidx;
29372 if (TREE_CODE (olddecl) == TYPE_DECL
29373 || TREE_CODE (olddecl) == TEMPLATE_DECL)
29375 newidx = TEMPLATE_TYPE_PARM_INDEX (newtype)
29376 = build_template_parm_index (index, level, level,
29377 newdecl, newtype);
29378 TEMPLATE_PARM_PARAMETER_PACK (newidx)
29379 = TEMPLATE_PARM_PARAMETER_PACK (oldidx);
29380 TYPE_STUB_DECL (newtype) = TYPE_NAME (newtype) = newdecl;
29382 if (TREE_CODE (olddecl) == TEMPLATE_DECL)
29384 tree newresult
29385 = build_lang_decl_loc (DECL_SOURCE_LOCATION (olddecl), TYPE_DECL,
29386 DECL_NAME (olddecl), newtype);
29387 DECL_ARTIFICIAL (newresult) = true;
29388 DECL_TEMPLATE_RESULT (newdecl) = newresult;
29389 // First create a copy (ttargs) of tsubst_args with an
29390 // additional level for the template template parameter's own
29391 // template parameters (ttparms).
29392 tree ttparms = (INNERMOST_TEMPLATE_PARMS
29393 (DECL_TEMPLATE_PARMS (olddecl)));
29394 const int depth = TMPL_ARGS_DEPTH (tsubst_args);
29395 tree ttargs = make_tree_vec (depth + 1);
29396 for (int i = 0; i < depth; ++i)
29397 TREE_VEC_ELT (ttargs, i) = TMPL_ARGS_LEVEL (tsubst_args, i + 1);
29398 TREE_VEC_ELT (ttargs, depth)
29399 = template_parms_level_to_args (ttparms);
29400 // Substitute ttargs into ttparms to fix references to
29401 // other template parameters.
29402 ttparms = tsubst_template_parms_level (ttparms, ttargs,
29403 complain|tf_partial);
29404 // Now substitute again with args based on tparms, to reduce
29405 // the level of the ttparms.
29406 ttargs = current_template_args ();
29407 ttparms = tsubst_template_parms_level (ttparms, ttargs,
29408 complain);
29409 // Finally, tack the adjusted parms onto tparms.
29410 ttparms = tree_cons (size_int (level + 1), ttparms,
29411 copy_node (current_template_parms));
29412 // As with all template template parms, the parameter list captured
29413 // by this template template parm that corresponds to its own level
29414 // should be empty. This avoids infinite recursion when structurally
29415 // comparing two such rewritten template template parms (PR102479).
29416 gcc_assert (!TREE_VEC_LENGTH
29417 (TREE_VALUE (TREE_CHAIN (DECL_TEMPLATE_PARMS (olddecl)))));
29418 gcc_assert (TMPL_PARMS_DEPTH (TREE_CHAIN (ttparms)) == level);
29419 TREE_VALUE (TREE_CHAIN (ttparms)) = make_tree_vec (0);
29420 // All done.
29421 DECL_TEMPLATE_PARMS (newdecl) = ttparms;
29422 DECL_TEMPLATE_INFO (newresult)
29423 = build_template_info (newdecl, template_parms_to_args (ttparms));
29426 if (TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (olddecl)))
29427 SET_TYPE_STRUCTURAL_EQUALITY (newtype);
29428 else
29429 TYPE_CANONICAL (newtype) = canonical_type_parameter (newtype);
29431 else
29433 tree oldconst = TEMPLATE_PARM_DECL (oldidx);
29434 tree newconst
29435 = build_decl (DECL_SOURCE_LOCATION (oldconst),
29436 TREE_CODE (oldconst),
29437 DECL_NAME (oldconst), newtype);
29438 TREE_CONSTANT (newconst) = TREE_CONSTANT (newdecl)
29439 = TREE_READONLY (newconst) = TREE_READONLY (newdecl) = true;
29440 SET_DECL_TEMPLATE_PARM_P (newconst);
29441 newidx = build_template_parm_index (index, level, level,
29442 newconst, newtype);
29443 TEMPLATE_PARM_PARAMETER_PACK (newidx)
29444 = TEMPLATE_PARM_PARAMETER_PACK (oldidx);
29445 DECL_INITIAL (newdecl) = DECL_INITIAL (newconst) = newidx;
29448 return newdecl;
29451 /* As rewrite_template_parm, but for the whole TREE_LIST representing a
29452 template parameter. */
29454 static tree
29455 rewrite_tparm_list (tree oldelt, unsigned index, unsigned level,
29456 tree targs, unsigned targs_index, tsubst_flags_t complain)
29458 tree olddecl = TREE_VALUE (oldelt);
29459 tree newdecl = rewrite_template_parm (olddecl, index, level,
29460 targs, complain);
29461 if (newdecl == error_mark_node)
29462 return error_mark_node;
29463 tree newdef = tsubst_template_arg (TREE_PURPOSE (oldelt),
29464 targs, complain, NULL_TREE);
29465 tree list = build_tree_list (newdef, newdecl);
29466 TEMPLATE_PARM_CONSTRAINTS (list)
29467 = tsubst_constraint_info (TEMPLATE_PARM_CONSTRAINTS (oldelt),
29468 targs, complain, NULL_TREE);
29469 int depth = TMPL_ARGS_DEPTH (targs);
29470 TMPL_ARG (targs, depth, targs_index) = template_parm_to_arg (list);
29471 return list;
29474 /* Returns a C++17 class deduction guide template based on the constructor
29475 CTOR. As a special case, CTOR can be a RECORD_TYPE for an implicit default
29476 guide, REFERENCE_TYPE for an implicit copy/move guide, or TREE_LIST for an
29477 aggregate initialization guide. OUTER_ARGS are the template arguments
29478 for the enclosing scope of the class. */
29480 static tree
29481 build_deduction_guide (tree type, tree ctor, tree outer_args, tsubst_flags_t complain)
29483 tree tparms, targs, fparms, fargs, ci;
29484 bool memtmpl = false;
29485 bool explicit_p;
29486 location_t loc;
29487 tree fn_tmpl = NULL_TREE;
29489 if (outer_args)
29491 ++processing_template_decl;
29492 type = tsubst (type, outer_args, complain, CLASSTYPE_TI_TEMPLATE (type));
29493 --processing_template_decl;
29496 if (!DECL_DECLARES_FUNCTION_P (ctor))
29498 if (TYPE_P (ctor))
29500 bool copy_p = TYPE_REF_P (ctor);
29501 if (copy_p)
29502 fparms = tree_cons (NULL_TREE, type, void_list_node);
29503 else
29504 fparms = void_list_node;
29506 else if (TREE_CODE (ctor) == TREE_LIST)
29507 fparms = ctor;
29508 else
29509 gcc_unreachable ();
29511 tree ctmpl = CLASSTYPE_TI_TEMPLATE (type);
29512 tparms = DECL_TEMPLATE_PARMS (ctmpl);
29513 targs = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
29514 ci = NULL_TREE;
29515 fargs = NULL_TREE;
29516 loc = DECL_SOURCE_LOCATION (ctmpl);
29517 explicit_p = false;
29519 else
29521 ++processing_template_decl;
29522 bool ok = true;
29524 complain |= tf_dguide;
29526 fn_tmpl
29527 = (TREE_CODE (ctor) == TEMPLATE_DECL ? ctor
29528 : DECL_TI_TEMPLATE (ctor));
29529 if (outer_args)
29530 fn_tmpl = tsubst (fn_tmpl, outer_args, complain, ctor);
29531 ctor = DECL_TEMPLATE_RESULT (fn_tmpl);
29533 tparms = DECL_TEMPLATE_PARMS (fn_tmpl);
29534 /* If type is a member class template, DECL_TI_ARGS (ctor) will have
29535 fully specialized args for the enclosing class. Strip those off, as
29536 the deduction guide won't have those template parameters. */
29537 targs = get_innermost_template_args (DECL_TI_ARGS (ctor),
29538 TMPL_PARMS_DEPTH (tparms));
29539 /* Discard the 'this' parameter. */
29540 fparms = FUNCTION_ARG_CHAIN (ctor);
29541 fargs = TREE_CHAIN (DECL_ARGUMENTS (ctor));
29542 ci = get_constraints (ctor);
29543 loc = DECL_SOURCE_LOCATION (ctor);
29544 explicit_p = DECL_NONCONVERTING_P (ctor);
29546 if (PRIMARY_TEMPLATE_P (fn_tmpl))
29548 memtmpl = true;
29550 /* For a member template constructor, we need to flatten the two
29551 template parameter lists into one, and then adjust the function
29552 signature accordingly. This gets...complicated. */
29553 tree save_parms = current_template_parms;
29555 /* For a member template we should have two levels of parms/args, one
29556 for the class and one for the constructor. We stripped
29557 specialized args for further enclosing classes above. */
29558 const int depth = 2;
29559 gcc_assert (TMPL_ARGS_DEPTH (targs) == depth);
29561 /* Template args for translating references to the two-level template
29562 parameters into references to the one-level template parameters we
29563 are creating. */
29564 tree tsubst_args = copy_node (targs);
29565 TMPL_ARGS_LEVEL (tsubst_args, depth)
29566 = copy_node (TMPL_ARGS_LEVEL (tsubst_args, depth));
29568 /* Template parms for the constructor template. */
29569 tree ftparms = TREE_VALUE (tparms);
29570 unsigned flen = TREE_VEC_LENGTH (ftparms);
29571 /* Template parms for the class template. */
29572 tparms = TREE_CHAIN (tparms);
29573 tree ctparms = TREE_VALUE (tparms);
29574 unsigned clen = TREE_VEC_LENGTH (ctparms);
29575 /* Template parms for the deduction guide start as a copy of the
29576 template parms for the class. We set current_template_parms for
29577 lookup_template_class_1. */
29578 current_template_parms = tparms = copy_node (tparms);
29579 tree new_vec = TREE_VALUE (tparms) = make_tree_vec (flen + clen);
29580 for (unsigned i = 0; i < clen; ++i)
29581 TREE_VEC_ELT (new_vec, i) = TREE_VEC_ELT (ctparms, i);
29583 /* Now we need to rewrite the constructor parms to append them to the
29584 class parms. */
29585 for (unsigned i = 0; i < flen; ++i)
29587 unsigned index = i + clen;
29588 unsigned level = 1;
29589 tree oldelt = TREE_VEC_ELT (ftparms, i);
29590 tree newelt
29591 = rewrite_tparm_list (oldelt, index, level,
29592 tsubst_args, i, complain);
29593 if (newelt == error_mark_node)
29594 ok = false;
29595 TREE_VEC_ELT (new_vec, index) = newelt;
29598 /* Now we have a final set of template parms to substitute into the
29599 function signature. */
29600 targs = template_parms_to_args (tparms);
29601 fparms = tsubst_arg_types (fparms, tsubst_args, NULL_TREE,
29602 complain, ctor);
29603 if (fparms == error_mark_node)
29604 ok = false;
29605 if (ci)
29607 if (outer_args)
29608 /* FIXME: We'd like to avoid substituting outer template
29609 arguments into the constraint ahead of time, but the
29610 construction of tsubst_args assumes that outer arguments
29611 are already substituted in. */
29612 ci = tsubst_constraint_info (ci, outer_args, complain, ctor);
29613 ci = tsubst_constraint_info (ci, tsubst_args, complain, ctor);
29616 /* Parms are to have DECL_CHAIN tsubsted, which would be skipped if
29617 cp_unevaluated_operand. */
29618 cp_evaluated ev;
29619 fargs = tsubst (fargs, tsubst_args, complain, ctor);
29620 current_template_parms = save_parms;
29622 else
29624 /* Substitute in the same arguments to rewrite class members into
29625 references to members of an unknown specialization. */
29626 cp_evaluated ev;
29627 fparms = tsubst_arg_types (fparms, targs, NULL_TREE, complain, ctor);
29628 fargs = tsubst (fargs, targs, complain, ctor);
29629 if (ci)
29631 if (outer_args)
29632 /* FIXME: As above. */
29633 ci = tsubst_constraint_info (ci, outer_args, complain, ctor);
29634 ci = tsubst_constraint_info (ci, targs, complain, ctor);
29638 --processing_template_decl;
29639 if (!ok)
29640 return error_mark_node;
29643 if (!memtmpl)
29645 /* Copy the parms so we can set DECL_PRIMARY_TEMPLATE. */
29646 tparms = copy_node (tparms);
29647 INNERMOST_TEMPLATE_PARMS (tparms)
29648 = copy_node (INNERMOST_TEMPLATE_PARMS (tparms));
29651 tree fntype = build_function_type (type, fparms);
29652 tree ded_fn = build_lang_decl_loc (loc,
29653 FUNCTION_DECL,
29654 dguide_name (type), fntype);
29655 DECL_ARGUMENTS (ded_fn) = fargs;
29656 DECL_ARTIFICIAL (ded_fn) = true;
29657 DECL_NONCONVERTING_P (ded_fn) = explicit_p;
29658 tree ded_tmpl = build_template_decl (ded_fn, tparms, /*member*/false);
29659 DECL_ARTIFICIAL (ded_tmpl) = true;
29660 DECL_TEMPLATE_INFO (ded_fn) = build_template_info (ded_tmpl, targs);
29661 DECL_PRIMARY_TEMPLATE (ded_tmpl) = ded_tmpl;
29662 if (DECL_P (ctor))
29663 DECL_ABSTRACT_ORIGIN (ded_tmpl) = fn_tmpl;
29664 if (ci)
29665 set_constraints (ded_tmpl, ci);
29667 return ded_tmpl;
29670 /* Add to LIST the member types for the reshaped initializer CTOR. */
29672 static tree
29673 collect_ctor_idx_types (tree ctor, tree list, tree elt = NULL_TREE)
29675 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (ctor);
29676 tree idx, val; unsigned i;
29677 FOR_EACH_CONSTRUCTOR_ELT (v, i, idx, val)
29679 tree ftype = elt ? elt : TREE_TYPE (idx);
29680 if (BRACE_ENCLOSED_INITIALIZER_P (val)
29681 && CONSTRUCTOR_BRACES_ELIDED_P (val))
29683 tree subelt = NULL_TREE;
29684 if (TREE_CODE (ftype) == ARRAY_TYPE)
29685 subelt = TREE_TYPE (ftype);
29686 list = collect_ctor_idx_types (val, list, subelt);
29687 continue;
29689 tree arg = NULL_TREE;
29690 if (i == v->length() - 1
29691 && PACK_EXPANSION_P (ftype))
29692 /* Give the trailing pack expansion parameter a default argument to
29693 match aggregate initialization behavior, even if we deduce the
29694 length of the pack separately to more than we have initializers. */
29695 arg = build_constructor (init_list_type_node, NULL);
29696 /* if ei is of array type and xi is a braced-init-list or string literal,
29697 Ti is an rvalue reference to the declared type of ei */
29698 STRIP_ANY_LOCATION_WRAPPER (val);
29699 if (TREE_CODE (ftype) == ARRAY_TYPE
29700 && (BRACE_ENCLOSED_INITIALIZER_P (val)
29701 || TREE_CODE (val) == STRING_CST))
29703 if (TREE_CODE (val) == STRING_CST)
29704 ftype = cp_build_qualified_type
29705 (ftype, cp_type_quals (ftype) | TYPE_QUAL_CONST);
29706 ftype = (cp_build_reference_type
29707 (ftype, BRACE_ENCLOSED_INITIALIZER_P (val)));
29709 list = tree_cons (arg, ftype, list);
29712 return list;
29715 /* Return whether ETYPE is, or is derived from, a specialization of TMPL. */
29717 static bool
29718 is_spec_or_derived (tree etype, tree tmpl)
29720 if (!etype || !CLASS_TYPE_P (etype))
29721 return false;
29723 etype = cv_unqualified (etype);
29724 tree type = TREE_TYPE (tmpl);
29725 tree tparms = (INNERMOST_TEMPLATE_PARMS
29726 (DECL_TEMPLATE_PARMS (tmpl)));
29727 tree targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
29728 int err = unify (tparms, targs, type, etype,
29729 UNIFY_ALLOW_DERIVED, /*explain*/false);
29730 ggc_free (targs);
29731 return !err;
29734 static tree alias_ctad_tweaks (tree, tree);
29736 /* Return a C++20 aggregate deduction candidate for TYPE initialized from
29737 INIT. */
29739 static tree
29740 maybe_aggr_guide (tree tmpl, tree init, vec<tree,va_gc> *args)
29742 if (cxx_dialect < cxx20)
29743 return NULL_TREE;
29745 if (init == NULL_TREE)
29746 return NULL_TREE;
29748 if (DECL_ALIAS_TEMPLATE_P (tmpl))
29750 tree under = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
29751 tree tinfo = get_template_info (under);
29752 if (tree guide = maybe_aggr_guide (TI_TEMPLATE (tinfo), init, args))
29753 return alias_ctad_tweaks (tmpl, guide);
29754 return NULL_TREE;
29757 /* We might be creating a guide for a class member template, e.g.,
29759 template<typename U> struct A {
29760 template<typename T> struct B { T t; };
29763 At this point, A will have been instantiated. Below, we need to
29764 use both A<U>::B<T> (TEMPLATE_TYPE) and A<int>::B<T> (TYPE) types. */
29765 const bool member_template_p
29766 = (DECL_TEMPLATE_INFO (tmpl)
29767 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (tmpl)));
29768 tree type = TREE_TYPE (tmpl);
29769 tree template_type = (member_template_p
29770 ? TREE_TYPE (DECL_TI_TEMPLATE (tmpl))
29771 : type);
29772 if (!CP_AGGREGATE_TYPE_P (template_type))
29773 return NULL_TREE;
29775 /* No aggregate candidate for copy-initialization. */
29776 if (args->length() == 1)
29778 tree val = (*args)[0];
29779 if (is_spec_or_derived (TREE_TYPE (val), tmpl))
29780 return NULL_TREE;
29783 /* If we encounter a problem, we just won't add the candidate. */
29784 tsubst_flags_t complain = tf_none;
29786 tree parms = NULL_TREE;
29787 if (BRACE_ENCLOSED_INITIALIZER_P (init))
29789 init = reshape_init (template_type, init, complain);
29790 if (init == error_mark_node)
29791 return NULL_TREE;
29792 parms = collect_ctor_idx_types (init, parms);
29793 /* If we're creating a deduction guide for a member class template,
29794 we've used the original template pattern type for the reshape_init
29795 above; this is done because we want PARMS to be a template parameter
29796 type, something that can be deduced when used as a function template
29797 parameter. At this point the outer class template has already been
29798 partially instantiated (we deferred the deduction until the enclosing
29799 scope is non-dependent). Therefore we have to partially instantiate
29800 PARMS, so that its template level is properly reduced and we don't get
29801 mismatches when deducing types using the guide with PARMS. */
29802 if (member_template_p)
29804 ++processing_template_decl;
29805 parms = tsubst (parms, DECL_TI_ARGS (tmpl), complain, init);
29806 --processing_template_decl;
29809 else if (TREE_CODE (init) == TREE_LIST)
29811 int len = list_length (init);
29812 for (tree field = TYPE_FIELDS (type);
29813 len;
29814 --len, field = DECL_CHAIN (field))
29816 field = next_aggregate_field (field);
29817 if (!field)
29818 return NULL_TREE;
29819 tree ftype = finish_decltype_type (field, true, complain);
29820 parms = tree_cons (NULL_TREE, ftype, parms);
29823 else
29824 /* Aggregate initialization doesn't apply to an initializer expression. */
29825 return NULL_TREE;
29827 if (parms)
29829 tree last = parms;
29830 parms = nreverse (parms);
29831 TREE_CHAIN (last) = void_list_node;
29832 tree guide = build_deduction_guide (type, parms, NULL_TREE, complain);
29833 return guide;
29836 return NULL_TREE;
29839 /* UGUIDES are the deduction guides for the underlying template of alias
29840 template TMPL; adjust them to be deduction guides for TMPL. */
29842 static tree
29843 alias_ctad_tweaks (tree tmpl, tree uguides)
29845 /* [over.match.class.deduct]: When resolving a placeholder for a deduced
29846 class type (9.2.8.2) where the template-name names an alias template A,
29847 the defining-type-id of A must be of the form
29849 typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
29851 as specified in 9.2.8.2. The guides of A are the set of functions or
29852 function templates formed as follows. For each function or function
29853 template f in the guides of the template named by the simple-template-id
29854 of the defining-type-id, the template arguments of the return type of f
29855 are deduced from the defining-type-id of A according to the process in
29856 13.10.2.5 with the exception that deduction does not fail if not all
29857 template arguments are deduced. Let g denote the result of substituting
29858 these deductions into f. If substitution succeeds, form a function or
29859 function template f' with the following properties and add it to the set
29860 of guides of A:
29862 * The function type of f' is the function type of g.
29864 * If f is a function template, f' is a function template whose template
29865 parameter list consists of all the template parameters of A (including
29866 their default template arguments) that appear in the above deductions or
29867 (recursively) in their default template arguments, followed by the
29868 template parameters of f that were not deduced (including their default
29869 template arguments), otherwise f' is not a function template.
29871 * The associated constraints (13.5.2) are the conjunction of the
29872 associated constraints of g and a constraint that is satisfied if and only
29873 if the arguments of A are deducible (see below) from the return type.
29875 * If f is a copy deduction candidate (12.4.1.8), then f' is considered to
29876 be so as well.
29878 * If f was generated from a deduction-guide (12.4.1.8), then f' is
29879 considered to be so as well.
29881 * The explicit-specifier of f' is the explicit-specifier of g (if
29882 any). */
29884 tsubst_flags_t complain = tf_warning_or_error;
29885 tree atype = TREE_TYPE (tmpl);
29886 tree aguides = NULL_TREE;
29887 tree fullatparms = DECL_TEMPLATE_PARMS (tmpl);
29888 tree atparms = INNERMOST_TEMPLATE_PARMS (fullatparms);
29889 unsigned natparms = TREE_VEC_LENGTH (atparms);
29890 tree utype = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
29891 for (ovl_iterator iter (uguides); iter; ++iter)
29893 tree f = *iter;
29894 tree in_decl = f;
29895 location_t loc = DECL_SOURCE_LOCATION (f);
29896 tree ret = TREE_TYPE (TREE_TYPE (f));
29897 tree fprime = f;
29898 if (TREE_CODE (f) == TEMPLATE_DECL)
29900 processing_template_decl_sentinel ptds (/*reset*/false);
29901 ++processing_template_decl;
29903 /* Deduce template arguments for f from the type-id of A. */
29904 tree ftparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (f));
29905 unsigned len = TREE_VEC_LENGTH (ftparms);
29906 tree targs = make_tree_vec (len);
29907 int err = unify (ftparms, targs, ret, utype, UNIFY_ALLOW_NONE, false);
29908 if (err)
29909 /* CWG2664: Discard any deductions, still build the guide. */
29910 for (unsigned i = 0; i < len; ++i)
29911 TREE_VEC_ELT (targs, i) = NULL_TREE;
29913 /* The number of parms for f' is the number of parms of A used in
29914 the deduced arguments plus non-deduced parms of f. */
29915 unsigned ndlen = 0;
29916 unsigned j;
29917 for (unsigned i = 0; i < len; ++i)
29918 if (TREE_VEC_ELT (targs, i) == NULL_TREE)
29919 ++ndlen;
29920 find_template_parameter_info ftpi (fullatparms);
29921 ftpi.find_in_recursive (targs);
29922 unsigned nusedatparms = ftpi.num_found ();
29923 unsigned nfparms = nusedatparms + ndlen;
29924 tree gtparms = make_tree_vec (nfparms);
29926 /* Set current_template_parms as in build_deduction_guide. */
29927 auto ctp = make_temp_override (current_template_parms);
29928 current_template_parms = copy_node (DECL_TEMPLATE_PARMS (tmpl));
29929 TREE_VALUE (current_template_parms) = gtparms;
29931 j = 0;
29932 unsigned level = 1;
29934 /* First copy over the used parms of A. */
29935 tree atargs = make_tree_vec (natparms);
29936 for (unsigned i = 0; i < natparms; ++i)
29938 tree elt = TREE_VEC_ELT (atparms, i);
29939 if (ftpi.found (elt))
29941 unsigned index = j++;
29942 tree nelt = rewrite_tparm_list (elt, index, level,
29943 atargs, i, complain);
29944 TREE_VEC_ELT (gtparms, index) = nelt;
29947 gcc_checking_assert (j == nusedatparms);
29949 /* Adjust the deduced template args for f to refer to the A parms
29950 with their new indexes. */
29951 if (nusedatparms && nusedatparms != natparms)
29952 targs = tsubst_template_args (targs, atargs, complain, in_decl);
29954 /* Now rewrite the non-deduced parms of f. */
29955 for (unsigned i = 0; ndlen && i < len; ++i)
29956 if (TREE_VEC_ELT (targs, i) == NULL_TREE)
29958 --ndlen;
29959 unsigned index = j++;
29960 tree oldlist = TREE_VEC_ELT (ftparms, i);
29961 tree list = rewrite_tparm_list (oldlist, index, level,
29962 targs, i, complain);
29963 TREE_VEC_ELT (gtparms, index) = list;
29965 gtparms = build_tree_list (size_one_node, gtparms);
29967 /* Substitute the deduced arguments plus the rewritten template
29968 parameters into f to get g. This covers the type, copyness,
29969 guideness, and explicit-specifier. */
29970 tree g;
29972 /* Parms are to have DECL_CHAIN tsubsted, which would be skipped
29973 if cp_unevaluated_operand. */
29974 cp_evaluated ev;
29975 g = tsubst_decl (DECL_TEMPLATE_RESULT (f), targs, complain);
29977 if (g == error_mark_node)
29978 continue;
29979 if (nfparms == 0)
29981 /* The targs are all non-dependent, so g isn't a template. */
29982 fprime = g;
29983 ret = TREE_TYPE (TREE_TYPE (fprime));
29984 goto non_template;
29986 DECL_USE_TEMPLATE (g) = 0;
29987 fprime = build_template_decl (g, gtparms, false);
29988 DECL_TEMPLATE_RESULT (fprime) = g;
29989 TREE_TYPE (fprime) = TREE_TYPE (g);
29990 tree gtargs = template_parms_to_args (gtparms);
29991 DECL_TEMPLATE_INFO (g) = build_template_info (fprime, gtargs);
29992 DECL_PRIMARY_TEMPLATE (fprime) = fprime;
29994 /* Substitute the associated constraints. */
29995 tree ci = get_constraints (f);
29996 if (ci)
29997 ci = tsubst_constraint_info (ci, targs, complain, in_decl);
29998 if (ci == error_mark_node)
29999 continue;
30001 /* Add a constraint that the return type matches the instantiation of
30002 A with the same template arguments. */
30003 ret = TREE_TYPE (TREE_TYPE (fprime));
30004 if (!same_type_p (atype, ret)
30005 /* FIXME this should mean they don't compare as equivalent. */
30006 || dependent_alias_template_spec_p (atype, nt_opaque))
30008 tree same = finish_trait_expr (loc, CPTK_IS_DEDUCIBLE, tmpl, ret);
30009 ci = append_constraint (ci, same);
30012 if (ci)
30014 remove_constraints (fprime);
30015 set_constraints (fprime, ci);
30018 else
30020 /* For a non-template deduction guide, if the arguments of A aren't
30021 deducible from the return type, don't add the candidate. */
30022 non_template:
30023 if (!type_targs_deducible_from (tmpl, ret))
30024 continue;
30027 aguides = lookup_add (fprime, aguides);
30030 return aguides;
30033 /* True iff template arguments for TMPL can be deduced from TYPE.
30034 Used to implement CPTK_IS_DEDUCIBLE for alias CTAD according to
30035 [over.match.class.deduct].
30037 This check is specified in terms of partial specialization, so the behavior
30038 should be parallel to that of get_partial_spec_bindings. */
30040 bool
30041 type_targs_deducible_from (tree tmpl, tree type)
30043 tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
30044 int len = TREE_VEC_LENGTH (tparms);
30045 tree targs = make_tree_vec (len);
30046 bool tried_array_deduction = (cxx_dialect < cxx17);
30048 /* If tmpl is a class template, this is trivial: it's deducible if TYPE is a
30049 specialization of TMPL. */
30050 if (DECL_CLASS_TEMPLATE_P (tmpl))
30051 return (CLASS_TYPE_P (type)
30052 && CLASSTYPE_TEMPLATE_INFO (type)
30053 && CLASSTYPE_TI_TEMPLATE (type) == tmpl);
30055 /* Otherwise it's an alias template. */
30056 again:
30057 if (unify (tparms, targs, TREE_TYPE (tmpl), type,
30058 UNIFY_ALLOW_NONE, false))
30059 return false;
30061 /* We don't fail on an undeduced targ the second time through (like
30062 get_partial_spec_bindings) because we're going to try defaults. */
30063 for (int i = 0; i < len; ++i)
30064 if (! TREE_VEC_ELT (targs, i))
30066 tree tparm = TREE_VEC_ELT (tparms, i);
30067 tparm = TREE_VALUE (tparm);
30069 if (!tried_array_deduction
30070 && TREE_CODE (tparm) == TYPE_DECL)
30072 try_array_deduction (tparms, targs, TREE_TYPE (tmpl));
30073 tried_array_deduction = true;
30074 if (TREE_VEC_ELT (targs, i))
30075 goto again;
30077 /* If the type parameter is a parameter pack, then it will be deduced
30078 to an empty parameter pack. This is another case that doesn't model
30079 well as partial specialization. */
30080 if (template_parameter_pack_p (tparm))
30082 tree arg;
30083 if (TREE_CODE (tparm) == PARM_DECL)
30085 arg = make_node (NONTYPE_ARGUMENT_PACK);
30086 TREE_CONSTANT (arg) = 1;
30088 else
30089 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
30090 ARGUMENT_PACK_ARGS (arg) = make_tree_vec (0);
30091 TREE_VEC_ELT (targs, i) = arg;
30095 /* Maybe add in default template args. This seems like a flaw in the
30096 specification in terms of partial specialization, since it says the
30097 partial specialization has the the template parameter list of A, but a
30098 partial specialization can't have default targs. */
30099 targs = coerce_template_parms (tparms, targs, tmpl, tf_none);
30100 if (targs == error_mark_node)
30101 return false;
30103 /* I believe we don't need the template_template_parm_bindings_ok_p call
30104 because coerce_template_parms did coerce_template_template_parms. */
30106 return constraints_satisfied_p (tmpl, targs);
30109 /* Return artificial deduction guides built from the constructors of class
30110 template TMPL. */
30112 static tree
30113 ctor_deduction_guides_for (tree tmpl, tsubst_flags_t complain)
30115 tree outer_args = outer_template_args (tmpl);
30116 tree type = TREE_TYPE (most_general_template (tmpl));
30118 tree cands = NULL_TREE;
30120 for (ovl_iterator iter (CLASSTYPE_CONSTRUCTORS (type)); iter; ++iter)
30122 /* Skip inherited constructors. */
30123 if (iter.using_p ())
30124 continue;
30126 tree guide = build_deduction_guide (type, *iter, outer_args, complain);
30127 cands = lookup_add (guide, cands);
30130 /* Add implicit default constructor deduction guide. */
30131 if (!TYPE_HAS_USER_CONSTRUCTOR (type))
30133 tree guide = build_deduction_guide (type, type, outer_args,
30134 complain);
30135 cands = lookup_add (guide, cands);
30138 /* Add copy guide. */
30140 tree gtype = build_reference_type (type);
30141 tree guide = build_deduction_guide (type, gtype, outer_args,
30142 complain);
30143 cands = lookup_add (guide, cands);
30146 return cands;
30149 static GTY((deletable)) hash_map<tree, tree_pair_p> *dguide_cache;
30151 /* Return the non-aggregate deduction guides for deducible template TMPL. The
30152 aggregate candidate is added separately because it depends on the
30153 initializer. Set ANY_DGUIDES_P if we find a non-implicit deduction
30154 guide. */
30156 static tree
30157 deduction_guides_for (tree tmpl, bool &any_dguides_p, tsubst_flags_t complain)
30159 tree guides = NULL_TREE;
30160 if (DECL_ALIAS_TEMPLATE_P (tmpl))
30162 tree under = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30163 tree tinfo = get_template_info (under);
30164 guides = deduction_guides_for (TI_TEMPLATE (tinfo), any_dguides_p,
30165 complain);
30167 else
30169 guides = lookup_qualified_name (CP_DECL_CONTEXT (tmpl),
30170 dguide_name (tmpl),
30171 LOOK_want::NORMAL, /*complain*/false);
30172 if (guides == error_mark_node)
30173 guides = NULL_TREE;
30174 else
30175 any_dguides_p = true;
30178 /* Cache the deduction guides for a template. We also remember the result of
30179 lookup, and rebuild everything if it changes; should be very rare. */
30180 tree_pair_p cache = NULL;
30181 if (tree_pair_p &r
30182 = hash_map_safe_get_or_insert<hm_ggc> (dguide_cache, tmpl))
30184 cache = r;
30185 if (cache->purpose == guides)
30186 return cache->value;
30188 else
30190 r = cache = ggc_cleared_alloc<tree_pair_s> ();
30191 cache->purpose = guides;
30194 tree cands = NULL_TREE;
30195 if (DECL_ALIAS_TEMPLATE_P (tmpl))
30196 cands = alias_ctad_tweaks (tmpl, guides);
30197 else
30199 cands = ctor_deduction_guides_for (tmpl, complain);
30200 for (ovl_iterator it (guides); it; ++it)
30201 cands = lookup_add (*it, cands);
30204 cache->value = cands;
30205 return cands;
30208 /* Return whether TMPL is a (class template argument-) deducible template. */
30210 bool
30211 ctad_template_p (tree tmpl)
30213 /* A deducible template is either a class template or is an alias template
30214 whose defining-type-id is of the form
30216 typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
30218 where the nested-name-specifier (if any) is non-dependent and the
30219 template-name of the simple-template-id names a deducible template. */
30221 if (DECL_CLASS_TEMPLATE_P (tmpl)
30222 || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
30223 return true;
30224 if (!DECL_ALIAS_TEMPLATE_P (tmpl))
30225 return false;
30226 tree orig = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30227 if (tree tinfo = get_template_info (orig))
30228 return ctad_template_p (TI_TEMPLATE (tinfo));
30229 return false;
30232 /* Deduce template arguments for the class template placeholder PTYPE for
30233 template TMPL based on the initializer INIT, and return the resulting
30234 type. */
30236 static tree
30237 do_class_deduction (tree ptype, tree tmpl, tree init,
30238 int flags, tsubst_flags_t complain)
30240 /* We should have handled this in the caller. */
30241 if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
30242 return ptype;
30244 /* If the class was erroneous, don't try to deduce, because that
30245 can generate a lot of diagnostic. */
30246 if (TREE_TYPE (tmpl)
30247 && TYPE_LANG_SPECIFIC (TREE_TYPE (tmpl))
30248 && CLASSTYPE_ERRONEOUS (TREE_TYPE (tmpl)))
30249 return ptype;
30251 /* Wait until the enclosing scope is non-dependent. */
30252 if (DECL_CLASS_SCOPE_P (tmpl)
30253 && dependent_type_p (DECL_CONTEXT (tmpl)))
30254 return ptype;
30256 /* Initializing one placeholder from another. */
30257 if (init
30258 && (TREE_CODE (init) == TEMPLATE_PARM_INDEX
30259 || (TREE_CODE (init) == EXPR_PACK_EXPANSION
30260 && (TREE_CODE (PACK_EXPANSION_PATTERN (init))
30261 == TEMPLATE_PARM_INDEX)))
30262 && is_auto (TREE_TYPE (init))
30263 && CLASS_PLACEHOLDER_TEMPLATE (TREE_TYPE (init)) == tmpl)
30264 return cp_build_qualified_type (TREE_TYPE (init), cp_type_quals (ptype));
30266 if (!ctad_template_p (tmpl))
30268 if (complain & tf_error)
30269 error ("non-deducible template %qT used without template arguments", tmpl);
30270 return error_mark_node;
30272 else if (cxx_dialect < cxx20 && DECL_ALIAS_TEMPLATE_P (tmpl))
30274 if (complain & tf_error)
30276 /* Be permissive with equivalent alias templates. */
30277 tree u = get_underlying_template (tmpl);
30278 diagnostic_t dk = (u == tmpl) ? DK_ERROR : DK_PEDWARN;
30279 bool complained
30280 = emit_diagnostic (dk, input_location, 0,
30281 "alias template deduction only available "
30282 "with %<-std=c++20%> or %<-std=gnu++20%>");
30283 if (u == tmpl)
30284 return error_mark_node;
30285 else if (complained)
30287 inform (input_location, "use %qD directly instead", u);
30288 tmpl = u;
30291 else
30292 return error_mark_node;
30295 /* Wait until the initializer is non-dependent. */
30296 if (type_dependent_expression_p (init))
30297 return ptype;
30299 /* Don't bother with the alias rules for an equivalent template. */
30300 tmpl = get_underlying_template (tmpl);
30302 tree type = TREE_TYPE (tmpl);
30304 bool try_list_cand = false;
30305 bool list_init_p = false;
30307 releasing_vec rv_args = NULL;
30308 vec<tree,va_gc> *&args = *&rv_args;
30309 if (init == NULL_TREE)
30310 args = make_tree_vector ();
30311 else if (BRACE_ENCLOSED_INITIALIZER_P (init))
30313 list_init_p = true;
30314 try_list_cand = true;
30315 if (CONSTRUCTOR_NELTS (init) == 1
30316 && !CONSTRUCTOR_IS_DESIGNATED_INIT (init))
30318 /* As an exception, the first phase in 16.3.1.7 (considering the
30319 initializer list as a single argument) is omitted if the
30320 initializer list consists of a single expression of type cv U,
30321 where U is a specialization of C or a class derived from a
30322 specialization of C. */
30323 tree elt = CONSTRUCTOR_ELT (init, 0)->value;
30324 if (is_spec_or_derived (TREE_TYPE (elt), tmpl))
30325 try_list_cand = false;
30327 if (try_list_cand || is_std_init_list (type))
30328 args = make_tree_vector_single (init);
30329 else
30330 args = make_tree_vector_from_ctor (init);
30332 else if (TREE_CODE (init) == TREE_LIST)
30333 args = make_tree_vector_from_list (init);
30334 else
30335 args = make_tree_vector_single (init);
30337 /* Do this now to avoid problems with erroneous args later on. */
30338 args = resolve_args (args, complain);
30339 if (args == NULL)
30340 return error_mark_node;
30342 bool any_dguides_p = false;
30343 tree cands = deduction_guides_for (tmpl, any_dguides_p, complain);
30344 if (cands == error_mark_node)
30345 return error_mark_node;
30347 /* Prune explicit deduction guides in copy-initialization context (but
30348 not copy-list-initialization). */
30349 bool elided = false;
30350 if (!list_init_p && (flags & LOOKUP_ONLYCONVERTING))
30352 for (lkp_iterator iter (cands); !elided && iter; ++iter)
30353 if (DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
30354 elided = true;
30356 if (elided)
30358 /* Found a nonconverting guide, prune the candidates. */
30359 tree pruned = NULL_TREE;
30360 for (lkp_iterator iter (cands); iter; ++iter)
30361 if (!DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
30362 pruned = lookup_add (*iter, pruned);
30364 cands = pruned;
30368 if (!any_dguides_p)
30369 if (tree guide = maybe_aggr_guide (tmpl, init, args))
30370 cands = lookup_add (guide, cands);
30372 tree fndecl = error_mark_node;
30374 /* If this is list-initialization and the class has a list guide, first
30375 try deducing from the list as a single argument, as [over.match.list]. */
30376 if (try_list_cand)
30378 tree list_cands = NULL_TREE;
30379 for (tree dg : lkp_range (cands))
30380 if (is_list_ctor (dg))
30381 list_cands = lookup_add (dg, list_cands);
30382 if (list_cands)
30383 fndecl = perform_dguide_overload_resolution (list_cands, args, tf_none);
30384 if (fndecl == error_mark_node)
30386 /* That didn't work, now try treating the list as a sequence of
30387 arguments. */
30388 release_tree_vector (args);
30389 args = make_tree_vector_from_ctor (init);
30390 args = resolve_args (args, complain);
30391 if (args == NULL)
30392 return error_mark_node;
30396 if (elided && !cands)
30398 error ("cannot deduce template arguments for copy-initialization"
30399 " of %qT, as it has no non-explicit deduction guides or "
30400 "user-declared constructors", type);
30401 return error_mark_node;
30403 else if (!cands && fndecl == error_mark_node)
30405 error ("cannot deduce template arguments of %qT, as it has no viable "
30406 "deduction guides", type);
30407 return error_mark_node;
30410 if (fndecl == error_mark_node)
30411 fndecl = perform_dguide_overload_resolution (cands, args, tf_none);
30413 if (fndecl == error_mark_node)
30415 if (complain & tf_warning_or_error)
30417 error ("class template argument deduction failed:");
30418 perform_dguide_overload_resolution (cands, args, complain);
30419 if (elided)
30420 inform (input_location, "explicit deduction guides not considered "
30421 "for copy-initialization");
30423 return error_mark_node;
30425 /* [over.match.list]/1: In copy-list-initialization, if an explicit
30426 constructor is chosen, the initialization is ill-formed. */
30427 else if (flags & LOOKUP_ONLYCONVERTING)
30429 if (DECL_NONCONVERTING_P (fndecl))
30431 if (complain & tf_warning_or_error)
30433 // TODO: Pass down location from cp_finish_decl.
30434 error ("class template argument deduction for %qT failed: "
30435 "explicit deduction guide selected in "
30436 "copy-list-initialization", type);
30437 inform (DECL_SOURCE_LOCATION (fndecl),
30438 "explicit deduction guide declared here");
30441 return error_mark_node;
30445 /* If CTAD succeeded but the type doesn't have any explicit deduction
30446 guides, this deduction might not be what the user intended. */
30447 if (fndecl != error_mark_node && !any_dguides_p && (complain & tf_warning))
30449 if ((!DECL_IN_SYSTEM_HEADER (fndecl)
30450 || global_dc->m_warn_system_headers)
30451 && warning (OPT_Wctad_maybe_unsupported,
30452 "%qT may not intend to support class template argument "
30453 "deduction", type))
30454 inform (input_location, "add a deduction guide to suppress this "
30455 "warning");
30458 return cp_build_qualified_type (TREE_TYPE (TREE_TYPE (fndecl)),
30459 cp_type_quals (ptype));
30462 /* Return true if INIT is an unparenthesized id-expression or an
30463 unparenthesized class member access. Used for the argument of
30464 decltype(auto). */
30466 bool
30467 unparenthesized_id_or_class_member_access_p (tree init)
30469 STRIP_ANY_LOCATION_WRAPPER (init);
30471 /* We need to be able to tell '(r)' and 'r' apart (when it's of
30472 reference type). Only the latter is an id-expression. */
30473 if (REFERENCE_REF_P (init)
30474 && !REF_PARENTHESIZED_P (init))
30475 init = TREE_OPERAND (init, 0);
30476 return (DECL_P (init)
30477 || ((TREE_CODE (init) == COMPONENT_REF
30478 || TREE_CODE (init) == SCOPE_REF)
30479 && !REF_PARENTHESIZED_P (init)));
30482 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
30483 from INIT. AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.
30484 The CONTEXT determines the context in which auto deduction is performed
30485 and is used to control error diagnostics. FLAGS are the LOOKUP_* flags.
30487 OUTER_TARGS is used during template argument deduction (context == adc_unify)
30488 to properly substitute the result. It's also used in the adc_unify and
30489 adc_requirement contexts to communicate the necessary template arguments
30490 to satisfaction. OUTER_TARGS is ignored in other contexts.
30492 Additionally for adc_unify contexts TMPL is the template for which TYPE
30493 is a template parameter type.
30495 For partial-concept-ids, extra args from OUTER_TARGS, TMPL and the current
30496 scope may be appended to the list of deduced template arguments prior to
30497 determining constraint satisfaction as appropriate. */
30499 tree
30500 do_auto_deduction (tree type, tree init, tree auto_node,
30501 tsubst_flags_t complain /* = tf_warning_or_error */,
30502 auto_deduction_context context /* = adc_unspecified */,
30503 tree outer_targs /* = NULL_TREE */,
30504 int flags /* = LOOKUP_NORMAL */,
30505 tree tmpl /* = NULL_TREE */)
30507 if (type == error_mark_node || init == error_mark_node)
30508 return error_mark_node;
30510 if (init && type_dependent_expression_p (init)
30511 && context != adc_unify)
30512 /* Defining a subset of type-dependent expressions that we can deduce
30513 from ahead of time isn't worth the trouble. */
30514 return type;
30516 /* Similarly, we can't deduce from another undeduced decl. */
30517 if (init && undeduced_auto_decl (init))
30518 return type;
30520 /* We may be doing a partial substitution, but we still want to replace
30521 auto_node. */
30522 complain &= ~tf_partial;
30524 if (init && BRACE_ENCLOSED_INITIALIZER_P (init))
30526 /* We don't recurse here because we can't deduce from a nested
30527 initializer_list. */
30528 if (CONSTRUCTOR_ELTS (init))
30529 for (constructor_elt &elt : CONSTRUCTOR_ELTS (init))
30530 elt.value = resolve_nondeduced_context (elt.value, complain);
30532 else if (init)
30533 init = resolve_nondeduced_context (init, complain);
30535 /* In C++23, we must deduce the type to int&& for code like
30536 decltype(auto) f(int&& x) { return (x); }
30538 auto&& f(int x) { return x; }
30539 so we use treat_lvalue_as_rvalue_p. But don't do it for
30540 decltype(auto) f(int x) { return x; }
30541 where we should deduce 'int' rather than 'int&&'; transmogrifying
30542 INIT to an rvalue would break that. */
30543 tree r;
30544 if (cxx_dialect >= cxx23
30545 && context == adc_return_type
30546 && (!AUTO_IS_DECLTYPE (auto_node)
30547 || !unparenthesized_id_or_class_member_access_p (init))
30548 && (r = treat_lvalue_as_rvalue_p (maybe_undo_parenthesized_ref (init),
30549 /*return*/true)))
30550 init = r;
30552 if (tree ctmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node))
30553 /* C++17 class template argument deduction. */
30554 return do_class_deduction (type, ctmpl, init, flags, complain);
30556 if (init == NULL_TREE || TREE_TYPE (init) == NULL_TREE)
30557 /* Nothing we can do with this, even in deduction context. */
30558 return type;
30560 location_t loc = cp_expr_loc_or_input_loc (init);
30562 /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
30563 with either a new invented type template parameter U or, if the
30564 initializer is a braced-init-list (8.5.4), with
30565 std::initializer_list<U>. */
30566 if (BRACE_ENCLOSED_INITIALIZER_P (init))
30568 if (!DIRECT_LIST_INIT_P (init))
30569 type = listify_autos (type, auto_node);
30570 else if (CONSTRUCTOR_NELTS (init) == 1)
30571 init = CONSTRUCTOR_ELT (init, 0)->value;
30572 else
30574 if (complain & tf_warning_or_error)
30576 if (permerror (loc, "direct-list-initialization of "
30577 "%<auto%> requires exactly one element"))
30578 inform (loc,
30579 "for deduction to %<std::initializer_list%>, use copy-"
30580 "list-initialization (i.e. add %<=%> before the %<{%>)");
30582 type = listify_autos (type, auto_node);
30586 if (type == error_mark_node || init == error_mark_node)
30587 return error_mark_node;
30589 tree targs;
30590 if (context == adc_decomp_type
30591 && auto_node == type
30592 && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
30594 /* [dcl.struct.bind]/1 - if decomposition declaration has no ref-qualifiers
30595 and initializer has array type, deduce cv-qualified array type. */
30596 targs = make_tree_vec (1);
30597 TREE_VEC_ELT (targs, 0) = TREE_TYPE (init);
30599 else if (AUTO_IS_DECLTYPE (auto_node))
30601 const bool id = unparenthesized_id_or_class_member_access_p (init);
30602 tree deduced = finish_decltype_type (init, id, complain);
30603 deduced = canonicalize_type_argument (deduced, complain);
30604 if (deduced == error_mark_node)
30605 return error_mark_node;
30606 targs = make_tree_vec (1);
30607 TREE_VEC_ELT (targs, 0) = deduced;
30609 else
30611 if (error_operand_p (init))
30612 return error_mark_node;
30614 tree parms = build_tree_list (NULL_TREE, type);
30615 tree tparms;
30617 if (flag_concepts_ts)
30618 tparms = extract_autos (type);
30619 else
30621 tparms = make_tree_vec (1);
30622 TREE_VEC_ELT (tparms, 0)
30623 = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
30626 targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
30627 int val = type_unification_real (tparms, targs, parms, &init, 1, 0,
30628 DEDUCE_CALL,
30629 NULL, /*explain_p=*/false);
30630 if (val > 0)
30632 if (processing_template_decl)
30633 /* Try again at instantiation time. */
30634 return type;
30635 if (type && type != error_mark_node
30636 && (complain & tf_error))
30637 /* If type is error_mark_node a diagnostic must have been
30638 emitted by now. Also, having a mention to '<type error>'
30639 in the diagnostic is not really useful to the user. */
30641 if (cfun
30642 && FNDECL_USED_AUTO (current_function_decl)
30643 && (auto_node
30644 == DECL_SAVED_AUTO_RETURN_TYPE (current_function_decl))
30645 && LAMBDA_FUNCTION_P (current_function_decl))
30646 error_at (loc, "unable to deduce lambda return type from %qE",
30647 init);
30648 else
30649 error_at (loc, "unable to deduce %qT from %qE", type, init);
30650 type_unification_real (tparms, targs, parms, &init, 1, 0,
30651 DEDUCE_CALL,
30652 NULL, /*explain_p=*/true);
30654 return error_mark_node;
30658 /* Check any placeholder constraints against the deduced type. */
30659 if (processing_template_decl && context == adc_unify)
30660 /* Constraints will be checked after deduction. */;
30661 else if (tree constr = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (auto_node)))
30663 if (processing_template_decl)
30665 gcc_checking_assert (context == adc_variable_type
30666 || context == adc_return_type
30667 || context == adc_decomp_type);
30668 gcc_checking_assert (!type_dependent_expression_p (init));
30669 /* If the constraint is dependent, we need to wait until
30670 instantiation time to resolve the placeholder. */
30671 if (placeholder_type_constraint_dependent_p (constr))
30672 return type;
30675 if (context == adc_return_type
30676 || context == adc_variable_type
30677 || context == adc_decomp_type)
30678 if (tree fn = current_function_decl)
30679 if (DECL_TEMPLATE_INFO (fn) || LAMBDA_FUNCTION_P (fn))
30681 outer_targs = DECL_TEMPLATE_INFO (fn)
30682 ? DECL_TI_ARGS (fn) : NULL_TREE;
30683 if (LAMBDA_FUNCTION_P (fn))
30685 /* As in satisfy_declaration_constraints. */
30686 tree regen_args = lambda_regenerating_args (fn);
30687 if (outer_targs)
30688 outer_targs = add_to_template_args (regen_args, outer_targs);
30689 else
30690 outer_targs = regen_args;
30694 tree full_targs = outer_targs;
30695 if (context == adc_unify && tmpl)
30696 full_targs = add_outermost_template_args (tmpl, full_targs);
30697 full_targs = add_to_template_args (full_targs, targs);
30699 /* HACK: Compensate for callers not always communicating all levels of
30700 outer template arguments by filling in the outermost missing levels
30701 with dummy levels before checking satisfaction. We'll still crash
30702 if the constraint depends on a template argument belonging to one of
30703 these missing levels, but this hack otherwise allows us to handle a
30704 large subset of possible constraints (including all non-dependent
30705 constraints). */
30706 if (int missing_levels = (TEMPLATE_TYPE_ORIG_LEVEL (auto_node)
30707 - TMPL_ARGS_DEPTH (full_targs)))
30709 tree dummy_levels = make_tree_vec (missing_levels);
30710 for (int i = 0; i < missing_levels; ++i)
30711 TREE_VEC_ELT (dummy_levels, i) = make_tree_vec (0);
30712 full_targs = add_to_template_args (dummy_levels, full_targs);
30715 if (!constraints_satisfied_p (auto_node, full_targs))
30717 if (complain & tf_warning_or_error)
30719 auto_diagnostic_group d;
30720 switch (context)
30722 case adc_unspecified:
30723 case adc_unify:
30724 error_at (loc, "placeholder constraints not satisfied");
30725 break;
30726 case adc_variable_type:
30727 case adc_decomp_type:
30728 error_at (loc, "deduced initializer does not satisfy "
30729 "placeholder constraints");
30730 break;
30731 case adc_return_type:
30732 error_at (loc, "deduced return type does not satisfy "
30733 "placeholder constraints");
30734 break;
30735 case adc_requirement:
30736 error_at (loc, "deduced expression type does not satisfy "
30737 "placeholder constraints");
30738 break;
30740 diagnose_constraints (loc, auto_node, full_targs);
30742 return error_mark_node;
30746 if (TEMPLATE_TYPE_LEVEL (auto_node) == 1)
30747 /* The outer template arguments are already substituted into type
30748 (but we still may have used them for constraint checking above). */;
30749 else if (context == adc_unify)
30750 targs = add_to_template_args (outer_targs, targs);
30751 else if (processing_template_decl)
30752 targs = add_to_template_args (current_template_args (), targs);
30753 return tsubst (type, targs, complain, NULL_TREE);
30756 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
30757 result. */
30759 tree
30760 splice_late_return_type (tree type, tree late_return_type)
30762 if (late_return_type)
30764 gcc_assert (is_auto (type) || seen_error ());
30765 return late_return_type;
30768 if (tree auto_node = find_type_usage (type, is_auto))
30769 if (TEMPLATE_TYPE_LEVEL (auto_node) <= current_template_depth)
30771 /* In an abbreviated function template we didn't know we were dealing
30772 with a function template when we saw the auto return type, so rebuild
30773 the return type using an auto with the correct level. */
30774 tree new_auto = make_auto_1 (TYPE_IDENTIFIER (auto_node), false);
30775 tree auto_vec = make_tree_vec (1);
30776 TREE_VEC_ELT (auto_vec, 0) = new_auto;
30777 tree targs = add_outermost_template_args (current_template_args (),
30778 auto_vec);
30779 /* Also rebuild the constraint info in terms of the new auto. */
30780 if (tree ci = PLACEHOLDER_TYPE_CONSTRAINTS_INFO (auto_node))
30781 PLACEHOLDER_TYPE_CONSTRAINTS_INFO (new_auto)
30782 = build_tree_list (current_template_parms,
30783 tsubst_constraint (TREE_VALUE (ci), targs,
30784 tf_none, NULL_TREE));
30785 TYPE_CANONICAL (new_auto) = canonical_type_parameter (new_auto);
30786 return tsubst (type, targs, tf_none, NULL_TREE);
30788 return type;
30791 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto' or
30792 'decltype(auto)' or a deduced class template. */
30794 bool
30795 is_auto (const_tree type)
30797 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
30798 && (TYPE_IDENTIFIER (type) == auto_identifier
30799 || TYPE_IDENTIFIER (type) == decltype_auto_identifier))
30800 return true;
30801 else
30802 return false;
30805 /* for_each_template_parm callback for type_uses_auto. */
30808 is_auto_r (tree tp, void */*data*/)
30810 return is_auto (tp);
30813 /* Returns the TEMPLATE_TYPE_PARM in TYPE representing `auto' iff TYPE contains
30814 a use of `auto'. Returns NULL_TREE otherwise. */
30816 tree
30817 type_uses_auto (tree type)
30819 if (type == NULL_TREE)
30820 return NULL_TREE;
30822 /* For parameter packs, check the contents of the pack. */
30823 if (PACK_EXPANSION_P (type))
30824 type = PACK_EXPANSION_PATTERN (type);
30826 if (flag_concepts_ts)
30828 /* The Concepts TS allows multiple autos in one type-specifier; just
30829 return the first one we find, do_auto_deduction will collect all of
30830 them. */
30831 if (uses_template_parms (type))
30832 return for_each_template_parm (type, is_auto_r, /*data*/NULL,
30833 /*visited*/NULL, /*nondeduced*/false);
30834 else
30835 return NULL_TREE;
30837 else
30838 return find_type_usage (type, is_auto);
30841 /* Report ill-formed occurrences of auto types in ARGUMENTS. If
30842 concepts are enabled, auto is acceptable in template arguments, but
30843 only when TEMPL identifies a template class. Return TRUE if any
30844 such errors were reported. */
30846 bool
30847 check_auto_in_tmpl_args (tree tmpl, tree args)
30849 if (!flag_concepts_ts)
30850 /* Only the concepts TS allows 'auto' as a type-id; it'd otherwise
30851 have already been rejected by the parser more generally. */
30852 return false;
30854 /* If there were previous errors, nevermind. */
30855 if (!args || TREE_CODE (args) != TREE_VEC)
30856 return false;
30858 /* If TMPL is an identifier, we're parsing and we can't tell yet
30859 whether TMPL is supposed to be a type, a function or a variable.
30860 We'll only be able to tell during template substitution, so we
30861 expect to be called again then. If concepts are enabled and we
30862 know we have a type, we're ok. */
30863 if (identifier_p (tmpl)
30864 || (DECL_P (tmpl)
30865 && (DECL_TYPE_TEMPLATE_P (tmpl)
30866 || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))))
30867 return false;
30869 /* Quickly search for any occurrences of auto; usually there won't
30870 be any, and then we'll avoid allocating the vector. */
30871 if (!type_uses_auto (args))
30872 return false;
30874 bool errors = false;
30876 tree vec = extract_autos (args);
30877 for (int i = 0; i < TREE_VEC_LENGTH (vec); i++)
30879 tree xauto = TREE_VALUE (TREE_VEC_ELT (vec, i));
30880 error_at (DECL_SOURCE_LOCATION (xauto),
30881 "invalid use of %qT in template argument", xauto);
30882 errors = true;
30885 return errors;
30888 /* Recursively walk over && expressions searching for EXPR. Return a reference
30889 to that expression. */
30891 static tree *find_template_requirement (tree *t, tree key)
30893 if (*t == key)
30894 return t;
30895 if (TREE_CODE (*t) == TRUTH_ANDIF_EXPR)
30897 if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 0), key))
30898 return p;
30899 if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 1), key))
30900 return p;
30902 return 0;
30905 /* Convert the generic type parameters in PARM that match the types given in the
30906 range [START_IDX, END_IDX) from the current_template_parms into generic type
30907 packs. */
30909 tree
30910 convert_generic_types_to_packs (tree parm, int start_idx, int end_idx)
30912 tree current = current_template_parms;
30913 int depth = TMPL_PARMS_DEPTH (current);
30914 current = INNERMOST_TEMPLATE_PARMS (current);
30915 tree replacement = make_tree_vec (TREE_VEC_LENGTH (current));
30917 for (int i = 0; i < start_idx; ++i)
30918 TREE_VEC_ELT (replacement, i)
30919 = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
30921 for (int i = start_idx; i < end_idx; ++i)
30923 /* Create a distinct parameter pack type from the current parm and add it
30924 to the replacement args to tsubst below into the generic function
30925 parameter. */
30926 tree node = TREE_VEC_ELT (current, i);
30927 tree o = TREE_TYPE (TREE_VALUE (node));
30928 tree t = copy_type (o);
30929 TEMPLATE_TYPE_PARM_INDEX (t)
30930 = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (o),
30931 t, 0, 0, tf_none);
30932 TREE_TYPE (TEMPLATE_TYPE_DECL (t)) = t;
30933 TYPE_STUB_DECL (t) = TYPE_NAME (t) = TEMPLATE_TYPE_DECL (t);
30934 TYPE_MAIN_VARIANT (t) = t;
30935 TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
30936 TYPE_CANONICAL (t) = canonical_type_parameter (t);
30937 TREE_VEC_ELT (replacement, i) = t;
30939 /* Replace the current template parameter with new pack. */
30940 TREE_VALUE (node) = TREE_CHAIN (t);
30942 /* Surgically adjust the associated constraint of adjusted parameter
30943 and it's corresponding contribution to the current template
30944 requirements. */
30945 if (tree constr = TEMPLATE_PARM_CONSTRAINTS (node))
30947 tree id = unpack_concept_check (constr);
30948 TREE_VEC_ELT (TREE_OPERAND (id, 1), 0) = t;
30949 location_t loc = DECL_SOURCE_LOCATION (TYPE_NAME (t));
30950 tree fold = finish_left_unary_fold_expr (loc, constr,
30951 TRUTH_ANDIF_EXPR);
30952 TEMPLATE_PARM_CONSTRAINTS (node) = fold;
30954 /* If there was a constraint, we also need to replace that in
30955 the template requirements, which we've already built. */
30956 tree *reqs = &TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
30957 reqs = find_template_requirement (reqs, constr);
30958 *reqs = fold;
30962 for (int i = end_idx, e = TREE_VEC_LENGTH (current); i < e; ++i)
30963 TREE_VEC_ELT (replacement, i)
30964 = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
30966 /* If there are more levels then build up the replacement with the outer
30967 template parms. */
30968 if (depth > 1)
30969 replacement = add_to_template_args (template_parms_to_args
30970 (TREE_CHAIN (current_template_parms)),
30971 replacement);
30973 return tsubst (parm, replacement, tf_none, NULL_TREE);
30976 /* __integer_pack(N) in a pack expansion expands to a sequence of numbers from
30977 0..N-1. */
30979 void
30980 declare_integer_pack (void)
30982 tree ipfn = push_library_fn (get_identifier ("__integer_pack"),
30983 build_function_type_list (integer_type_node,
30984 integer_type_node,
30985 NULL_TREE),
30986 NULL_TREE, ECF_CONST);
30987 DECL_DECLARED_CONSTEXPR_P (ipfn) = true;
30988 set_decl_built_in_function (ipfn, BUILT_IN_FRONTEND,
30989 CP_BUILT_IN_INTEGER_PACK);
30992 /* Walk the decl or type specialization table calling FN on each
30993 entry. */
30995 void
30996 walk_specializations (bool decls_p,
30997 void (*fn) (bool decls_p, spec_entry *entry, void *data),
30998 void *data)
31000 spec_hash_table *table = decls_p ? decl_specializations
31001 : type_specializations;
31002 spec_hash_table::iterator end (table->end ());
31003 for (spec_hash_table::iterator iter (table->begin ()); iter != end; ++iter)
31004 fn (decls_p, *iter, data);
31007 /* Lookup the specialization of *ELT, in the decl or type
31008 specialization table. Return the SPEC that's already there, or
31009 NULL if nothing. */
31011 tree
31012 match_mergeable_specialization (bool decl_p, spec_entry *elt)
31014 hash_table<spec_hasher> *specializations
31015 = decl_p ? decl_specializations : type_specializations;
31016 hashval_t hash = spec_hasher::hash (elt);
31017 auto *slot = specializations->find_slot_with_hash (elt, hash, NO_INSERT);
31019 if (slot)
31020 return (*slot)->spec;
31022 return NULL_TREE;
31025 /* Return flags encoding whether SPEC is on the instantiation and/or
31026 specialization lists of TMPL. */
31028 unsigned
31029 get_mergeable_specialization_flags (tree tmpl, tree decl)
31031 unsigned flags = 0;
31033 for (tree inst = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
31034 inst; inst = TREE_CHAIN (inst))
31035 if (TREE_VALUE (inst) == decl)
31037 flags |= 1;
31038 break;
31041 if (CLASS_TYPE_P (TREE_TYPE (decl))
31042 && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl))
31043 && CLASSTYPE_USE_TEMPLATE (TREE_TYPE (decl)) == 2)
31044 /* Only need to search if DECL is a partial specialization. */
31045 for (tree part = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
31046 part; part = TREE_CHAIN (part))
31047 if (TREE_VALUE (part) == decl)
31049 flags |= 2;
31050 break;
31053 return flags;
31056 /* Add a new specialization described by SPEC. DECL is the
31057 maybe-template decl and FLAGS is as returned from
31058 get_mergeable_specialization_flags. */
31060 void
31061 add_mergeable_specialization (bool decl_p, bool alias_p, spec_entry *elt,
31062 tree decl, unsigned flags)
31064 hashval_t hash = spec_hasher::hash (elt);
31065 if (decl_p)
31067 auto *slot = decl_specializations->find_slot_with_hash (elt, hash, INSERT);
31069 gcc_checking_assert (!*slot);
31070 auto entry = ggc_alloc<spec_entry> ();
31071 *entry = *elt;
31072 *slot = entry;
31074 if (alias_p)
31076 elt->spec = TREE_TYPE (elt->spec);
31077 gcc_checking_assert (elt->spec);
31081 if (!decl_p || alias_p)
31083 auto *slot = type_specializations->find_slot_with_hash (elt, hash, INSERT);
31085 /* We don't distinguish different constrained partial type
31086 specializations, so there could be duplicates. Everything else
31087 must be new. */
31088 if (!(flags & 2 && *slot))
31090 gcc_checking_assert (!*slot);
31092 auto entry = ggc_alloc<spec_entry> ();
31093 *entry = *elt;
31094 *slot = entry;
31098 if (flags & 1)
31099 DECL_TEMPLATE_INSTANTIATIONS (elt->tmpl)
31100 = tree_cons (elt->args, decl, DECL_TEMPLATE_INSTANTIATIONS (elt->tmpl));
31102 if (flags & 2)
31104 /* A partial specialization. */
31105 tree cons = tree_cons (elt->args, decl,
31106 DECL_TEMPLATE_SPECIALIZATIONS (elt->tmpl));
31107 TREE_TYPE (cons) = decl_p ? TREE_TYPE (elt->spec) : elt->spec;
31108 DECL_TEMPLATE_SPECIALIZATIONS (elt->tmpl) = cons;
31112 /* Set up the hash tables for template instantiations. */
31114 void
31115 init_template_processing (void)
31117 decl_specializations = hash_table<spec_hasher>::create_ggc (37);
31118 type_specializations = hash_table<spec_hasher>::create_ggc (37);
31120 if (cxx_dialect >= cxx11)
31121 declare_integer_pack ();
31124 /* Print stats about the template hash tables for -fstats. */
31126 void
31127 print_template_statistics (void)
31129 fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
31130 "%f collisions\n", (long) decl_specializations->size (),
31131 (long) decl_specializations->elements (),
31132 decl_specializations->collisions ());
31133 fprintf (stderr, "type_specializations: size %ld, %ld elements, "
31134 "%f collisions\n", (long) type_specializations->size (),
31135 (long) type_specializations->elements (),
31136 type_specializations->collisions ());
31139 #if CHECKING_P
31141 namespace selftest {
31143 /* Verify that type_dependent_expression_p () works correctly, even
31144 in the presence of location wrapper nodes. */
31146 static void
31147 test_type_dependent_expression_p ()
31149 location_t loc = BUILTINS_LOCATION;
31151 tree name = get_identifier ("foo");
31153 /* If no templates are involved, nothing is type-dependent. */
31154 gcc_assert (!processing_template_decl);
31155 ASSERT_FALSE (type_dependent_expression_p (name));
31157 ++processing_template_decl;
31159 /* Within a template, an unresolved name is always type-dependent. */
31160 ASSERT_TRUE (type_dependent_expression_p (name));
31162 /* Ensure it copes with NULL_TREE and errors. */
31163 ASSERT_FALSE (type_dependent_expression_p (NULL_TREE));
31164 ASSERT_FALSE (type_dependent_expression_p (error_mark_node));
31166 /* A USING_DECL in a template should be type-dependent, even if wrapped
31167 with a location wrapper (PR c++/83799). */
31168 tree using_decl = build_lang_decl (USING_DECL, name, NULL_TREE);
31169 TREE_TYPE (using_decl) = integer_type_node;
31170 ASSERT_TRUE (type_dependent_expression_p (using_decl));
31171 tree wrapped_using_decl = maybe_wrap_with_location (using_decl, loc);
31172 ASSERT_TRUE (location_wrapper_p (wrapped_using_decl));
31173 ASSERT_TRUE (type_dependent_expression_p (wrapped_using_decl));
31175 --processing_template_decl;
31178 /* Run all of the selftests within this file. */
31180 void
31181 cp_pt_cc_tests ()
31183 test_type_dependent_expression_p ();
31186 } // namespace selftest
31188 #endif /* #if CHECKING_P */
31190 #include "gt-cp-pt.h"