d: Merge dmd, druntime a6f1083699, phobos 31dedd7da
[official-gcc.git] / gcc / cp / pt.cc
blob903a4a1c363011c046620a99e3c8fc8a84cc129f
1 /* Handle parameterized types (templates) for GNU -*- C++ -*-.
2 Copyright (C) 1992-2024 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"
50 #include "omp-general.h"
52 /* The type of functions taking a tree, and some additional data, and
53 returning an int. */
54 typedef int (*tree_fn_t) (tree, void*);
56 /* The PENDING_TEMPLATES is a list of templates whose instantiations
57 have been deferred, either because their definitions were not yet
58 available, or because we were putting off doing the work. */
59 struct GTY ((chain_next ("%h.next"))) pending_template
61 struct pending_template *next;
62 struct tinst_level *tinst;
65 static GTY(()) struct pending_template *pending_templates;
66 static GTY(()) struct pending_template *last_pending_template;
68 int processing_template_parmlist;
69 static int template_header_count;
71 static vec<int> inline_parm_levels;
73 static GTY(()) struct tinst_level *current_tinst_level;
75 static GTY(()) vec<tree, va_gc> *saved_access_scope;
77 /* Live only within one (recursive) call to tsubst_expr. We use
78 this to pass the statement expression node from the STMT_EXPR
79 to the EXPR_STMT that is its result. */
80 static tree cur_stmt_expr;
82 // -------------------------------------------------------------------------- //
83 // Local Specialization Stack
85 // Implementation of the RAII helper for creating new local
86 // specializations.
87 local_specialization_stack::local_specialization_stack (lss_policy policy)
88 : saved (local_specializations)
90 if (policy == lss_nop)
92 else if (policy == lss_blank || !saved)
93 local_specializations = new hash_map<tree, tree>;
94 else
95 local_specializations = new hash_map<tree, tree>(*saved);
98 local_specialization_stack::~local_specialization_stack ()
100 if (local_specializations != saved)
102 delete local_specializations;
103 local_specializations = saved;
107 /* True if we've recursed into fn_type_unification too many times. */
108 static bool excessive_deduction_depth;
110 struct spec_hasher : ggc_ptr_hash<spec_entry>
112 static hashval_t hash (tree, tree);
113 static hashval_t hash (spec_entry *);
114 static bool equal (spec_entry *, spec_entry *);
117 /* The general template is not in these tables. */
118 typedef hash_table<spec_hasher> spec_hash_table;
119 static GTY (()) spec_hash_table *decl_specializations;
120 static GTY (()) spec_hash_table *type_specializations;
122 /* Contains canonical template parameter types. The vector is indexed by
123 the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
124 TREE_LIST, whose TREE_VALUEs contain the canonical template
125 parameters of various types and levels. */
126 static GTY(()) vec<tree, va_gc> *canonical_template_parms;
128 #define UNIFY_ALLOW_NONE 0
129 #define UNIFY_ALLOW_MORE_CV_QUAL 1
130 #define UNIFY_ALLOW_LESS_CV_QUAL 2
131 #define UNIFY_ALLOW_DERIVED 4
132 #define UNIFY_ALLOW_INTEGER 8
133 #define UNIFY_ALLOW_OUTER_LEVEL 16
134 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
135 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
137 enum template_base_result {
138 tbr_incomplete_type,
139 tbr_ambiguous_baseclass,
140 tbr_success
143 static bool resolve_overloaded_unification (tree, tree, tree, tree,
144 unification_kind_t, int,
145 bool);
146 static int try_one_overload (tree, tree, tree, tree, tree,
147 unification_kind_t, int, bool, bool);
148 static int unify (tree, tree, tree, tree, int, bool);
149 static void add_pending_template (tree);
150 static tree reopen_tinst_level (struct tinst_level *);
151 static tree tsubst_initializer_list (tree, tree);
152 static tree get_partial_spec_bindings (tree, tree, tree);
153 static void tsubst_enum (tree, tree, tree);
154 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
155 static int check_non_deducible_conversion (tree, tree, unification_kind_t, int,
156 struct conversion **, bool, bool);
157 static int maybe_adjust_types_for_deduction (tree, unification_kind_t,
158 tree*, tree*, tree);
159 static int type_unification_real (tree, tree, tree, const tree *,
160 unsigned int, int, unification_kind_t,
161 vec<deferred_access_check, va_gc> **,
162 bool);
163 static void note_template_header (int);
164 static tree convert_nontype_argument_function (tree, tree, tsubst_flags_t);
165 static tree convert_nontype_argument (tree, tree, tsubst_flags_t);
166 static tree convert_template_argument (tree, tree, tree,
167 tsubst_flags_t, int, tree);
168 static tree for_each_template_parm (tree, tree_fn_t, void*,
169 hash_set<tree> *, bool, tree_fn_t = NULL);
170 static tree expand_template_argument_pack (tree);
171 static tree build_template_parm_index (int, int, int, tree, tree);
172 static bool inline_needs_template_parms (tree, bool);
173 static void push_inline_template_parms_recursive (tree, int);
174 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
175 static int mark_template_parm (tree, void *);
176 static int template_parm_this_level_p (tree, void *);
177 static tree tsubst_friend_function (tree, tree);
178 static tree tsubst_friend_class (tree, tree);
179 static int can_complete_type_without_circularity (tree);
180 static tree get_bindings (tree, tree, tree, bool);
181 static int template_decl_level (tree);
182 static int check_cv_quals_for_unify (int, tree, tree);
183 static int unify_pack_expansion (tree, tree, tree,
184 tree, unification_kind_t, bool, bool);
185 static tree copy_template_args (tree);
186 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
187 static void tsubst_each_template_parm_constraints (tree, tree, tsubst_flags_t);
188 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
189 static tree tsubst_aggr_type_1 (tree, tree, tsubst_flags_t, tree, int);
190 static tree tsubst_arg_types (tree, tree, tree, tsubst_flags_t, tree);
191 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
192 static bool check_specialization_scope (void);
193 static tree process_partial_specialization (tree);
194 static enum template_base_result get_template_base (tree, tree, tree, tree,
195 bool , tree *);
196 static tree try_class_unification (tree, tree, tree, tree, bool);
197 static bool class_nttp_const_wrapper_p (tree t);
198 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
199 tree, tree);
200 static bool template_template_parm_bindings_ok_p (tree, tree);
201 static void tsubst_default_arguments (tree, tsubst_flags_t);
202 static tree for_each_template_parm_r (tree *, int *, void *);
203 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
204 static void copy_default_args_to_explicit_spec (tree);
205 static bool invalid_nontype_parm_type_p (tree, tsubst_flags_t);
206 static bool dependent_template_arg_p (tree);
207 static bool dependent_type_p_r (tree);
208 static tree tsubst_stmt (tree, tree, tsubst_flags_t, tree);
209 static tree tsubst_decl (tree, tree, tsubst_flags_t, bool = true);
210 static tree tsubst_scope (tree, tree, tsubst_flags_t, tree);
211 static tree tsubst_name (tree, tree, tsubst_flags_t, tree);
212 static void perform_instantiation_time_access_checks (tree, tree);
213 static tree listify (tree);
214 static tree listify_autos (tree, tree);
215 static tree tsubst_template_parm (tree, tree, tsubst_flags_t);
216 static tree instantiate_alias_template (tree, tree, tsubst_flags_t);
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);
226 static tree alias_ctad_tweaks (tree, tree);
227 static tree inherited_ctad_tweaks (tree, tree, tsubst_flags_t);
228 static tree deduction_guides_for (tree, bool&, tsubst_flags_t);
230 /* Make the current scope suitable for access checking when we are
231 processing T. T can be FUNCTION_DECL for instantiated function
232 template, VAR_DECL for static member variable, or TYPE_DECL for
233 for a class or alias template (needed by instantiate_decl). */
235 void
236 push_access_scope (tree t)
238 gcc_assert (VAR_OR_FUNCTION_DECL_P (t)
239 || TREE_CODE (t) == TYPE_DECL);
241 if (DECL_FRIEND_CONTEXT (t))
242 push_nested_class (DECL_FRIEND_CONTEXT (t));
243 else if (DECL_IMPLICIT_TYPEDEF_P (t)
244 && CLASS_TYPE_P (TREE_TYPE (t)))
245 push_nested_class (TREE_TYPE (t));
246 else if (DECL_CLASS_SCOPE_P (t))
247 push_nested_class (DECL_CONTEXT (t));
248 else if (deduction_guide_p (t) && DECL_ARTIFICIAL (t))
249 /* An artificial deduction guide should have the same access as
250 the constructor. */
251 push_nested_class (TREE_TYPE (TREE_TYPE (t)));
252 else
253 push_to_top_level ();
255 if (TREE_CODE (t) == FUNCTION_DECL)
257 vec_safe_push (saved_access_scope, current_function_decl);
258 current_function_decl = t;
262 /* Restore the scope set up by push_access_scope. T is the node we
263 are processing. */
265 void
266 pop_access_scope (tree t)
268 if (TREE_CODE (t) == FUNCTION_DECL)
269 current_function_decl = saved_access_scope->pop();
271 if (DECL_FRIEND_CONTEXT (t)
272 || (DECL_IMPLICIT_TYPEDEF_P (t)
273 && CLASS_TYPE_P (TREE_TYPE (t)))
274 || DECL_CLASS_SCOPE_P (t)
275 || (deduction_guide_p (t) && DECL_ARTIFICIAL (t)))
276 pop_nested_class ();
277 else
278 pop_from_top_level ();
281 /* Do any processing required when DECL (a member template
282 declaration) is finished. Returns the TEMPLATE_DECL corresponding
283 to DECL, unless it is a specialization, in which case the DECL
284 itself is returned. */
286 tree
287 finish_member_template_decl (tree decl)
289 if (decl == error_mark_node)
290 return error_mark_node;
292 gcc_assert (DECL_P (decl));
294 if (TREE_CODE (decl) == TYPE_DECL)
296 tree type;
298 type = TREE_TYPE (decl);
299 if (type == error_mark_node)
300 return error_mark_node;
301 if (MAYBE_CLASS_TYPE_P (type)
302 && CLASSTYPE_TEMPLATE_INFO (type)
303 && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
305 tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
306 check_member_template (tmpl);
307 return tmpl;
309 return NULL_TREE;
311 else if (TREE_CODE (decl) == FIELD_DECL)
312 error_at (DECL_SOURCE_LOCATION (decl),
313 "data member %qD cannot be a member template", decl);
314 else if (DECL_TEMPLATE_INFO (decl))
316 if (!DECL_TEMPLATE_SPECIALIZATION (decl))
318 check_member_template (DECL_TI_TEMPLATE (decl));
319 return DECL_TI_TEMPLATE (decl);
321 else
322 return NULL_TREE;
324 else
325 error_at (DECL_SOURCE_LOCATION (decl),
326 "invalid member template declaration %qD", decl);
328 return error_mark_node;
331 /* Create a template info node. */
333 tree
334 build_template_info (tree template_decl, tree template_args)
336 tree result = make_node (TEMPLATE_INFO);
337 TI_TEMPLATE (result) = template_decl;
338 TI_ARGS (result) = template_args;
339 return result;
342 /* DECL_TEMPLATE_INFO, if applicable, or NULL_TREE. */
344 static tree
345 decl_template_info (const_tree decl)
347 /* This needs to match template_info_decl_check. */
348 if (DECL_LANG_SPECIFIC (decl))
349 switch (TREE_CODE (decl))
351 case FUNCTION_DECL:
352 if (DECL_THUNK_P (decl))
353 break;
354 gcc_fallthrough ();
355 case VAR_DECL:
356 case FIELD_DECL:
357 case TYPE_DECL:
358 case CONCEPT_DECL:
359 case TEMPLATE_DECL:
360 return DECL_TEMPLATE_INFO (decl);
362 default:
363 break;
365 return NULL_TREE;
368 /* Return the template info node corresponding to T, whatever T is. */
370 tree
371 get_template_info (const_tree t)
373 tree tinfo = NULL_TREE;
375 if (!t || t == error_mark_node)
376 return NULL;
378 if (TREE_CODE (t) == NAMESPACE_DECL
379 || TREE_CODE (t) == PARM_DECL)
380 return NULL;
382 if (DECL_P (t))
383 tinfo = decl_template_info (t);
385 if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
386 t = TREE_TYPE (t);
388 if (OVERLOAD_TYPE_P (t))
389 tinfo = TYPE_TEMPLATE_INFO (t);
390 else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
391 tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
393 return tinfo;
396 /* Returns the template nesting level of the indicated class TYPE.
398 For example, in:
399 template <class T>
400 struct A
402 template <class U>
403 struct B {};
406 A<T>::B<U> has depth two, while A<T> has depth one.
407 Both A<T>::B<int> and A<int>::B<U> have depth one, if
408 they are instantiations, not specializations.
410 This function is guaranteed to return 0 if passed NULL_TREE so
411 that, for example, `template_class_depth (current_class_type)' is
412 always safe. */
415 template_class_depth (tree type)
417 int depth;
419 for (depth = 0; type && TREE_CODE (type) != NAMESPACE_DECL; )
421 tree tinfo = get_template_info (type);
423 if (tinfo
424 && TREE_CODE (TI_TEMPLATE (tinfo)) == TEMPLATE_DECL
425 && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
426 && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
427 ++depth;
429 if (DECL_P (type))
431 if (tree fctx = DECL_FRIEND_CONTEXT (type))
432 type = fctx;
433 else
434 type = CP_DECL_CONTEXT (type);
436 else if (LAMBDA_TYPE_P (type) && LAMBDA_TYPE_EXTRA_SCOPE (type))
437 type = LAMBDA_TYPE_EXTRA_SCOPE (type);
438 else
439 type = CP_TYPE_CONTEXT (type);
442 return depth;
445 /* Return TRUE if NODE instantiates a template that has arguments of
446 its own, be it directly a primary template or indirectly through a
447 partial specializations. */
448 static bool
449 instantiates_primary_template_p (tree node)
451 tree tinfo = get_template_info (node);
452 if (!tinfo)
453 return false;
455 tree tmpl = TI_TEMPLATE (tinfo);
456 if (PRIMARY_TEMPLATE_P (tmpl))
457 return true;
459 if (!DECL_TEMPLATE_SPECIALIZATION (tmpl))
460 return false;
462 /* So now we know we have a specialization, but it could be a full
463 or a partial specialization. To tell which, compare the depth of
464 its template arguments with those of its context. */
466 tree ctxt = DECL_CONTEXT (tmpl);
467 tree ctinfo = get_template_info (ctxt);
468 if (!ctinfo)
469 return true;
471 return (TMPL_ARGS_DEPTH (TI_ARGS (tinfo))
472 > TMPL_ARGS_DEPTH (TI_ARGS (ctinfo)));
475 /* Subroutine of maybe_begin_member_template_processing.
476 Returns true if processing DECL needs us to push template parms. */
478 static bool
479 inline_needs_template_parms (tree decl, bool nsdmi)
481 if (!decl || (!nsdmi && ! DECL_TEMPLATE_INFO (decl)))
482 return false;
484 return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
485 > (current_template_depth + DECL_TEMPLATE_SPECIALIZATION (decl)));
488 /* Subroutine of maybe_begin_member_template_processing.
489 Push the template parms in PARMS, starting from LEVELS steps into the
490 chain, and ending at the beginning, since template parms are listed
491 innermost first. */
493 static void
494 push_inline_template_parms_recursive (tree parmlist, int levels)
496 tree parms = TREE_VALUE (parmlist);
497 int i;
499 if (levels > 1)
500 push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
502 ++processing_template_decl;
503 current_template_parms
504 = tree_cons (size_int (current_template_depth + 1),
505 parms, current_template_parms);
506 TEMPLATE_PARMS_CONSTRAINTS (current_template_parms)
507 = TEMPLATE_PARMS_CONSTRAINTS (parmlist);
508 TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
510 begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
511 NULL);
512 for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
514 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
516 if (error_operand_p (parm))
517 continue;
519 gcc_assert (DECL_P (parm));
521 switch (TREE_CODE (parm))
523 case TYPE_DECL:
524 case TEMPLATE_DECL:
525 pushdecl (parm);
526 break;
528 case PARM_DECL:
529 /* Push the CONST_DECL. */
530 pushdecl (TEMPLATE_PARM_DECL (DECL_INITIAL (parm)));
531 break;
533 default:
534 gcc_unreachable ();
539 /* Restore the template parameter context for a member template, a
540 friend template defined in a class definition, or a non-template
541 member of template class. */
543 void
544 maybe_begin_member_template_processing (tree decl)
546 tree parms;
547 int levels = 0;
548 bool nsdmi = TREE_CODE (decl) == FIELD_DECL;
550 if (nsdmi)
552 tree ctx = DECL_CONTEXT (decl);
553 decl = (CLASSTYPE_TEMPLATE_INFO (ctx)
554 /* Disregard full specializations (c++/60999). */
555 && uses_template_parms (ctx)
556 ? CLASSTYPE_TI_TEMPLATE (ctx) : NULL_TREE);
559 if (inline_needs_template_parms (decl, nsdmi))
561 parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
562 levels = TMPL_PARMS_DEPTH (parms) - current_template_depth;
564 if (DECL_TEMPLATE_SPECIALIZATION (decl))
566 --levels;
567 parms = TREE_CHAIN (parms);
570 push_inline_template_parms_recursive (parms, levels);
573 /* Remember how many levels of template parameters we pushed so that
574 we can pop them later. */
575 inline_parm_levels.safe_push (levels);
578 /* Undo the effects of maybe_begin_member_template_processing. */
580 void
581 maybe_end_member_template_processing (void)
583 int i;
584 int last;
586 if (inline_parm_levels.length () == 0)
587 return;
589 last = inline_parm_levels.pop ();
590 for (i = 0; i < last; ++i)
592 --processing_template_decl;
593 current_template_parms = TREE_CHAIN (current_template_parms);
594 poplevel (0, 0, 0);
598 /* Return a new template argument vector which contains all of ARGS,
599 but has as its innermost set of arguments the EXTRA_ARGS. */
601 tree
602 add_to_template_args (tree args, tree extra_args)
604 tree new_args;
605 int extra_depth;
606 int i;
607 int j;
609 if (args == NULL_TREE || extra_args == error_mark_node)
610 return extra_args;
612 extra_depth = TMPL_ARGS_DEPTH (extra_args);
613 new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
615 for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
616 SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
618 for (j = 1; j <= extra_depth; ++j, ++i)
619 SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
621 return new_args;
624 /* Like add_to_template_args, but only the outermost ARGS are added to
625 the EXTRA_ARGS. In particular, all but TMPL_ARGS_DEPTH
626 (EXTRA_ARGS) levels are added. This function is used to combine
627 the template arguments from a partial instantiation with the
628 template arguments used to attain the full instantiation from the
629 partial instantiation.
631 If ARGS is a TEMPLATE_DECL, use its parameters as args. */
633 tree
634 add_outermost_template_args (tree args, tree extra_args)
636 tree new_args;
638 if (!args)
639 return extra_args;
640 if (TREE_CODE (args) == TEMPLATE_DECL)
642 tree ti = get_template_info (DECL_TEMPLATE_RESULT (args));
643 args = TI_ARGS (ti);
646 /* If there are more levels of EXTRA_ARGS than there are ARGS,
647 something very fishy is going on. */
648 gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
650 /* If *all* the new arguments will be the EXTRA_ARGS, just return
651 them. */
652 if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
653 return extra_args;
655 /* For the moment, we make ARGS look like it contains fewer levels. */
656 TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
658 new_args = add_to_template_args (args, extra_args);
660 /* Now, we restore ARGS to its full dimensions. */
661 TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
663 return new_args;
666 /* Return the N levels of innermost template arguments from the ARGS. */
668 tree
669 get_innermost_template_args (tree args, int n)
671 tree new_args;
672 int extra_levels;
673 int i;
675 gcc_assert (n >= 0);
677 /* If N is 1, just return the innermost set of template arguments. */
678 if (n == 1)
679 return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
681 /* If we're not removing anything, just return the arguments we were
682 given. */
683 extra_levels = TMPL_ARGS_DEPTH (args) - n;
684 gcc_assert (extra_levels >= 0);
685 if (extra_levels == 0)
686 return args;
688 /* Make a new set of arguments, not containing the outer arguments. */
689 new_args = make_tree_vec (n);
690 for (i = 1; i <= n; ++i)
691 SET_TMPL_ARGS_LEVEL (new_args, i,
692 TMPL_ARGS_LEVEL (args, i + extra_levels));
694 return new_args;
697 /* The inverse of get_innermost_template_args: Return all but the innermost
698 EXTRA_LEVELS levels of template arguments from the ARGS. */
700 static tree
701 strip_innermost_template_args (tree args, int extra_levels)
703 tree new_args;
704 int n = TMPL_ARGS_DEPTH (args) - extra_levels;
705 int i;
707 gcc_assert (n >= 0);
709 /* If N is 1, just return the outermost set of template arguments. */
710 if (n == 1)
711 return TMPL_ARGS_LEVEL (args, 1);
713 /* If we're not removing anything, just return the arguments we were
714 given. */
715 gcc_assert (extra_levels >= 0);
716 if (extra_levels == 0)
717 return args;
719 /* Make a new set of arguments, not containing the inner arguments. */
720 new_args = make_tree_vec (n);
721 for (i = 1; i <= n; ++i)
722 SET_TMPL_ARGS_LEVEL (new_args, i,
723 TMPL_ARGS_LEVEL (args, i));
725 return new_args;
728 /* We've got a template header coming up; push to a new level for storing
729 the parms. */
731 void
732 begin_template_parm_list (void)
734 /* We use a non-tag-transparent scope here, which causes pushtag to
735 put tags in this scope, rather than in the enclosing class or
736 namespace scope. This is the right thing, since we want
737 TEMPLATE_DECLS, and not TYPE_DECLS for template classes. For a
738 global template class, push_template_decl handles putting the
739 TEMPLATE_DECL into top-level scope. For a nested template class,
740 e.g.:
742 template <class T> struct S1 {
743 template <class T> struct S2 {};
746 pushtag contains special code to insert the TEMPLATE_DECL for S2
747 at the right scope. */
748 begin_scope (sk_template_parms, NULL);
749 ++processing_template_decl;
750 ++processing_template_parmlist;
751 note_template_header (0);
753 /* Add a dummy parameter level while we process the parameter list. */
754 current_template_parms
755 = tree_cons (size_int (current_template_depth + 1),
756 make_tree_vec (0),
757 current_template_parms);
760 /* This routine is called when a specialization is declared. If it is
761 invalid to declare a specialization here, an error is reported and
762 false is returned, otherwise this routine will return true. */
764 static bool
765 check_specialization_scope (void)
767 tree scope = current_scope ();
769 /* [temp.expl.spec]
771 An explicit specialization shall be declared in the namespace of
772 which the template is a member, or, for member templates, in the
773 namespace of which the enclosing class or enclosing class
774 template is a member. An explicit specialization of a member
775 function, member class or static data member of a class template
776 shall be declared in the namespace of which the class template
777 is a member. */
778 if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
780 error ("explicit specialization in non-namespace scope %qD", scope);
781 return false;
784 /* [temp.expl.spec]
786 In an explicit specialization declaration for a member of a class
787 template or a member template that appears in namespace scope,
788 the member template and some of its enclosing class templates may
789 remain unspecialized, except that the declaration shall not
790 explicitly specialize a class member template if its enclosing
791 class templates are not explicitly specialized as well. */
792 if (current_template_parms)
794 error ("enclosing class templates are not explicitly specialized");
795 return false;
798 return true;
801 /* We've just seen template <>. */
803 bool
804 begin_specialization (void)
806 begin_scope (sk_template_spec, NULL);
807 note_template_header (1);
808 return check_specialization_scope ();
811 /* Called at then end of processing a declaration preceded by
812 template<>. */
814 void
815 end_specialization (void)
817 finish_scope ();
818 reset_specialization ();
821 /* Any template <>'s that we have seen thus far are not referring to a
822 function specialization. */
824 void
825 reset_specialization (void)
827 processing_specialization = 0;
828 template_header_count = 0;
831 /* We've just seen a template header. If SPECIALIZATION is nonzero,
832 it was of the form template <>. */
834 static void
835 note_template_header (int specialization)
837 processing_specialization = specialization;
838 template_header_count++;
841 /* We're beginning an explicit instantiation. */
843 void
844 begin_explicit_instantiation (void)
846 gcc_assert (!processing_explicit_instantiation);
847 processing_explicit_instantiation = true;
851 void
852 end_explicit_instantiation (void)
854 gcc_assert (processing_explicit_instantiation);
855 processing_explicit_instantiation = false;
858 /* An explicit specialization or partial specialization of TMPL is being
859 declared. Check that the namespace in which the specialization is
860 occurring is permissible. Returns false iff it is invalid to
861 specialize TMPL in the current namespace. */
863 static bool
864 check_specialization_namespace (tree tmpl)
866 tree tpl_ns = decl_namespace_context (tmpl);
868 /* [tmpl.expl.spec]
870 An explicit specialization shall be declared in a namespace enclosing the
871 specialized template. An explicit specialization whose declarator-id is
872 not qualified shall be declared in the nearest enclosing namespace of the
873 template, or, if the namespace is inline (7.3.1), any namespace from its
874 enclosing namespace set. */
875 if (current_scope() != DECL_CONTEXT (tmpl)
876 && !at_namespace_scope_p ())
878 error ("specialization of %qD must appear at namespace scope", tmpl);
879 return false;
882 if (is_nested_namespace (current_namespace, tpl_ns, cxx_dialect < cxx11))
883 /* Same or enclosing namespace. */
884 return true;
885 else
887 auto_diagnostic_group d;
888 if (permerror (input_location,
889 "specialization of %qD in different namespace", tmpl))
890 inform (DECL_SOURCE_LOCATION (tmpl),
891 " from definition of %q#D", tmpl);
892 return false;
896 /* SPEC is an explicit instantiation. Check that it is valid to
897 perform this explicit instantiation in the current namespace. */
899 static void
900 check_explicit_instantiation_namespace (tree spec)
902 tree ns;
904 /* DR 275: An explicit instantiation shall appear in an enclosing
905 namespace of its template. */
906 ns = decl_namespace_context (spec);
907 if (!is_nested_namespace (current_namespace, ns))
908 permerror (input_location, "explicit instantiation of %qD in namespace %qD "
909 "(which does not enclose namespace %qD)",
910 spec, current_namespace, ns);
913 /* Returns true if TYPE is a new partial specialization that needs to be
914 set up. This may also modify TYPE to point to the correct (new or
915 existing) constrained partial specialization. */
917 static bool
918 maybe_new_partial_specialization (tree& type)
920 /* An implicit instantiation of an incomplete type implies
921 the definition of a new class template.
923 template<typename T>
924 struct S;
926 template<typename T>
927 struct S<T*>;
929 Here, S<T*> is an implicit instantiation of S whose type
930 is incomplete. */
931 if (CLASSTYPE_IMPLICIT_INSTANTIATION (type) && !COMPLETE_TYPE_P (type))
932 return true;
934 /* It can also be the case that TYPE is a completed specialization.
935 Continuing the previous example, suppose we also declare:
937 template<typename T>
938 requires Integral<T>
939 struct S<T*>;
941 Here, S<T*> refers to the specialization S<T*> defined
942 above. However, we need to differentiate definitions because
943 we intend to define a new partial specialization. In this case,
944 we rely on the fact that the constraints are different for
945 this declaration than that above.
947 Note that we also get here for injected class names and
948 late-parsed template definitions. We must ensure that we
949 do not create new type declarations for those cases. */
950 if (flag_concepts && CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
952 tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
953 tree args = CLASSTYPE_TI_ARGS (type);
955 /* If there are no template parameters, this cannot be a new
956 partial template specialization? */
957 if (!current_template_parms)
958 return false;
960 /* The injected-class-name is not a new partial specialization. */
961 if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
962 return false;
964 /* If the constraints are not the same as those of the primary
965 then, we can probably create a new specialization. */
966 tree type_constr = current_template_constraints ();
968 if (type == TREE_TYPE (tmpl))
970 tree main_constr = get_constraints (tmpl);
971 if (equivalent_constraints (type_constr, main_constr))
972 return false;
975 /* Also, if there's a pre-existing specialization with matching
976 constraints, then this also isn't new. */
977 tree specs = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
978 while (specs)
980 tree spec_tmpl = TREE_VALUE (specs);
981 tree spec_args = TREE_PURPOSE (specs);
982 tree spec_constr = get_constraints (spec_tmpl);
983 if (comp_template_args (args, spec_args)
984 && equivalent_constraints (type_constr, spec_constr))
986 type = TREE_TYPE (spec_tmpl);
987 return false;
989 specs = TREE_CHAIN (specs);
992 /* Create a new type node (and corresponding type decl)
993 for the newly declared specialization. */
994 tree t = make_class_type (TREE_CODE (type));
995 CLASSTYPE_DECLARED_CLASS (t) = CLASSTYPE_DECLARED_CLASS (type);
996 SET_TYPE_TEMPLATE_INFO (t, build_template_info (tmpl, args));
998 /* We only need a separate type node for storing the definition of this
999 partial specialization; uses of S<T*> are unconstrained, so all are
1000 equivalent. So keep TYPE_CANONICAL the same. */
1001 TYPE_CANONICAL (t) = TYPE_CANONICAL (type);
1003 /* Build the corresponding type decl. */
1004 tree d = create_implicit_typedef (DECL_NAME (tmpl), t);
1005 DECL_CONTEXT (d) = TYPE_CONTEXT (t);
1006 DECL_SOURCE_LOCATION (d) = input_location;
1007 TREE_PUBLIC (d) = TREE_PUBLIC (DECL_TEMPLATE_RESULT (tmpl));
1009 set_instantiating_module (d);
1010 DECL_MODULE_EXPORT_P (d) = DECL_MODULE_EXPORT_P (tmpl);
1012 type = t;
1013 return true;
1016 return false;
1019 /* The TYPE is being declared. If it is a template type, that means it
1020 is a partial specialization. Do appropriate error-checking. */
1022 tree
1023 maybe_process_partial_specialization (tree type)
1025 tree context;
1027 if (type == error_mark_node)
1028 return error_mark_node;
1030 /* A lambda that appears in specialization context is not itself a
1031 specialization. */
1032 if (CLASS_TYPE_P (type) && CLASSTYPE_LAMBDA_EXPR (type))
1033 return type;
1035 /* An injected-class-name is not a specialization. */
1036 if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
1037 return type;
1039 if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
1041 error ("name of class shadows template template parameter %qD",
1042 TYPE_NAME (type));
1043 return error_mark_node;
1046 context = TYPE_CONTEXT (type);
1048 if (TYPE_ALIAS_P (type))
1050 tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (type);
1052 if (tinfo && DECL_ALIAS_TEMPLATE_P (TI_TEMPLATE (tinfo)))
1053 error ("specialization of alias template %qD",
1054 TI_TEMPLATE (tinfo));
1055 else
1056 error ("explicit specialization of non-template %qT", type);
1057 return error_mark_node;
1059 else if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
1061 /* This is for ordinary explicit specialization and partial
1062 specialization of a template class such as:
1064 template <> class C<int>;
1068 template <class T> class C<T*>;
1070 Make sure that `C<int>' and `C<T*>' are implicit instantiations. */
1072 if (maybe_new_partial_specialization (type))
1074 if (!check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type))
1075 && !at_namespace_scope_p ())
1076 return error_mark_node;
1077 SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
1078 DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
1079 if (processing_template_decl)
1081 tree decl = push_template_decl (TYPE_MAIN_DECL (type));
1082 if (decl == error_mark_node)
1083 return error_mark_node;
1084 return TREE_TYPE (decl);
1087 else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
1088 error ("specialization of %qT after instantiation", type);
1089 else if (errorcount && !processing_specialization
1090 && CLASSTYPE_TEMPLATE_SPECIALIZATION (type)
1091 && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
1092 /* Trying to define a specialization either without a template<> header
1093 or in an inappropriate place. We've already given an error, so just
1094 bail now so we don't actually define the specialization. */
1095 return error_mark_node;
1097 else if (CLASS_TYPE_P (type)
1098 && !CLASSTYPE_USE_TEMPLATE (type)
1099 && CLASSTYPE_TEMPLATE_INFO (type)
1100 && context && CLASS_TYPE_P (context)
1101 && CLASSTYPE_TEMPLATE_INFO (context))
1103 /* This is for an explicit specialization of member class
1104 template according to [temp.expl.spec/18]:
1106 template <> template <class U> class C<int>::D;
1108 The context `C<int>' must be an implicit instantiation.
1109 Otherwise this is just a member class template declared
1110 earlier like:
1112 template <> class C<int> { template <class U> class D; };
1113 template <> template <class U> class C<int>::D;
1115 In the first case, `C<int>::D' is a specialization of `C<T>::D'
1116 while in the second case, `C<int>::D' is a primary template
1117 and `C<T>::D' may not exist. */
1119 if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
1120 && !COMPLETE_TYPE_P (type))
1122 tree t;
1123 tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
1125 if (current_namespace
1126 != decl_namespace_context (tmpl))
1128 if (permerror (input_location,
1129 "specialization of %qD in different namespace",
1130 type))
1131 inform (DECL_SOURCE_LOCATION (tmpl),
1132 "from definition of %q#D", tmpl);
1135 /* Check for invalid specialization after instantiation:
1137 template <> template <> class C<int>::D<int>;
1138 template <> template <class U> class C<int>::D; */
1140 for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
1141 t; t = TREE_CHAIN (t))
1143 tree inst = TREE_VALUE (t);
1144 if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst)
1145 || !COMPLETE_OR_OPEN_TYPE_P (inst))
1147 /* We already have a full specialization of this partial
1148 instantiation, or a full specialization has been
1149 looked up but not instantiated. Reassign it to the
1150 new member specialization template. */
1151 spec_entry elt;
1152 spec_entry *entry;
1154 elt.tmpl = most_general_template (tmpl);
1155 elt.args = CLASSTYPE_TI_ARGS (inst);
1156 elt.spec = inst;
1158 type_specializations->remove_elt (&elt);
1160 elt.tmpl = tmpl;
1161 CLASSTYPE_TI_ARGS (inst)
1162 = elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
1164 spec_entry **slot
1165 = type_specializations->find_slot (&elt, INSERT);
1166 entry = ggc_alloc<spec_entry> ();
1167 *entry = elt;
1168 *slot = entry;
1170 else
1171 /* But if we've had an implicit instantiation, that's a
1172 problem ([temp.expl.spec]/6). */
1173 error ("specialization %qT after instantiation %qT",
1174 type, inst);
1177 /* Mark TYPE as a specialization. And as a result, we only
1178 have one level of template argument for the innermost
1179 class template. */
1180 SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
1181 DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
1182 CLASSTYPE_TI_ARGS (type)
1183 = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
1186 else if (processing_specialization)
1188 /* Someday C++0x may allow for enum template specialization. */
1189 if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
1190 && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
1191 pedwarn (input_location, OPT_Wpedantic, "template specialization "
1192 "of %qD not allowed by ISO C++", type);
1193 else
1195 error ("explicit specialization of non-template %qT", type);
1196 return error_mark_node;
1200 return type;
1203 /* Make sure ARGS doesn't use any inappropriate typedefs; we should have
1204 gone through coerce_template_parms by now. */
1206 static void
1207 verify_unstripped_args_1 (tree inner)
1209 for (int i = 0; i < TREE_VEC_LENGTH (inner); ++i)
1211 tree arg = TREE_VEC_ELT (inner, i);
1212 if (TREE_CODE (arg) == TEMPLATE_DECL)
1213 /* OK */;
1214 else if (TYPE_P (arg))
1215 gcc_assert (strip_typedefs (arg, NULL) == arg);
1216 else if (ARGUMENT_PACK_P (arg))
1217 verify_unstripped_args_1 (ARGUMENT_PACK_ARGS (arg));
1218 else if (strip_typedefs (TREE_TYPE (arg), NULL) != TREE_TYPE (arg))
1219 /* Allow typedefs on the type of a non-type argument, since a
1220 parameter can have them. */;
1221 else
1222 gcc_assert (strip_typedefs_expr (arg, NULL) == arg);
1226 static void
1227 verify_unstripped_args (tree args)
1229 ++processing_template_decl;
1230 if (!any_dependent_template_arguments_p (args))
1231 verify_unstripped_args_1 (INNERMOST_TEMPLATE_ARGS (args));
1232 --processing_template_decl;
1235 /* Retrieve the specialization (in the sense of [temp.spec] - a
1236 specialization is either an instantiation or an explicit
1237 specialization) of TMPL for the given template ARGS. If there is
1238 no such specialization, return NULL_TREE. The ARGS are a vector of
1239 arguments, or a vector of vectors of arguments, in the case of
1240 templates with more than one level of parameters.
1242 If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
1243 then we search for a partial specialization matching ARGS. This
1244 parameter is ignored if TMPL is not a class template.
1246 We can also look up a FIELD_DECL, if it is a lambda capture pack; the
1247 result is a NONTYPE_ARGUMENT_PACK. */
1249 static tree
1250 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
1252 if (tmpl == NULL_TREE)
1253 return NULL_TREE;
1255 if (args == error_mark_node)
1256 return NULL_TREE;
1258 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL
1259 || TREE_CODE (tmpl) == FIELD_DECL);
1261 /* There should be as many levels of arguments as there are
1262 levels of parameters. */
1263 gcc_assert (TMPL_ARGS_DEPTH (args)
1264 == (TREE_CODE (tmpl) == TEMPLATE_DECL
1265 ? TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl))
1266 : template_class_depth (DECL_CONTEXT (tmpl))));
1268 if (flag_checking)
1269 verify_unstripped_args (args);
1271 /* Lambda functions in templates aren't instantiated normally, but through
1272 tsubst_lambda_expr. */
1273 if (lambda_fn_in_template_p (tmpl))
1274 return NULL_TREE;
1276 spec_entry elt;
1277 elt.tmpl = tmpl;
1278 elt.args = args;
1279 elt.spec = NULL_TREE;
1281 spec_hash_table *specializations;
1282 if (DECL_CLASS_TEMPLATE_P (tmpl))
1283 specializations = type_specializations;
1284 else
1285 specializations = decl_specializations;
1287 if (hash == 0)
1288 hash = spec_hasher::hash (&elt);
1289 if (spec_entry *found = specializations->find_with_hash (&elt, hash))
1290 return found->spec;
1292 return NULL_TREE;
1295 /* Like retrieve_specialization, but for local declarations. */
1297 tree
1298 retrieve_local_specialization (tree tmpl)
1300 if (local_specializations == NULL)
1301 return NULL_TREE;
1303 tree *slot = local_specializations->get (tmpl);
1304 return slot ? *slot : NULL_TREE;
1307 /* Returns nonzero iff DECL is a specialization of TMPL. */
1310 is_specialization_of (tree decl, tree tmpl)
1312 tree t;
1314 if (TREE_CODE (decl) == FUNCTION_DECL)
1316 for (t = decl;
1317 t != NULL_TREE;
1318 t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1319 if (t == tmpl)
1320 return 1;
1322 else
1324 gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1326 for (t = TREE_TYPE (decl);
1327 t != NULL_TREE;
1328 t = CLASSTYPE_USE_TEMPLATE (t)
1329 ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1330 if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1331 return 1;
1334 return 0;
1337 /* Returns nonzero iff DECL is a specialization of friend declaration
1338 FRIEND_DECL according to [temp.friend]. */
1340 bool
1341 is_specialization_of_friend (tree decl, tree friend_decl)
1343 bool need_template = true;
1344 int template_depth;
1346 gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1347 || TREE_CODE (decl) == TYPE_DECL);
1349 /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1350 of a template class, we want to check if DECL is a specialization
1351 if this. */
1352 if (TREE_CODE (friend_decl) == FUNCTION_DECL
1353 && DECL_CLASS_SCOPE_P (friend_decl)
1354 && DECL_TEMPLATE_INFO (friend_decl)
1355 && !DECL_USE_TEMPLATE (friend_decl))
1357 /* We want a TEMPLATE_DECL for `is_specialization_of'. */
1358 friend_decl = DECL_TI_TEMPLATE (friend_decl);
1359 need_template = false;
1361 else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1362 && !PRIMARY_TEMPLATE_P (friend_decl))
1363 need_template = false;
1365 /* There is nothing to do if this is not a template friend. */
1366 if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1367 return false;
1369 if (is_specialization_of (decl, friend_decl))
1370 return true;
1372 /* [temp.friend/6]
1373 A member of a class template may be declared to be a friend of a
1374 non-template class. In this case, the corresponding member of
1375 every specialization of the class template is a friend of the
1376 class granting friendship.
1378 For example, given a template friend declaration
1380 template <class T> friend void A<T>::f();
1382 the member function below is considered a friend
1384 template <> struct A<int> {
1385 void f();
1388 For this type of template friend, TEMPLATE_DEPTH below will be
1389 nonzero. To determine if DECL is a friend of FRIEND, we first
1390 check if the enclosing class is a specialization of another. */
1392 template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1393 if (template_depth
1394 && DECL_CLASS_SCOPE_P (decl)
1395 && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1396 CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1398 /* Next, we check the members themselves. In order to handle
1399 a few tricky cases, such as when FRIEND_DECL's are
1401 template <class T> friend void A<T>::g(T t);
1402 template <class T> template <T t> friend void A<T>::h();
1404 and DECL's are
1406 void A<int>::g(int);
1407 template <int> void A<int>::h();
1409 we need to figure out ARGS, the template arguments from
1410 the context of DECL. This is required for template substitution
1411 of `T' in the function parameter of `g' and template parameter
1412 of `h' in the above examples. Here ARGS corresponds to `int'. */
1414 tree context = DECL_CONTEXT (decl);
1415 tree args = NULL_TREE;
1416 int current_depth = 0;
1418 while (current_depth < template_depth)
1420 if (CLASSTYPE_TEMPLATE_INFO (context))
1422 if (current_depth == 0)
1423 args = TYPE_TI_ARGS (context);
1424 else
1425 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1426 current_depth++;
1428 context = TYPE_CONTEXT (context);
1431 if (TREE_CODE (decl) == FUNCTION_DECL)
1433 bool is_template;
1434 tree friend_type;
1435 tree decl_type;
1436 tree friend_args_type;
1437 tree decl_args_type;
1439 /* Make sure that both DECL and FRIEND_DECL are templates or
1440 non-templates. */
1441 is_template = DECL_TEMPLATE_INFO (decl)
1442 && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1443 if (need_template ^ is_template)
1444 return false;
1445 else if (is_template)
1447 /* If both are templates, check template parameter list. */
1448 tree friend_parms
1449 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1450 args, tf_none);
1451 if (!comp_template_parms
1452 (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1453 friend_parms))
1454 return false;
1456 decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1458 else
1459 decl_type = TREE_TYPE (decl);
1461 friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1462 tf_none, NULL_TREE);
1463 if (friend_type == error_mark_node)
1464 return false;
1466 /* Check if return types match. */
1467 if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1468 return false;
1470 /* Check if function parameter types match, ignoring the
1471 `this' parameter. */
1472 friend_args_type = TYPE_ARG_TYPES (friend_type);
1473 decl_args_type = TYPE_ARG_TYPES (decl_type);
1474 if (DECL_IOBJ_MEMBER_FUNCTION_P (friend_decl))
1475 friend_args_type = TREE_CHAIN (friend_args_type);
1476 if (DECL_IOBJ_MEMBER_FUNCTION_P (decl))
1477 decl_args_type = TREE_CHAIN (decl_args_type);
1479 return compparms (decl_args_type, friend_args_type);
1481 else
1483 /* DECL is a TYPE_DECL */
1484 bool is_template;
1485 tree decl_type = TREE_TYPE (decl);
1487 /* Make sure that both DECL and FRIEND_DECL are templates or
1488 non-templates. */
1489 is_template
1490 = CLASSTYPE_TEMPLATE_INFO (decl_type)
1491 && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1493 if (need_template ^ is_template)
1494 return false;
1495 else if (is_template)
1497 tree friend_parms;
1498 /* If both are templates, check the name of the two
1499 TEMPLATE_DECL's first because is_friend didn't. */
1500 if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1501 != DECL_NAME (friend_decl))
1502 return false;
1504 /* Now check template parameter list. */
1505 friend_parms
1506 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1507 args, tf_none);
1508 return comp_template_parms
1509 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1510 friend_parms);
1512 else
1513 return (DECL_NAME (decl)
1514 == DECL_NAME (friend_decl));
1517 return false;
1520 /* Register the specialization SPEC as a specialization of TMPL with
1521 the indicated ARGS. IS_FRIEND indicates whether the specialization
1522 is actually just a friend declaration. ATTRLIST is the list of
1523 attributes that the specialization is declared with or NULL when
1524 it isn't. Returns SPEC, or an equivalent prior declaration, if
1525 available.
1527 We also store instantiations of field packs in the hash table, even
1528 though they are not themselves templates, to make lookup easier. */
1530 static tree
1531 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1532 hashval_t hash)
1534 tree fn;
1536 gcc_assert ((TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec))
1537 || (TREE_CODE (tmpl) == FIELD_DECL
1538 && TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK));
1540 spec_entry elt;
1541 elt.tmpl = tmpl;
1542 elt.args = args;
1543 elt.spec = spec;
1545 if (hash == 0)
1546 hash = spec_hasher::hash (&elt);
1548 spec_entry **slot = decl_specializations->find_slot_with_hash (&elt, hash, INSERT);
1549 if (*slot)
1550 fn = (*slot)->spec;
1551 else
1552 fn = NULL_TREE;
1554 /* We can sometimes try to re-register a specialization that we've
1555 already got. In particular, regenerate_decl_from_template calls
1556 duplicate_decls which will update the specialization list. But,
1557 we'll still get called again here anyhow. It's more convenient
1558 to simply allow this than to try to prevent it. */
1559 if (fn == spec)
1560 return spec;
1561 else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1563 if (DECL_TEMPLATE_INSTANTIATION (fn))
1565 if (DECL_ODR_USED (fn)
1566 || DECL_EXPLICIT_INSTANTIATION (fn))
1568 error ("specialization of %qD after instantiation",
1569 fn);
1570 return error_mark_node;
1572 else
1574 tree clone;
1575 /* This situation should occur only if the first
1576 specialization is an implicit instantiation, the
1577 second is an explicit specialization, and the
1578 implicit instantiation has not yet been used. That
1579 situation can occur if we have implicitly
1580 instantiated a member function and then specialized
1581 it later.
1583 We can also wind up here if a friend declaration that
1584 looked like an instantiation turns out to be a
1585 specialization:
1587 template <class T> void foo(T);
1588 class S { friend void foo<>(int) };
1589 template <> void foo(int);
1591 We transform the existing DECL in place so that any
1592 pointers to it become pointers to the updated
1593 declaration.
1595 If there was a definition for the template, but not
1596 for the specialization, we want this to look as if
1597 there were no definition, and vice versa. */
1598 DECL_INITIAL (fn) = NULL_TREE;
1599 duplicate_decls (spec, fn, /*hiding=*/is_friend);
1601 /* The call to duplicate_decls will have applied
1602 [temp.expl.spec]:
1604 An explicit specialization of a function template
1605 is inline only if it is explicitly declared to be,
1606 and independently of whether its function template
1609 to the primary function; now copy the inline bits to
1610 the various clones. */
1611 FOR_EACH_CLONE (clone, fn)
1613 DECL_DECLARED_INLINE_P (clone)
1614 = DECL_DECLARED_INLINE_P (fn);
1615 DECL_SOURCE_LOCATION (clone)
1616 = DECL_SOURCE_LOCATION (fn);
1617 DECL_DELETED_FN (clone)
1618 = DECL_DELETED_FN (fn);
1620 check_specialization_namespace (tmpl);
1622 return fn;
1625 else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1627 tree dd = duplicate_decls (spec, fn, /*hiding=*/is_friend);
1628 if (dd == error_mark_node)
1629 /* We've already complained in duplicate_decls. */
1630 return error_mark_node;
1632 if (dd == NULL_TREE && DECL_INITIAL (spec))
1633 /* Dup decl failed, but this is a new definition. Set the
1634 line number so any errors match this new
1635 definition. */
1636 DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1638 return fn;
1641 else if (fn)
1642 return duplicate_decls (spec, fn, /*hiding=*/is_friend);
1644 /* A specialization must be declared in the same namespace as the
1645 template it is specializing. */
1646 if (DECL_P (spec) && DECL_TEMPLATE_SPECIALIZATION (spec)
1647 && !check_specialization_namespace (tmpl))
1648 DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1650 spec_entry *entry = ggc_alloc<spec_entry> ();
1651 gcc_assert (tmpl && args && spec);
1652 *entry = elt;
1653 *slot = entry;
1654 if ((TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1655 && PRIMARY_TEMPLATE_P (tmpl)
1656 && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1657 || variable_template_p (tmpl))
1658 /* If TMPL is a forward declaration of a template function, keep a list
1659 of all specializations in case we need to reassign them to a friend
1660 template later in tsubst_friend_function.
1662 Also keep a list of all variable template instantiations so that
1663 process_partial_specialization can check whether a later partial
1664 specialization would have used it. */
1665 DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1666 = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1668 return spec;
1671 /* Restricts tree and type comparisons. */
1672 int comparing_specializations;
1673 int comparing_dependent_aliases;
1675 /* Whether we are comparing template arguments during partial ordering
1676 (and therefore want the comparison to look through dependent alias
1677 template specializations). */
1679 static int comparing_for_partial_ordering;
1681 /* Returns true iff two spec_entry nodes are equivalent. */
1683 bool
1684 spec_hasher::equal (spec_entry *e1, spec_entry *e2)
1686 int equal;
1688 ++comparing_specializations;
1689 ++comparing_dependent_aliases;
1690 ++processing_template_decl;
1691 equal = (e1->tmpl == e2->tmpl
1692 && comp_template_args (e1->args, e2->args));
1693 if (equal && flag_concepts
1694 /* tmpl could be a FIELD_DECL for a capture pack. */
1695 && TREE_CODE (e1->tmpl) == TEMPLATE_DECL
1696 && VAR_P (DECL_TEMPLATE_RESULT (e1->tmpl))
1697 && uses_template_parms (e1->args))
1699 /* Partial specializations of a variable template can be distinguished by
1700 constraints. */
1701 tree c1 = e1->spec ? get_constraints (e1->spec) : NULL_TREE;
1702 tree c2 = e2->spec ? get_constraints (e2->spec) : NULL_TREE;
1703 equal = equivalent_constraints (c1, c2);
1705 --processing_template_decl;
1706 --comparing_dependent_aliases;
1707 --comparing_specializations;
1709 return equal;
1712 /* Returns a hash for a template TMPL and template arguments ARGS. */
1714 static hashval_t
1715 hash_tmpl_and_args (tree tmpl, tree args)
1717 hashval_t val = iterative_hash_object (DECL_UID (tmpl), 0);
1718 return iterative_hash_template_arg (args, val);
1721 hashval_t
1722 spec_hasher::hash (tree tmpl, tree args)
1724 ++comparing_specializations;
1725 hashval_t val = hash_tmpl_and_args (tmpl, args);
1726 --comparing_specializations;
1727 return val;
1730 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1731 ignoring SPEC. */
1733 hashval_t
1734 spec_hasher::hash (spec_entry *e)
1736 return spec_hasher::hash (e->tmpl, e->args);
1739 /* Recursively calculate a hash value for a template argument ARG, for use
1740 in the hash tables of template specializations. We must be
1741 careful to (at least) skip the same entities template_args_equal
1742 does. */
1744 hashval_t
1745 iterative_hash_template_arg (tree arg, hashval_t val)
1747 if (arg == NULL_TREE)
1748 return iterative_hash_object (arg, val);
1750 if (!TYPE_P (arg))
1751 /* Strip nop-like things, but not the same as STRIP_NOPS. */
1752 while (CONVERT_EXPR_P (arg)
1753 || TREE_CODE (arg) == NON_LVALUE_EXPR
1754 || class_nttp_const_wrapper_p (arg))
1755 arg = TREE_OPERAND (arg, 0);
1757 enum tree_code code = TREE_CODE (arg);
1759 val = iterative_hash_object (code, val);
1761 switch (code)
1763 case ARGUMENT_PACK_SELECT:
1764 /* Getting here with an ARGUMENT_PACK_SELECT means we're probably
1765 preserving it in a hash table, which is bad because it will change
1766 meaning when gen_elem_of_pack_expansion_instantiation changes the
1767 ARGUMENT_PACK_SELECT_INDEX. */
1768 gcc_unreachable ();
1770 case ERROR_MARK:
1771 return val;
1773 case IDENTIFIER_NODE:
1774 return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1776 case TREE_VEC:
1777 for (tree elt : tree_vec_range (arg))
1778 val = iterative_hash_template_arg (elt, val);
1779 return val;
1781 case TYPE_PACK_EXPANSION:
1782 case EXPR_PACK_EXPANSION:
1783 val = iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1784 return iterative_hash_template_arg (PACK_EXPANSION_EXTRA_ARGS (arg), val);
1786 case TYPE_ARGUMENT_PACK:
1787 case NONTYPE_ARGUMENT_PACK:
1788 return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1790 case TREE_LIST:
1791 for (; arg; arg = TREE_CHAIN (arg))
1792 val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1793 return val;
1795 case OVERLOAD:
1796 for (lkp_iterator iter (arg); iter; ++iter)
1797 val = iterative_hash_template_arg (*iter, val);
1798 return val;
1800 case CONSTRUCTOR:
1802 iterative_hash_template_arg (TREE_TYPE (arg), val);
1803 for (auto &e: CONSTRUCTOR_ELTS (arg))
1805 val = iterative_hash_template_arg (e.index, val);
1806 val = iterative_hash_template_arg (e.value, val);
1808 return val;
1811 case PARM_DECL:
1812 if (!DECL_ARTIFICIAL (arg))
1814 val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1815 val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
1817 return iterative_hash_template_arg (TREE_TYPE (arg), val);
1819 case TEMPLATE_DECL:
1820 if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg))
1821 return iterative_hash_template_arg (TREE_TYPE (arg), val);
1822 break;
1824 case TARGET_EXPR:
1825 return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1827 case PTRMEM_CST:
1828 val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1829 return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1831 case TEMPLATE_PARM_INDEX:
1832 val = iterative_hash_template_arg
1833 (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1834 val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1835 return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1837 case TRAIT_EXPR:
1838 val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1839 val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1840 return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1842 case BASELINK:
1843 val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1844 val);
1845 return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1846 val);
1848 case MODOP_EXPR:
1849 val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1850 code = TREE_CODE (TREE_OPERAND (arg, 1));
1851 val = iterative_hash_object (code, val);
1852 return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1854 case LAMBDA_EXPR:
1855 /* [temp.over.link] Two lambda-expressions are never considered
1856 equivalent.
1858 So just hash the closure type. */
1859 return iterative_hash_template_arg (TREE_TYPE (arg), val);
1861 case CAST_EXPR:
1862 case IMPLICIT_CONV_EXPR:
1863 case STATIC_CAST_EXPR:
1864 case REINTERPRET_CAST_EXPR:
1865 case CONST_CAST_EXPR:
1866 case DYNAMIC_CAST_EXPR:
1867 case NEW_EXPR:
1868 val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1869 /* Now hash operands as usual. */
1870 break;
1872 case CALL_EXPR:
1874 tree fn = CALL_EXPR_FN (arg);
1875 if (tree name = call_expr_dependent_name (arg))
1877 if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
1878 val = iterative_hash_template_arg (TREE_OPERAND (fn, 1), val);
1879 fn = name;
1881 val = iterative_hash_template_arg (fn, val);
1882 call_expr_arg_iterator ai;
1883 for (tree x = first_call_expr_arg (arg, &ai); x;
1884 x = next_call_expr_arg (&ai))
1885 val = iterative_hash_template_arg (x, val);
1886 return val;
1889 default:
1890 break;
1893 char tclass = TREE_CODE_CLASS (code);
1894 switch (tclass)
1896 case tcc_type:
1897 if (tree ats = alias_template_specialization_p (arg, nt_transparent))
1899 // We want an alias specialization that survived strip_typedefs
1900 // to hash differently from its TYPE_CANONICAL, to avoid hash
1901 // collisions that compare as different in template_args_equal.
1902 // These could be dependent specializations that strip_typedefs
1903 // left alone, or untouched specializations because
1904 // coerce_template_parms returns the unconverted template
1905 // arguments if it sees incomplete argument packs.
1906 tree ti = TYPE_ALIAS_TEMPLATE_INFO (ats);
1907 return hash_tmpl_and_args (TI_TEMPLATE (ti), TI_ARGS (ti));
1910 switch (code)
1912 case DECLTYPE_TYPE:
1913 val = iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1914 break;
1916 case TYPENAME_TYPE:
1917 if (comparing_specializations)
1919 /* Hash the components that are relevant to TYPENAME_TYPE
1920 equivalence as determined by structural_comptypes. We
1921 can only coherently do this when comparing_specializations
1922 is set, because otherwise structural_comptypes tries
1923 resolving TYPENAME_TYPE via the current instantiation. */
1924 tree context = TYPE_MAIN_VARIANT (TYPE_CONTEXT (arg));
1925 tree fullname = TYPENAME_TYPE_FULLNAME (arg);
1926 val = iterative_hash_template_arg (context, val);
1927 val = iterative_hash_template_arg (fullname, val);
1929 break;
1931 default:
1932 if (tree canonical = TYPE_CANONICAL (arg))
1933 val = iterative_hash_object (TYPE_HASH (canonical), val);
1934 else if (tree ti = TYPE_TEMPLATE_INFO (arg))
1936 val = iterative_hash_template_arg (TI_TEMPLATE (ti), val);
1937 val = iterative_hash_template_arg (TI_ARGS (ti), val);
1939 break;
1942 return val;
1944 case tcc_declaration:
1945 case tcc_constant:
1946 return iterative_hash_expr (arg, val);
1948 default:
1949 gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1950 for (int i = 0, n = cp_tree_operand_length (arg); i < n; ++i)
1951 val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1952 return val;
1956 /* Unregister the specialization SPEC as a specialization of TMPL.
1957 Replace it with NEW_SPEC, if NEW_SPEC is non-NULL. Returns true
1958 if the SPEC was listed as a specialization of TMPL.
1960 Note that SPEC has been ggc_freed, so we can't look inside it. */
1962 bool
1963 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1965 spec_entry *entry;
1966 spec_entry elt;
1968 elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1969 elt.args = TI_ARGS (tinfo);
1970 elt.spec = NULL_TREE;
1972 entry = decl_specializations->find (&elt);
1973 if (entry != NULL)
1975 gcc_assert (entry->spec == spec || entry->spec == new_spec);
1976 gcc_assert (new_spec != NULL_TREE);
1977 entry->spec = new_spec;
1978 return 1;
1981 return 0;
1984 /* Like register_specialization, but for local declarations. We are
1985 registering SPEC, an instantiation of TMPL. */
1987 void
1988 register_local_specialization (tree spec, tree tmpl)
1990 gcc_assert (tmpl != spec);
1991 local_specializations->put (tmpl, spec);
1994 /* Registers T as a specialization of itself. This is used to preserve
1995 the references to already-parsed parameters when instantiating
1996 postconditions. */
1998 void
1999 register_local_identity (tree t)
2001 local_specializations->put (t, t);
2004 /* TYPE is a class type. Returns true if TYPE is an explicitly
2005 specialized class. */
2007 bool
2008 explicit_class_specialization_p (tree type)
2010 if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
2011 return false;
2012 return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
2015 /* Print the list of functions at FNS, going through all the overloads
2016 for each element of the list. Alternatively, FNS cannot be a
2017 TREE_LIST, in which case it will be printed together with all the
2018 overloads.
2020 MORE and *STR should respectively be FALSE and NULL when the function
2021 is called from the outside. They are used internally on recursive
2022 calls. print_candidates manages the two parameters and leaves NULL
2023 in *STR when it ends. */
2025 static void
2026 print_candidates_1 (tree fns, char **str, bool more = false)
2028 if (TREE_CODE (fns) == TREE_LIST)
2029 for (; fns; fns = TREE_CHAIN (fns))
2030 print_candidates_1 (TREE_VALUE (fns), str, more || TREE_CHAIN (fns));
2031 else
2032 for (lkp_iterator iter (fns); iter;)
2034 tree cand = *iter;
2035 ++iter;
2037 const char *pfx = *str;
2038 if (!pfx)
2040 if (more || iter)
2041 pfx = _("candidates are:");
2042 else
2043 pfx = _("candidate is:");
2044 *str = get_spaces (pfx);
2046 inform (DECL_SOURCE_LOCATION (cand), "%s %#qD", pfx, cand);
2050 /* Print the list of candidate FNS in an error message. FNS can also
2051 be a TREE_LIST of non-functions in the case of an ambiguous lookup. */
2053 void
2054 print_candidates (tree fns)
2056 char *str = NULL;
2057 print_candidates_1 (fns, &str);
2058 free (str);
2061 /* Get a (possibly) constrained template declaration for the
2062 purpose of ordering candidates. */
2063 static tree
2064 get_template_for_ordering (tree list)
2066 gcc_assert (TREE_CODE (list) == TREE_LIST);
2067 tree f = TREE_VALUE (list);
2068 if (tree ti = DECL_TEMPLATE_INFO (f))
2069 return TI_TEMPLATE (ti);
2070 return f;
2073 /* Among candidates having the same signature, return the
2074 most constrained or NULL_TREE if there is no best candidate.
2075 If the signatures of candidates vary (e.g., template
2076 specialization vs. member function), then there can be no
2077 most constrained.
2079 Note that we don't compare constraints on the functions
2080 themselves, but rather those of their templates. */
2081 static tree
2082 most_constrained_function (tree candidates)
2084 // Try to find the best candidate in a first pass.
2085 tree champ = candidates;
2086 for (tree c = TREE_CHAIN (champ); c; c = TREE_CHAIN (c))
2088 int winner = more_constrained (get_template_for_ordering (champ),
2089 get_template_for_ordering (c));
2090 if (winner == -1)
2091 champ = c; // The candidate is more constrained
2092 else if (winner == 0)
2093 return NULL_TREE; // Neither is more constrained
2096 // Verify that the champ is better than previous candidates.
2097 for (tree c = candidates; c != champ; c = TREE_CHAIN (c)) {
2098 if (!more_constrained (get_template_for_ordering (champ),
2099 get_template_for_ordering (c)))
2100 return NULL_TREE;
2103 return champ;
2107 /* Returns the template (one of the functions given by TEMPLATE_ID)
2108 which can be specialized to match the indicated DECL with the
2109 explicit template args given in TEMPLATE_ID. The DECL may be
2110 NULL_TREE if none is available. In that case, the functions in
2111 TEMPLATE_ID are non-members.
2113 If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
2114 specialization of a member template.
2116 The TEMPLATE_COUNT is the number of references to qualifying
2117 template classes that appeared in the name of the function. See
2118 check_explicit_specialization for a more accurate description.
2120 TSK indicates what kind of template declaration (if any) is being
2121 declared. TSK_TEMPLATE indicates that the declaration given by
2122 DECL, though a FUNCTION_DECL, has template parameters, and is
2123 therefore a template function.
2125 The template args (those explicitly specified and those deduced)
2126 are output in a newly created vector *TARGS_OUT.
2128 If it is impossible to determine the result, an error message is
2129 issued. The error_mark_node is returned to indicate failure. */
2131 static tree
2132 determine_specialization (tree template_id,
2133 tree decl,
2134 tree* targs_out,
2135 int need_member_template,
2136 int template_count,
2137 tmpl_spec_kind tsk)
2139 tree fns;
2140 tree targs;
2141 tree explicit_targs;
2142 tree candidates = NULL_TREE;
2144 /* A TREE_LIST of templates of which DECL may be a specialization.
2145 The TREE_VALUE of each node is a TEMPLATE_DECL. The
2146 corresponding TREE_PURPOSE is the set of template arguments that,
2147 when used to instantiate the template, would produce a function
2148 with the signature of DECL. */
2149 tree templates = NULL_TREE;
2150 int header_count;
2151 cp_binding_level *b;
2153 *targs_out = NULL_TREE;
2155 if (template_id == error_mark_node || decl == error_mark_node)
2156 return error_mark_node;
2158 /* We shouldn't be specializing a member template of an
2159 unspecialized class template; we already gave an error in
2160 check_specialization_scope, now avoid crashing. */
2161 if (!VAR_P (decl)
2162 && template_count && DECL_CLASS_SCOPE_P (decl)
2163 && template_class_depth (DECL_CONTEXT (decl)) > 0)
2165 gcc_assert (errorcount);
2166 return error_mark_node;
2169 fns = TREE_OPERAND (template_id, 0);
2170 explicit_targs = TREE_OPERAND (template_id, 1);
2172 if (fns == error_mark_node)
2173 return error_mark_node;
2175 /* Check for baselinks. */
2176 if (BASELINK_P (fns))
2177 fns = BASELINK_FUNCTIONS (fns);
2179 if (TREE_CODE (decl) == FUNCTION_DECL && !is_overloaded_fn (fns))
2181 error_at (DECL_SOURCE_LOCATION (decl),
2182 "%qD is not a function template", fns);
2183 return error_mark_node;
2185 else if (VAR_P (decl) && !variable_template_p (fns))
2187 error ("%qD is not a variable template", fns);
2188 return error_mark_node;
2191 /* Count the number of template headers specified for this
2192 specialization. */
2193 header_count = 0;
2194 for (b = current_binding_level;
2195 b->kind == sk_template_parms;
2196 b = b->level_chain)
2197 ++header_count;
2199 tree orig_fns = fns;
2200 bool header_mismatch = false;
2202 if (variable_template_p (fns))
2204 tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (fns));
2205 targs = coerce_template_parms (parms, explicit_targs, fns,
2206 tf_warning_or_error);
2207 if (targs != error_mark_node
2208 && constraints_satisfied_p (fns, targs))
2209 templates = tree_cons (targs, fns, templates);
2211 else for (lkp_iterator iter (fns); iter; ++iter)
2213 tree fn = *iter;
2215 if (TREE_CODE (fn) == TEMPLATE_DECL)
2217 tree decl_arg_types;
2218 tree fn_arg_types;
2220 /* In case of explicit specialization, we need to check if
2221 the number of template headers appearing in the specialization
2222 is correct. This is usually done in check_explicit_specialization,
2223 but the check done there cannot be exhaustive when specializing
2224 member functions. Consider the following code:
2226 template <> void A<int>::f(int);
2227 template <> template <> void A<int>::f(int);
2229 Assuming that A<int> is not itself an explicit specialization
2230 already, the first line specializes "f" which is a non-template
2231 member function, whilst the second line specializes "f" which
2232 is a template member function. So both lines are syntactically
2233 correct, and check_explicit_specialization does not reject
2234 them.
2236 Here, we can do better, as we are matching the specialization
2237 against the declarations. We count the number of template
2238 headers, and we check if they match TEMPLATE_COUNT + 1
2239 (TEMPLATE_COUNT is the number of qualifying template classes,
2240 plus there must be another header for the member template
2241 itself).
2243 Notice that if header_count is zero, this is not a
2244 specialization but rather a template instantiation, so there
2245 is no check we can perform here. */
2246 if (header_count && header_count != template_count + 1)
2248 header_mismatch = true;
2249 continue;
2252 /* Check that the number of template arguments at the
2253 innermost level for DECL is the same as for FN. */
2254 if (current_binding_level->kind == sk_template_parms
2255 && !current_binding_level->explicit_spec_p
2256 && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
2257 != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
2258 (current_template_parms))))
2259 continue;
2261 /* DECL might be a specialization of FN. */
2262 decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2263 fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
2265 /* For a non-static member function, we need to make sure
2266 that the const qualification is the same. Since
2267 get_bindings does not try to merge the "this" parameter,
2268 we must do the comparison explicitly. */
2269 if (DECL_IOBJ_MEMBER_FUNCTION_P (fn))
2271 if (!same_type_p (TREE_VALUE (fn_arg_types),
2272 TREE_VALUE (decl_arg_types)))
2273 continue;
2275 /* And the ref-qualification. */
2276 if (type_memfn_rqual (TREE_TYPE (decl))
2277 != type_memfn_rqual (TREE_TYPE (fn)))
2278 continue;
2281 /* Skip the "this" parameter and, for constructors of
2282 classes with virtual bases, the VTT parameter. A
2283 full specialization of a constructor will have a VTT
2284 parameter, but a template never will. */
2285 decl_arg_types
2286 = skip_artificial_parms_for (decl, decl_arg_types);
2287 fn_arg_types
2288 = skip_artificial_parms_for (fn, fn_arg_types);
2290 /* Function templates cannot be specializations; there are
2291 no partial specializations of functions. Therefore, if
2292 the type of DECL does not match FN, there is no
2293 match.
2295 Note that it should never be the case that we have both
2296 candidates added here, and for regular member functions
2297 below. */
2298 if (tsk == tsk_template)
2300 if (!comp_template_parms (DECL_TEMPLATE_PARMS (fn),
2301 current_template_parms))
2302 continue;
2303 if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2304 TREE_TYPE (TREE_TYPE (fn))))
2305 continue;
2306 if (!compparms (fn_arg_types, decl_arg_types))
2307 continue;
2309 tree freq = get_constraints (fn);
2310 tree dreq = get_constraints (decl);
2311 if (!freq != !dreq)
2312 continue;
2313 if (freq)
2315 /* C++20 CA104: Substitute directly into the
2316 constraint-expression. */
2317 tree fargs = DECL_TI_ARGS (fn);
2318 tsubst_flags_t complain = tf_none;
2319 freq = tsubst_constraint_info (freq, fargs, complain, fn);
2320 if (!cp_tree_equal (freq, dreq))
2321 continue;
2324 candidates = tree_cons (NULL_TREE, fn, candidates);
2325 continue;
2328 /* See whether this function might be a specialization of this
2329 template. Suppress access control because we might be trying
2330 to make this specialization a friend, and we have already done
2331 access control for the declaration of the specialization. */
2332 push_deferring_access_checks (dk_no_check);
2333 targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
2334 pop_deferring_access_checks ();
2336 if (!targs)
2337 /* We cannot deduce template arguments that when used to
2338 specialize TMPL will produce DECL. */
2339 continue;
2341 if (uses_template_parms (targs))
2342 /* We deduced something involving 'auto', which isn't a valid
2343 template argument. */
2344 continue;
2346 /* Save this template, and the arguments deduced. */
2347 templates = tree_cons (targs, fn, templates);
2349 else if (need_member_template)
2350 /* FN is an ordinary member function, and we need a
2351 specialization of a member template. */
2353 else if (TREE_CODE (fn) != FUNCTION_DECL)
2354 /* We can get IDENTIFIER_NODEs here in certain erroneous
2355 cases. */
2357 else if (!DECL_FUNCTION_MEMBER_P (fn))
2358 /* This is just an ordinary non-member function. Nothing can
2359 be a specialization of that. */
2361 else if (DECL_ARTIFICIAL (fn))
2362 /* Cannot specialize functions that are created implicitly. */
2364 else
2366 tree decl_arg_types;
2368 /* This is an ordinary member function. However, since
2369 we're here, we can assume its enclosing class is a
2370 template class. For example,
2372 template <typename T> struct S { void f(); };
2373 template <> void S<int>::f() {}
2375 Here, S<int>::f is a non-template, but S<int> is a
2376 template class. If FN has the same type as DECL, we
2377 might be in business. */
2379 if (!DECL_TEMPLATE_INFO (fn))
2380 /* Its enclosing class is an explicit specialization
2381 of a template class. This is not a candidate. */
2382 continue;
2384 if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2385 TREE_TYPE (TREE_TYPE (fn))))
2386 /* The return types differ. */
2387 continue;
2389 /* Adjust the type of DECL in case FN is a static member. */
2390 decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2391 if (DECL_STATIC_FUNCTION_P (fn)
2392 && DECL_IOBJ_MEMBER_FUNCTION_P (decl))
2393 decl_arg_types = TREE_CHAIN (decl_arg_types);
2395 if (!compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
2396 decl_arg_types))
2397 continue;
2399 if (DECL_IOBJ_MEMBER_FUNCTION_P (fn)
2400 && (type_memfn_rqual (TREE_TYPE (decl))
2401 != type_memfn_rqual (TREE_TYPE (fn))))
2402 continue;
2404 // If the deduced arguments do not satisfy the constraints,
2405 // this is not a candidate.
2406 if (flag_concepts && !constraints_satisfied_p (fn))
2407 continue;
2409 // Add the candidate.
2410 candidates = tree_cons (NULL_TREE, fn, candidates);
2414 if (templates && TREE_CHAIN (templates))
2416 /* We have:
2418 [temp.expl.spec]
2420 It is possible for a specialization with a given function
2421 signature to be instantiated from more than one function
2422 template. In such cases, explicit specification of the
2423 template arguments must be used to uniquely identify the
2424 function template specialization being specialized.
2426 Note that here, there's no suggestion that we're supposed to
2427 determine which of the candidate templates is most
2428 specialized. However, we, also have:
2430 [temp.func.order]
2432 Partial ordering of overloaded function template
2433 declarations is used in the following contexts to select
2434 the function template to which a function template
2435 specialization refers:
2437 -- when an explicit specialization refers to a function
2438 template.
2440 So, we do use the partial ordering rules, at least for now.
2441 This extension can only serve to make invalid programs valid,
2442 so it's safe. And, there is strong anecdotal evidence that
2443 the committee intended the partial ordering rules to apply;
2444 the EDG front end has that behavior, and John Spicer claims
2445 that the committee simply forgot to delete the wording in
2446 [temp.expl.spec]. */
2447 tree tmpl = most_specialized_instantiation (templates);
2448 if (tmpl != error_mark_node)
2450 templates = tmpl;
2451 TREE_CHAIN (templates) = NULL_TREE;
2455 // Concepts allows multiple declarations of member functions
2456 // with the same signature. Like above, we need to rely on
2457 // on the partial ordering of those candidates to determine which
2458 // is the best.
2459 if (flag_concepts && candidates && TREE_CHAIN (candidates))
2461 if (tree cand = most_constrained_function (candidates))
2463 candidates = cand;
2464 TREE_CHAIN (cand) = NULL_TREE;
2468 if (templates == NULL_TREE && candidates == NULL_TREE)
2470 error ("template-id %qD for %q+D does not match any template "
2471 "declaration", template_id, decl);
2472 if (header_mismatch)
2473 inform (DECL_SOURCE_LOCATION (decl),
2474 "saw %d %<template<>%>, need %d for "
2475 "specializing a member function template",
2476 header_count, template_count + 1);
2477 print_candidates (orig_fns);
2478 return error_mark_node;
2480 else if ((templates && TREE_CHAIN (templates))
2481 || (candidates && TREE_CHAIN (candidates))
2482 || (templates && candidates))
2484 error ("ambiguous template specialization %qD for %q+D",
2485 template_id, decl);
2486 candidates = chainon (candidates, templates);
2487 print_candidates (candidates);
2488 return error_mark_node;
2491 /* We have one, and exactly one, match. */
2492 if (candidates)
2494 tree fn = TREE_VALUE (candidates);
2495 *targs_out = copy_node (DECL_TI_ARGS (fn));
2497 /* Propagate the candidate's constraints to the declaration. */
2498 if (tsk != tsk_template)
2499 set_constraints (decl, get_constraints (fn));
2501 /* DECL is a re-declaration or partial instantiation of a template
2502 function. */
2503 if (TREE_CODE (fn) == TEMPLATE_DECL)
2504 return fn;
2505 /* It was a specialization of an ordinary member function in a
2506 template class. */
2507 return DECL_TI_TEMPLATE (fn);
2510 /* It was a specialization of a template. */
2511 tree tmpl = TREE_VALUE (templates);
2512 *targs_out = add_outermost_template_args (tmpl, TREE_PURPOSE (templates));
2514 /* Propagate the template's constraints to the declaration. */
2515 if (tsk != tsk_template)
2516 set_constraints (decl, get_constraints (tmpl));
2518 return tmpl;
2521 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2522 but with the default argument values filled in from those in the
2523 TMPL_TYPES. */
2525 static tree
2526 copy_default_args_to_explicit_spec_1 (tree spec_types,
2527 tree tmpl_types)
2529 tree new_spec_types;
2531 if (!spec_types)
2532 return NULL_TREE;
2534 if (spec_types == void_list_node)
2535 return void_list_node;
2537 /* Substitute into the rest of the list. */
2538 new_spec_types =
2539 copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2540 TREE_CHAIN (tmpl_types));
2542 /* Add the default argument for this parameter. */
2543 return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2544 TREE_VALUE (spec_types),
2545 new_spec_types);
2548 /* DECL is an explicit specialization. Replicate default arguments
2549 from the template it specializes. (That way, code like:
2551 template <class T> void f(T = 3);
2552 template <> void f(double);
2553 void g () { f (); }
2555 works, as required.) An alternative approach would be to look up
2556 the correct default arguments at the call-site, but this approach
2557 is consistent with how implicit instantiations are handled. */
2559 static void
2560 copy_default_args_to_explicit_spec (tree decl)
2562 tree tmpl;
2563 tree spec_types;
2564 tree tmpl_types;
2565 tree new_spec_types;
2566 tree old_type;
2567 tree new_type;
2568 tree t;
2569 tree object_type = NULL_TREE;
2570 tree in_charge = NULL_TREE;
2571 tree vtt = NULL_TREE;
2573 /* See if there's anything we need to do. */
2574 tmpl = DECL_TI_TEMPLATE (decl);
2575 tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2576 for (t = tmpl_types; t; t = TREE_CHAIN (t))
2577 if (TREE_PURPOSE (t))
2578 break;
2579 if (!t)
2580 return;
2582 old_type = TREE_TYPE (decl);
2583 spec_types = TYPE_ARG_TYPES (old_type);
2585 if (DECL_IOBJ_MEMBER_FUNCTION_P (decl))
2587 /* Remove the this pointer, but remember the object's type for
2588 CV quals. */
2589 object_type = TREE_TYPE (TREE_VALUE (spec_types));
2590 spec_types = TREE_CHAIN (spec_types);
2591 tmpl_types = TREE_CHAIN (tmpl_types);
2593 if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2595 /* DECL may contain more parameters than TMPL due to the extra
2596 in-charge parameter in constructors and destructors. */
2597 in_charge = spec_types;
2598 spec_types = TREE_CHAIN (spec_types);
2600 if (DECL_HAS_VTT_PARM_P (decl))
2602 vtt = spec_types;
2603 spec_types = TREE_CHAIN (spec_types);
2607 /* Compute the merged default arguments. */
2608 new_spec_types =
2609 copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2611 /* Compute the new FUNCTION_TYPE. */
2612 if (object_type)
2614 if (vtt)
2615 new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2616 TREE_VALUE (vtt),
2617 new_spec_types);
2619 if (in_charge)
2620 /* Put the in-charge parameter back. */
2621 new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2622 TREE_VALUE (in_charge),
2623 new_spec_types);
2625 new_type = build_method_type_directly (object_type,
2626 TREE_TYPE (old_type),
2627 new_spec_types);
2629 else
2630 new_type = build_function_type (TREE_TYPE (old_type),
2631 new_spec_types);
2632 new_type = cp_build_type_attribute_variant (new_type,
2633 TYPE_ATTRIBUTES (old_type));
2634 new_type = cxx_copy_lang_qualifiers (new_type, old_type);
2636 TREE_TYPE (decl) = new_type;
2639 /* Return the number of template headers we expect to see for a definition
2640 or specialization of CTYPE or one of its non-template members. */
2643 num_template_headers_for_class (tree ctype)
2645 int num_templates = 0;
2647 while (ctype && CLASS_TYPE_P (ctype))
2649 /* You're supposed to have one `template <...>' for every
2650 template class, but you don't need one for a full
2651 specialization. For example:
2653 template <class T> struct S{};
2654 template <> struct S<int> { void f(); };
2655 void S<int>::f () {}
2657 is correct; there shouldn't be a `template <>' for the
2658 definition of `S<int>::f'. */
2659 if (!CLASSTYPE_TEMPLATE_INFO (ctype))
2660 /* If CTYPE does not have template information of any
2661 kind, then it is not a template, nor is it nested
2662 within a template. */
2663 break;
2664 if (explicit_class_specialization_p (ctype))
2665 break;
2666 if (PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (ctype)))
2667 ++num_templates;
2669 ctype = TYPE_CONTEXT (ctype);
2672 return num_templates;
2675 /* Do a simple sanity check on the template headers that precede the
2676 variable declaration DECL. */
2678 void
2679 check_template_variable (tree decl)
2681 tree ctx = CP_DECL_CONTEXT (decl);
2682 int wanted = num_template_headers_for_class (ctx);
2683 if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)
2684 && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl)))
2686 if (cxx_dialect < cxx14)
2687 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wc__14_extensions,
2688 "variable templates only available with "
2689 "%<-std=c++14%> or %<-std=gnu++14%>");
2691 // Namespace-scope variable templates should have a template header.
2692 ++wanted;
2694 if (template_header_count > wanted)
2696 auto_diagnostic_group d;
2697 bool warned = pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2698 "too many template headers for %qD "
2699 "(should be %d)",
2700 decl, wanted);
2701 if (warned && CLASS_TYPE_P (ctx)
2702 && CLASSTYPE_TEMPLATE_SPECIALIZATION (ctx))
2703 inform (DECL_SOURCE_LOCATION (decl),
2704 "members of an explicitly specialized class are defined "
2705 "without a template header");
2709 /* An explicit specialization whose declarator-id or class-head-name is not
2710 qualified shall be declared in the nearest enclosing namespace of the
2711 template, or, if the namespace is inline (7.3.1), any namespace from its
2712 enclosing namespace set.
2714 If the name declared in the explicit instantiation is an unqualified name,
2715 the explicit instantiation shall appear in the namespace where its template
2716 is declared or, if that namespace is inline (7.3.1), any namespace from its
2717 enclosing namespace set. */
2719 void
2720 check_unqualified_spec_or_inst (tree t, location_t loc)
2722 tree tmpl = most_general_template (t);
2723 if (DECL_NAMESPACE_SCOPE_P (tmpl)
2724 && !is_nested_namespace (current_namespace,
2725 CP_DECL_CONTEXT (tmpl), true))
2727 if (processing_specialization)
2728 permerror (loc, "explicit specialization of %qD outside its "
2729 "namespace must use a nested-name-specifier", tmpl);
2730 else if (processing_explicit_instantiation
2731 && cxx_dialect >= cxx11)
2732 /* This was allowed in C++98, so only pedwarn. */
2733 pedwarn (loc, OPT_Wpedantic, "explicit instantiation of %qD "
2734 "outside its namespace must use a nested-name-"
2735 "specifier", tmpl);
2739 /* Warn for a template specialization SPEC that is missing some of a set
2740 of function or type attributes that the template TEMPL is declared with.
2741 ATTRLIST is a list of additional attributes that SPEC should be taken
2742 to ultimately be declared with. */
2744 static void
2745 warn_spec_missing_attributes (tree tmpl, tree spec, tree attrlist)
2747 if (DECL_FUNCTION_TEMPLATE_P (tmpl))
2748 tmpl = DECL_TEMPLATE_RESULT (tmpl);
2750 /* Avoid warning if the difference between the primary and
2751 the specialization is not in one of the attributes below. */
2752 const char* const blacklist[] = {
2753 "alloc_align", "alloc_size", "assume_aligned", "format",
2754 "format_arg", "malloc", "nonnull", NULL
2757 /* Put together a list of the black listed attributes that the primary
2758 template is declared with that the specialization is not, in case
2759 it's not apparent from the most recent declaration of the primary. */
2760 pretty_printer str;
2761 unsigned nattrs = decls_mismatched_attributes (tmpl, spec, attrlist,
2762 blacklist, &str);
2764 if (!nattrs)
2765 return;
2767 auto_diagnostic_group d;
2768 if (warning_at (DECL_SOURCE_LOCATION (spec), OPT_Wmissing_attributes,
2769 "explicit specialization %q#D may be missing attributes",
2770 spec))
2771 inform (DECL_SOURCE_LOCATION (tmpl),
2772 nattrs > 1
2773 ? G_("missing primary template attributes %s")
2774 : G_("missing primary template attribute %s"),
2775 pp_formatted_text (&str));
2778 /* Check to see if the function just declared, as indicated in
2779 DECLARATOR, and in DECL, is a specialization of a function
2780 template. We may also discover that the declaration is an explicit
2781 instantiation at this point.
2783 Returns DECL, or an equivalent declaration that should be used
2784 instead if all goes well. Issues an error message if something is
2785 amiss. Returns error_mark_node if the error is not easily
2786 recoverable.
2788 FLAGS is a bitmask consisting of the following flags:
2790 2: The function has a definition.
2791 4: The function is a friend.
2793 The TEMPLATE_COUNT is the number of references to qualifying
2794 template classes that appeared in the name of the function. For
2795 example, in
2797 template <class T> struct S { void f(); };
2798 void S<int>::f();
2800 the TEMPLATE_COUNT would be 1. However, explicitly specialized
2801 classes are not counted in the TEMPLATE_COUNT, so that in
2803 template <class T> struct S {};
2804 template <> struct S<int> { void f(); }
2805 template <> void S<int>::f();
2807 the TEMPLATE_COUNT would be 0. (Note that this declaration is
2808 invalid; there should be no template <>.)
2810 If the function is a specialization, it is marked as such via
2811 DECL_TEMPLATE_SPECIALIZATION. Furthermore, its DECL_TEMPLATE_INFO
2812 is set up correctly, and it is added to the list of specializations
2813 for that template. */
2815 tree
2816 check_explicit_specialization (tree declarator,
2817 tree decl,
2818 int template_count,
2819 int flags,
2820 tree attrlist)
2822 int have_def = flags & 2;
2823 int is_friend = flags & 4;
2824 bool is_concept = flags & 8;
2825 int specialization = 0;
2826 int explicit_instantiation = 0;
2827 int member_specialization = 0;
2828 tree ctype = DECL_CLASS_CONTEXT (decl);
2829 tree dname = DECL_NAME (decl);
2830 tmpl_spec_kind tsk;
2832 if (is_friend)
2834 if (!processing_specialization)
2835 tsk = tsk_none;
2836 else
2837 tsk = tsk_excessive_parms;
2839 else
2840 tsk = current_tmpl_spec_kind (template_count);
2842 switch (tsk)
2844 case tsk_none:
2845 if (processing_specialization && !VAR_P (decl))
2847 specialization = 1;
2848 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2850 else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR
2851 || (DECL_LANG_SPECIFIC (decl)
2852 && DECL_IMPLICIT_INSTANTIATION (decl)))
2854 if (is_friend)
2855 /* This could be something like:
2857 template <class T> void f(T);
2858 class S { friend void f<>(int); } */
2859 specialization = 1;
2860 else
2862 /* This case handles bogus declarations like template <>
2863 template <class T> void f<int>(); */
2865 error_at (cp_expr_loc_or_input_loc (declarator),
2866 "template-id %qE in declaration of primary template",
2867 declarator);
2868 return decl;
2871 break;
2873 case tsk_invalid_member_spec:
2874 /* The error has already been reported in
2875 check_specialization_scope. */
2876 return error_mark_node;
2878 case tsk_invalid_expl_inst:
2879 error ("template parameter list used in explicit instantiation");
2881 /* Fall through. */
2883 case tsk_expl_inst:
2884 if (have_def)
2885 error ("definition provided for explicit instantiation");
2887 explicit_instantiation = 1;
2888 break;
2890 case tsk_excessive_parms:
2891 case tsk_insufficient_parms:
2892 if (tsk == tsk_excessive_parms)
2893 error ("too many template parameter lists in declaration of %qD",
2894 decl);
2895 else if (template_header_count)
2896 error("too few template parameter lists in declaration of %qD", decl);
2897 else
2898 error("explicit specialization of %qD must be introduced by "
2899 "%<template <>%>", decl);
2901 /* Fall through. */
2902 case tsk_expl_spec:
2903 if (is_concept)
2904 error ("explicit specialization declared %<concept%>");
2906 if (VAR_P (decl) && TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2907 /* In cases like template<> constexpr bool v = true;
2908 We'll give an error in check_template_variable. */
2909 break;
2911 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2912 if (ctype)
2913 member_specialization = 1;
2914 else
2915 specialization = 1;
2916 break;
2918 case tsk_template:
2919 if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2921 /* This case handles bogus declarations like template <>
2922 template <class T> void f<int>(); */
2924 if (!uses_template_parms (TREE_OPERAND (declarator, 1)))
2925 error_at (cp_expr_loc_or_input_loc (declarator),
2926 "template-id %qE in declaration of primary template",
2927 declarator);
2928 else if (variable_template_p (TREE_OPERAND (declarator, 0)))
2930 /* Partial specialization of variable template. */
2931 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2932 specialization = 1;
2933 goto ok;
2935 else if (cxx_dialect < cxx14)
2936 error_at (cp_expr_loc_or_input_loc (declarator),
2937 "non-type partial specialization %qE "
2938 "is not allowed", declarator);
2939 else
2940 error_at (cp_expr_loc_or_input_loc (declarator),
2941 "non-class, non-variable partial specialization %qE "
2942 "is not allowed", declarator);
2943 return decl;
2944 ok:;
2947 if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2948 /* This is a specialization of a member template, without
2949 specialization the containing class. Something like:
2951 template <class T> struct S {
2952 template <class U> void f (U);
2954 template <> template <class U> void S<int>::f(U) {}
2956 That's a specialization -- but of the entire template. */
2957 specialization = 1;
2958 break;
2960 default:
2961 gcc_unreachable ();
2964 if ((specialization || member_specialization)
2965 /* This doesn't apply to variable templates. */
2966 && FUNC_OR_METHOD_TYPE_P (TREE_TYPE (decl)))
2968 tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2969 for (; t; t = TREE_CHAIN (t))
2970 if (TREE_PURPOSE (t))
2972 permerror (input_location,
2973 "default argument specified in explicit specialization");
2974 break;
2978 if (specialization || member_specialization || explicit_instantiation)
2980 tree tmpl = NULL_TREE;
2981 tree targs = NULL_TREE;
2982 bool was_template_id = (TREE_CODE (declarator) == TEMPLATE_ID_EXPR);
2983 bool found_hidden = false;
2985 /* Make sure that the declarator is a TEMPLATE_ID_EXPR. */
2986 if (!was_template_id)
2988 tree fns;
2990 gcc_assert (identifier_p (declarator));
2991 if (ctype)
2992 fns = dname;
2993 else
2995 /* If there is no class context, the explicit instantiation
2996 must be at namespace scope. */
2997 gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2999 /* Find the namespace binding, using the declaration
3000 context. */
3001 fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
3002 LOOK_want::NORMAL, true);
3003 if (fns == error_mark_node)
3005 /* If lookup fails, look for a friend declaration so we can
3006 give a better diagnostic. */
3007 fns = (lookup_qualified_name
3008 (CP_DECL_CONTEXT (decl), dname,
3009 LOOK_want::NORMAL | LOOK_want::HIDDEN_FRIEND,
3010 /*complain*/true));
3011 found_hidden = true;
3014 if (fns == error_mark_node || !is_overloaded_fn (fns))
3016 error ("%qD is not a template function", dname);
3017 fns = error_mark_node;
3021 declarator = lookup_template_function (fns, NULL_TREE);
3024 if (declarator == error_mark_node)
3025 return error_mark_node;
3027 if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
3029 if (!explicit_instantiation)
3030 /* A specialization in class scope. This is invalid,
3031 but the error will already have been flagged by
3032 check_specialization_scope. */
3033 return error_mark_node;
3034 else
3036 /* It's not valid to write an explicit instantiation in
3037 class scope, e.g.:
3039 class C { template void f(); }
3041 This case is caught by the parser. However, on
3042 something like:
3044 template class C { void f(); };
3046 (which is invalid) we can get here. The error will be
3047 issued later. */
3051 return decl;
3053 else if (ctype != NULL_TREE
3054 && (identifier_p (TREE_OPERAND (declarator, 0))))
3056 // We'll match variable templates in start_decl.
3057 if (VAR_P (decl))
3058 return decl;
3060 /* Find the list of functions in ctype that have the same
3061 name as the declared function. */
3062 tree name = TREE_OPERAND (declarator, 0);
3064 if (constructor_name_p (name, ctype))
3066 if (DECL_CONSTRUCTOR_P (decl)
3067 ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
3068 : !CLASSTYPE_DESTRUCTOR (ctype))
3070 /* From [temp.expl.spec]:
3072 If such an explicit specialization for the member
3073 of a class template names an implicitly-declared
3074 special member function (clause _special_), the
3075 program is ill-formed.
3077 Similar language is found in [temp.explicit]. */
3078 error ("specialization of implicitly-declared special member function");
3079 return error_mark_node;
3082 name = DECL_NAME (decl);
3085 /* For a type-conversion operator, We might be looking for
3086 `operator int' which will be a specialization of
3087 `operator T'. Grab all the conversion operators, and
3088 then select from them. */
3089 tree fns = get_class_binding (ctype, IDENTIFIER_CONV_OP_P (name)
3090 ? conv_op_identifier : name);
3092 if (fns == NULL_TREE)
3094 error ("no member function %qD declared in %qT", name, ctype);
3095 return error_mark_node;
3097 else
3098 TREE_OPERAND (declarator, 0) = fns;
3101 /* Figure out what exactly is being specialized at this point.
3102 Note that for an explicit instantiation, even one for a
3103 member function, we cannot tell a priori whether the
3104 instantiation is for a member template, or just a member
3105 function of a template class. Even if a member template is
3106 being instantiated, the member template arguments may be
3107 elided if they can be deduced from the rest of the
3108 declaration. */
3109 tmpl = determine_specialization (declarator, decl,
3110 &targs,
3111 member_specialization,
3112 template_count,
3113 tsk);
3115 if (!tmpl || tmpl == error_mark_node)
3116 /* We couldn't figure out what this declaration was
3117 specializing. */
3118 return error_mark_node;
3119 else
3121 if (found_hidden && TREE_CODE (decl) == FUNCTION_DECL)
3123 auto_diagnostic_group d;
3124 if (pedwarn (DECL_SOURCE_LOCATION (decl), 0,
3125 "friend declaration %qD is not visible to "
3126 "explicit specialization", tmpl))
3127 inform (DECL_SOURCE_LOCATION (tmpl),
3128 "friend declaration here");
3131 if (!ctype && !is_friend
3132 && CP_DECL_CONTEXT (decl) == current_namespace)
3133 check_unqualified_spec_or_inst (tmpl, DECL_SOURCE_LOCATION (decl));
3135 tree gen_tmpl = most_general_template (tmpl);
3137 if (explicit_instantiation)
3139 /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
3140 is done by do_decl_instantiation later. */
3142 int arg_depth = TMPL_ARGS_DEPTH (targs);
3143 int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
3145 if (arg_depth > parm_depth)
3147 /* If TMPL is not the most general template (for
3148 example, if TMPL is a friend template that is
3149 injected into namespace scope), then there will
3150 be too many levels of TARGS. Remove some of them
3151 here. */
3152 int i;
3153 tree new_targs;
3155 new_targs = make_tree_vec (parm_depth);
3156 for (i = arg_depth - parm_depth; i < arg_depth; ++i)
3157 TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
3158 = TREE_VEC_ELT (targs, i);
3159 targs = new_targs;
3162 return instantiate_template (tmpl, targs, tf_error);
3165 /* If we thought that the DECL was a member function, but it
3166 turns out to be specializing a static member function,
3167 make DECL a static member function as well. */
3168 if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3169 && DECL_STATIC_FUNCTION_P (tmpl)
3170 && DECL_IOBJ_MEMBER_FUNCTION_P (decl))
3171 revert_static_member_fn (decl);
3173 /* If this is a specialization of a member template of a
3174 template class, we want to return the TEMPLATE_DECL, not
3175 the specialization of it. */
3176 if (tsk == tsk_template && !was_template_id)
3178 tree result = DECL_TEMPLATE_RESULT (tmpl);
3179 SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3180 DECL_INITIAL (result) = NULL_TREE;
3181 if (have_def)
3183 tree parm;
3184 DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
3185 DECL_SOURCE_LOCATION (result)
3186 = DECL_SOURCE_LOCATION (decl);
3187 /* We want to use the argument list specified in the
3188 definition, not in the original declaration. */
3189 DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
3190 for (parm = DECL_ARGUMENTS (result); parm;
3191 parm = DECL_CHAIN (parm))
3192 DECL_CONTEXT (parm) = result;
3194 decl = register_specialization (tmpl, gen_tmpl, targs,
3195 is_friend, 0);
3196 remove_contract_attributes (result);
3197 return decl;
3200 /* Set up the DECL_TEMPLATE_INFO for DECL. */
3201 DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
3203 if (was_template_id)
3204 TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl)) = true;
3206 /* Inherit default function arguments from the template
3207 DECL is specializing. */
3208 if (DECL_FUNCTION_TEMPLATE_P (tmpl))
3209 copy_default_args_to_explicit_spec (decl);
3211 /* This specialization has the same protection as the
3212 template it specializes. */
3213 TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
3214 TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
3216 /* 7.1.1-1 [dcl.stc]
3218 A storage-class-specifier shall not be specified in an
3219 explicit specialization...
3221 The parser rejects these, so unless action is taken here,
3222 explicit function specializations will always appear with
3223 global linkage.
3225 The action recommended by the C++ CWG in response to C++
3226 defect report 605 is to make the storage class and linkage
3227 of the explicit specialization match the templated function:
3229 http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
3231 if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
3233 tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
3234 gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
3236 /* A concept cannot be specialized. */
3237 if (DECL_DECLARED_CONCEPT_P (tmpl_func))
3239 error ("explicit specialization of function concept %qD",
3240 gen_tmpl);
3241 return error_mark_node;
3244 /* This specialization has the same linkage and visibility as
3245 the function template it specializes. */
3246 TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
3247 if (! TREE_PUBLIC (decl))
3249 DECL_INTERFACE_KNOWN (decl) = 1;
3250 DECL_NOT_REALLY_EXTERN (decl) = 1;
3252 DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
3253 if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
3255 DECL_VISIBILITY_SPECIFIED (decl) = 1;
3256 DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
3260 /* If DECL is a friend declaration, declared using an
3261 unqualified name, the namespace associated with DECL may
3262 have been set incorrectly. For example, in:
3264 template <typename T> void f(T);
3265 namespace N {
3266 struct S { friend void f<int>(int); }
3269 we will have set the DECL_CONTEXT for the friend
3270 declaration to N, rather than to the global namespace. */
3271 if (DECL_NAMESPACE_SCOPE_P (decl))
3272 DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
3274 if (is_friend && !have_def)
3275 /* This is not really a declaration of a specialization.
3276 It's just the name of an instantiation. But, it's not
3277 a request for an instantiation, either. */
3278 SET_DECL_IMPLICIT_INSTANTIATION (decl);
3279 else if (TREE_CODE (decl) == FUNCTION_DECL)
3280 /* A specialization is not necessarily COMDAT. */
3281 DECL_COMDAT (decl) = (TREE_PUBLIC (decl)
3282 && DECL_DECLARED_INLINE_P (decl));
3283 else if (VAR_P (decl))
3284 DECL_COMDAT (decl) = false;
3286 /* If this is a full specialization, register it so that we can find
3287 it again. Partial specializations will be registered in
3288 process_partial_specialization. */
3289 if (!processing_template_decl)
3291 warn_spec_missing_attributes (gen_tmpl, decl, attrlist);
3293 decl = register_specialization (decl, gen_tmpl, targs,
3294 is_friend, 0);
3297 /* If this is a specialization, splice any contracts that may have
3298 been inherited from the template, removing them. */
3299 if (decl != error_mark_node && DECL_TEMPLATE_SPECIALIZATION (decl))
3300 remove_contract_attributes (decl);
3302 /* A 'structor should already have clones. */
3303 gcc_assert (decl == error_mark_node
3304 || variable_template_p (tmpl)
3305 || !(DECL_CONSTRUCTOR_P (decl)
3306 || DECL_DESTRUCTOR_P (decl))
3307 || DECL_CLONED_FUNCTION_P (DECL_CHAIN (decl)));
3311 return decl;
3314 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
3315 parameters. These are represented in the same format used for
3316 DECL_TEMPLATE_PARMS. */
3319 comp_template_parms (const_tree parms1, const_tree parms2)
3321 if (parms1 == parms2)
3322 return 1;
3324 tree t1 = TREE_VALUE (parms1);
3325 tree t2 = TREE_VALUE (parms2);
3326 int i;
3328 gcc_assert (TREE_CODE (t1) == TREE_VEC);
3329 gcc_assert (TREE_CODE (t2) == TREE_VEC);
3331 if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
3332 return 0;
3334 for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
3336 tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
3337 tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
3339 /* If either of the template parameters are invalid, assume
3340 they match for the sake of error recovery. */
3341 if (error_operand_p (parm1) || error_operand_p (parm2))
3342 return 1;
3344 if (TREE_CODE (parm1) != TREE_CODE (parm2))
3345 return 0;
3347 if (TREE_CODE (parm1) == TYPE_DECL
3348 && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm1))
3349 == TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm2))))
3350 continue;
3351 else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
3352 return 0;
3355 return 1;
3358 /* Returns true if two template parameters are declared with
3359 equivalent constraints. */
3361 static bool
3362 template_parameter_constraints_equivalent_p (const_tree parm1, const_tree parm2)
3364 tree req1 = TREE_TYPE (parm1);
3365 tree req2 = TREE_TYPE (parm2);
3366 if (!req1 != !req2)
3367 return false;
3368 if (req1)
3369 return cp_tree_equal (req1, req2);
3370 return true;
3373 /* Returns true when two template parameters are equivalent. */
3375 static bool
3376 template_parameters_equivalent_p (const_tree parm1, const_tree parm2)
3378 tree decl1 = TREE_VALUE (parm1);
3379 tree decl2 = TREE_VALUE (parm2);
3381 /* If either of the template parameters are invalid, assume
3382 they match for the sake of error recovery. */
3383 if (error_operand_p (decl1) || error_operand_p (decl2))
3384 return true;
3386 /* ... they declare parameters of the same kind. */
3387 if (TREE_CODE (decl1) != TREE_CODE (decl2))
3388 return false;
3390 /* ... one parameter was introduced by a parameter declaration, then
3391 both are. This case arises as a result of eagerly rewriting declarations
3392 during parsing. */
3393 if (DECL_IMPLICIT_TEMPLATE_PARM_P (decl1)
3394 != DECL_IMPLICIT_TEMPLATE_PARM_P (decl2))
3395 return false;
3397 /* ... if either declares a pack, they both do. */
3398 if (template_parameter_pack_p (decl1) != template_parameter_pack_p (decl2))
3399 return false;
3401 if (TREE_CODE (decl1) == PARM_DECL)
3403 /* ... if they declare non-type parameters, the types are equivalent. */
3404 if (!same_type_p (TREE_TYPE (decl1), TREE_TYPE (decl2)))
3405 return false;
3407 else if (TREE_CODE (decl2) == TEMPLATE_DECL)
3409 /* ... if they declare template template parameters, their template
3410 parameter lists are equivalent. */
3411 if (!template_heads_equivalent_p (decl1, decl2))
3412 return false;
3415 /* ... if they are declared with a qualified-concept name, they both
3416 are, and those names are equivalent. */
3417 return template_parameter_constraints_equivalent_p (parm1, parm2);
3420 /* Returns true if two template parameters lists are equivalent.
3421 Two template parameter lists are equivalent if they have the
3422 same length and their corresponding parameters are equivalent.
3424 PARMS1 and PARMS2 are TREE_LISTs containing TREE_VECs: the
3425 data structure returned by DECL_TEMPLATE_PARMS.
3427 This is generally the same implementation as comp_template_parms
3428 except that it also the concept names and arguments used to
3429 introduce parameters. */
3431 static bool
3432 template_parameter_lists_equivalent_p (const_tree parms1, const_tree parms2)
3434 if (parms1 == parms2)
3435 return true;
3437 tree list1 = TREE_VALUE (parms1);
3438 tree list2 = TREE_VALUE (parms2);
3440 if (TREE_VEC_LENGTH (list1) != TREE_VEC_LENGTH (list2))
3441 return 0;
3443 for (int i = 0; i < TREE_VEC_LENGTH (list2); ++i)
3445 tree parm1 = TREE_VEC_ELT (list1, i);
3446 tree parm2 = TREE_VEC_ELT (list2, i);
3447 if (!template_parameters_equivalent_p (parm1, parm2))
3448 return false;
3451 return true;
3454 /* Return true if the requires-clause of the template parameter lists are
3455 equivalent and false otherwise. */
3456 static bool
3457 template_requirements_equivalent_p (const_tree parms1, const_tree parms2)
3459 tree req1 = TEMPLATE_PARMS_CONSTRAINTS (parms1);
3460 tree req2 = TEMPLATE_PARMS_CONSTRAINTS (parms2);
3461 if ((req1 != NULL_TREE) != (req2 != NULL_TREE))
3462 return false;
3463 if (!cp_tree_equal (req1, req2))
3464 return false;
3465 return true;
3468 /* Returns true if two template heads are equivalent. 17.6.6.1p6:
3469 Two template heads are equivalent if their template parameter
3470 lists are equivalent and their requires clauses are equivalent.
3472 In pre-C++20, this is equivalent to calling comp_template_parms
3473 for the template parameters of TMPL1 and TMPL2. */
3475 bool
3476 template_heads_equivalent_p (const_tree tmpl1, const_tree tmpl2)
3478 tree parms1 = DECL_TEMPLATE_PARMS (tmpl1);
3479 tree parms2 = DECL_TEMPLATE_PARMS (tmpl2);
3481 /* Don't change the matching rules for pre-C++20. */
3482 if (cxx_dialect < cxx20)
3483 return comp_template_parms (parms1, parms2);
3485 /* ... have the same number of template parameters, and their
3486 corresponding parameters are equivalent. */
3487 if (!template_parameter_lists_equivalent_p (parms1, parms2))
3488 return false;
3490 /* ... if either has a requires-clause, they both do and their
3491 corresponding constraint-expressions are equivalent. */
3492 return template_requirements_equivalent_p (parms1, parms2);
3495 /* Determine whether PARM is a parameter pack. */
3497 bool
3498 template_parameter_pack_p (const_tree parm)
3500 /* Determine if we have a non-type template parameter pack. */
3501 if (TREE_CODE (parm) == PARM_DECL)
3502 return (DECL_TEMPLATE_PARM_P (parm)
3503 && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
3504 if (TREE_CODE (parm) == TEMPLATE_PARM_INDEX)
3505 return TEMPLATE_PARM_PARAMETER_PACK (parm);
3507 /* If this is a list of template parameters, we could get a
3508 TYPE_DECL or a TEMPLATE_DECL. */
3509 if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
3510 parm = TREE_TYPE (parm);
3512 /* Otherwise it must be a type template parameter. */
3513 return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
3514 || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
3515 && TEMPLATE_TYPE_PARAMETER_PACK (parm));
3518 /* Determine if T is a function parameter pack. */
3520 bool
3521 function_parameter_pack_p (const_tree t)
3523 if (t && TREE_CODE (t) == PARM_DECL)
3524 return DECL_PACK_P (t);
3525 return false;
3528 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
3529 PRIMARY_FUNC_TMPL_INST is a primary function template instantiation. */
3531 tree
3532 get_function_template_decl (const_tree primary_func_tmpl_inst)
3534 if (! primary_func_tmpl_inst
3535 || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
3536 || ! primary_template_specialization_p (primary_func_tmpl_inst))
3537 return NULL;
3539 return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
3542 /* Return true iff the function parameter PARAM_DECL was expanded
3543 from the function parameter pack PACK. */
3545 bool
3546 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
3548 if (DECL_ARTIFICIAL (param_decl)
3549 || !function_parameter_pack_p (pack))
3550 return false;
3552 /* The parameter pack and its pack arguments have the same
3553 DECL_PARM_INDEX. */
3554 return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
3557 /* Determine whether ARGS describes a variadic template args list,
3558 i.e., one that is terminated by a template argument pack. */
3560 static bool
3561 template_args_variadic_p (tree args)
3563 int nargs;
3564 tree last_parm;
3566 if (args == NULL_TREE)
3567 return false;
3569 args = INNERMOST_TEMPLATE_ARGS (args);
3570 nargs = TREE_VEC_LENGTH (args);
3572 if (nargs == 0)
3573 return false;
3575 last_parm = TREE_VEC_ELT (args, nargs - 1);
3577 return ARGUMENT_PACK_P (last_parm);
3580 /* Generate a new name for the parameter pack name NAME (an
3581 IDENTIFIER_NODE) that incorporates its */
3583 static tree
3584 make_ith_pack_parameter_name (tree name, int i)
3586 /* Munge the name to include the parameter index. */
3587 #define NUMBUF_LEN 128
3588 char numbuf[NUMBUF_LEN];
3589 char* newname;
3590 int newname_len;
3592 if (name == NULL_TREE)
3593 return name;
3594 snprintf (numbuf, NUMBUF_LEN, "%i", i);
3595 newname_len = IDENTIFIER_LENGTH (name)
3596 + strlen (numbuf) + 2;
3597 newname = (char*)alloca (newname_len);
3598 snprintf (newname, newname_len,
3599 "%s#%i", IDENTIFIER_POINTER (name), i);
3600 return get_identifier (newname);
3603 /* Return true if T is a primary function, class or alias template
3604 specialization, not including the template pattern. */
3606 bool
3607 primary_template_specialization_p (const_tree t)
3609 if (!t)
3610 return false;
3612 if (VAR_OR_FUNCTION_DECL_P (t))
3613 return (DECL_LANG_SPECIFIC (t)
3614 && DECL_USE_TEMPLATE (t)
3615 && DECL_TEMPLATE_INFO (t)
3616 && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t)));
3617 else if (CLASS_TYPE_P (t) && !TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
3618 return (CLASSTYPE_TEMPLATE_INFO (t)
3619 && CLASSTYPE_USE_TEMPLATE (t)
3620 && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)));
3621 else if (alias_template_specialization_p (t, nt_transparent))
3622 return true;
3623 return false;
3626 /* Return true if PARM is a template template parameter. */
3628 bool
3629 template_template_parameter_p (const_tree parm)
3631 return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
3634 /* Return true iff PARM is a DECL representing a type template
3635 parameter. */
3637 bool
3638 template_type_parameter_p (const_tree parm)
3640 return (parm
3641 && (TREE_CODE (parm) == TYPE_DECL
3642 || TREE_CODE (parm) == TEMPLATE_DECL)
3643 && DECL_TEMPLATE_PARM_P (parm));
3646 /* Return the template parameters of T if T is a
3647 primary template instantiation, NULL otherwise. */
3649 tree
3650 get_primary_template_innermost_parameters (const_tree t)
3652 tree parms = NULL, template_info = NULL;
3654 if ((template_info = get_template_info (t))
3655 && primary_template_specialization_p (t))
3656 parms = INNERMOST_TEMPLATE_PARMS
3657 (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
3659 return parms;
3662 /* Returns the template arguments of T if T is a template instantiation,
3663 NULL otherwise. */
3665 tree
3666 get_template_innermost_arguments (const_tree t)
3668 tree args = NULL, template_info = NULL;
3670 if ((template_info = get_template_info (t))
3671 && TI_ARGS (template_info))
3672 args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
3674 return args;
3677 /* Return the argument pack elements of T if T is a template argument pack,
3678 NULL otherwise. */
3680 tree
3681 get_template_argument_pack_elems (const_tree t)
3683 if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
3684 && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
3685 return NULL;
3687 return ARGUMENT_PACK_ARGS (t);
3690 /* In an ARGUMENT_PACK_SELECT, the actual underlying argument that the
3691 ARGUMENT_PACK_SELECT represents. */
3693 static tree
3694 argument_pack_select_arg (tree t)
3696 tree args = ARGUMENT_PACK_ARGS (ARGUMENT_PACK_SELECT_FROM_PACK (t));
3697 tree arg = TREE_VEC_ELT (args, ARGUMENT_PACK_SELECT_INDEX (t));
3699 /* If the selected argument is an expansion E, that most likely means we were
3700 called from gen_elem_of_pack_expansion_instantiation during the
3701 substituting of an argument pack (of which the Ith element is a pack
3702 expansion, where I is ARGUMENT_PACK_SELECT_INDEX) into a pack expansion.
3703 In this case, the Ith element resulting from this substituting is going to
3704 be a pack expansion, which pattern is the pattern of E. Let's return the
3705 pattern of E, and gen_elem_of_pack_expansion_instantiation will build the
3706 resulting pack expansion from it. */
3707 if (PACK_EXPANSION_P (arg))
3709 /* Make sure we aren't throwing away arg info. */
3710 gcc_assert (!PACK_EXPANSION_EXTRA_ARGS (arg));
3711 arg = PACK_EXPANSION_PATTERN (arg);
3714 return arg;
3717 /* Return a modification of ARGS that's suitable for preserving inside a hash
3718 table. In particular, this replaces each ARGUMENT_PACK_SELECT with its
3719 underlying argument. ARGS is copied (upon modification) iff COW_P. */
3721 static tree
3722 preserve_args (tree args, bool cow_p = true)
3724 if (!args)
3725 return NULL_TREE;
3727 for (int i = 0, len = TREE_VEC_LENGTH (args); i < len; ++i)
3729 tree t = TREE_VEC_ELT (args, i);
3730 tree r;
3731 if (!t)
3732 r = NULL_TREE;
3733 else if (TREE_CODE (t) == ARGUMENT_PACK_SELECT)
3734 r = argument_pack_select_arg (t);
3735 else if (TREE_CODE (t) == TREE_VEC)
3736 r = preserve_args (t, cow_p);
3737 else
3738 r = t;
3739 if (r != t)
3741 if (cow_p)
3743 args = copy_template_args (args);
3744 cow_p = false;
3746 TREE_VEC_ELT (args, i) = r;
3750 return args;
3753 /* True iff FN is a function representing a built-in variadic parameter
3754 pack. */
3756 bool
3757 builtin_pack_fn_p (tree fn)
3759 if (!fn
3760 || TREE_CODE (fn) != FUNCTION_DECL
3761 || !DECL_IS_UNDECLARED_BUILTIN (fn))
3762 return false;
3764 if (id_equal (DECL_NAME (fn), "__integer_pack"))
3765 return true;
3767 return false;
3770 /* True iff CALL is a call to a function representing a built-in variadic
3771 parameter pack. */
3773 static bool
3774 builtin_pack_call_p (tree call)
3776 if (TREE_CODE (call) != CALL_EXPR)
3777 return false;
3778 return builtin_pack_fn_p (CALL_EXPR_FN (call));
3781 /* Return a TREE_VEC for the expansion of __integer_pack(HI). */
3783 static tree
3784 expand_integer_pack (tree call, tree args, tsubst_flags_t complain,
3785 tree in_decl)
3787 tree ohi = CALL_EXPR_ARG (call, 0);
3788 tree hi = tsubst_expr (ohi, args, complain, in_decl);
3790 if (instantiation_dependent_expression_p (hi))
3792 if (hi != ohi)
3794 call = copy_node (call);
3795 CALL_EXPR_ARG (call, 0) = hi;
3797 tree ex = make_pack_expansion (call, complain);
3798 tree vec = make_tree_vec (1);
3799 TREE_VEC_ELT (vec, 0) = ex;
3800 return vec;
3802 else
3804 hi = instantiate_non_dependent_expr (hi, complain);
3805 hi = cxx_constant_value (hi, complain);
3806 int len = valid_constant_size_p (hi) ? tree_to_shwi (hi) : -1;
3808 /* Calculate the largest value of len that won't make the size of the vec
3809 overflow an int. The compiler will exceed resource limits long before
3810 this, but it seems a decent place to diagnose. */
3811 int max = ((INT_MAX - sizeof (tree_vec)) / sizeof (tree)) + 1;
3813 if (len < 0 || len > max)
3815 if ((complain & tf_error)
3816 && hi != error_mark_node)
3817 error ("argument to %<__integer_pack%> must be between 0 and %d",
3818 max);
3819 return error_mark_node;
3822 tree vec = make_tree_vec (len);
3824 for (int i = 0; i < len; ++i)
3825 TREE_VEC_ELT (vec, i) = size_int (i);
3827 return vec;
3831 /* Return a TREE_VEC for the expansion of built-in template parameter pack
3832 CALL. */
3834 static tree
3835 expand_builtin_pack_call (tree call, tree args, tsubst_flags_t complain,
3836 tree in_decl)
3838 if (!builtin_pack_call_p (call))
3839 return NULL_TREE;
3841 tree fn = CALL_EXPR_FN (call);
3843 if (id_equal (DECL_NAME (fn), "__integer_pack"))
3844 return expand_integer_pack (call, args, complain, in_decl);
3846 return NULL_TREE;
3849 /* Return true if the tree T has the extra args mechanism for
3850 avoiding partial instantiation. */
3852 static bool
3853 has_extra_args_mechanism_p (const_tree t)
3855 return (PACK_EXPANSION_P (t) /* PACK_EXPANSION_EXTRA_ARGS */
3856 || TREE_CODE (t) == REQUIRES_EXPR /* REQUIRES_EXPR_EXTRA_ARGS */
3857 || (TREE_CODE (t) == IF_STMT
3858 && IF_STMT_CONSTEXPR_P (t))); /* IF_STMT_EXTRA_ARGS */
3861 /* Structure used to track the progress of find_parameter_packs_r. */
3862 struct find_parameter_pack_data
3864 /* TREE_LIST that will contain all of the parameter packs found by
3865 the traversal. */
3866 tree* parameter_packs;
3868 /* Set of AST nodes that have been visited by the traversal. */
3869 hash_set<tree> *visited;
3871 /* True iff we're making a type pack expansion. */
3872 bool type_pack_expansion_p;
3874 /* True iff we found a subtree that has the extra args mechanism. */
3875 bool found_extra_args_tree_p = false;
3878 /* Identifies all of the argument packs that occur in a template
3879 argument and appends them to the TREE_LIST inside DATA, which is a
3880 find_parameter_pack_data structure. This is a subroutine of
3881 make_pack_expansion and uses_parameter_packs. */
3882 static tree
3883 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
3885 tree t = *tp;
3886 struct find_parameter_pack_data* ppd =
3887 (struct find_parameter_pack_data*)data;
3888 bool parameter_pack_p = false;
3890 #define WALK_SUBTREE(NODE) \
3891 cp_walk_tree (&(NODE), &find_parameter_packs_r, \
3892 ppd, ppd->visited) \
3894 /* Don't look through typedefs; we are interested in whether a
3895 parameter pack is actually written in the expression/type we're
3896 looking at, not the target type. */
3897 if (TYPE_P (t) && typedef_variant_p (t))
3899 /* But do look at arguments for an alias template. */
3900 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
3901 cp_walk_tree (&TI_ARGS (tinfo),
3902 &find_parameter_packs_r,
3903 ppd, ppd->visited);
3904 *walk_subtrees = 0;
3905 return NULL_TREE;
3908 /* Identify whether this is a parameter pack or not. */
3909 switch (TREE_CODE (t))
3911 case TEMPLATE_PARM_INDEX:
3912 if (TEMPLATE_PARM_PARAMETER_PACK (t))
3913 parameter_pack_p = true;
3914 break;
3916 case TEMPLATE_TYPE_PARM:
3917 t = TYPE_MAIN_VARIANT (t);
3918 /* FALLTHRU */
3919 case TEMPLATE_TEMPLATE_PARM:
3920 /* If the placeholder appears in the decl-specifier-seq of a function
3921 parameter pack (14.6.3), or the type-specifier-seq of a type-id that
3922 is a pack expansion, the invented template parameter is a template
3923 parameter pack. */
3924 if (ppd->type_pack_expansion_p && is_auto (t))
3925 TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
3926 if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3927 parameter_pack_p = true;
3928 break;
3930 case FIELD_DECL:
3931 case PARM_DECL:
3932 if (DECL_PACK_P (t))
3934 /* We don't want to walk into the type of a PARM_DECL,
3935 because we don't want to see the type parameter pack. */
3936 *walk_subtrees = 0;
3937 parameter_pack_p = true;
3939 break;
3941 case VAR_DECL:
3942 if (DECL_PACK_P (t))
3944 /* We don't want to walk into the type of a variadic capture proxy,
3945 because we don't want to see the type parameter pack. */
3946 *walk_subtrees = 0;
3947 parameter_pack_p = true;
3949 else if (variable_template_specialization_p (t))
3951 cp_walk_tree (&DECL_TI_ARGS (t),
3952 find_parameter_packs_r,
3953 ppd, ppd->visited);
3954 *walk_subtrees = 0;
3956 break;
3958 case CALL_EXPR:
3959 if (builtin_pack_call_p (t))
3960 parameter_pack_p = true;
3961 break;
3963 case BASES:
3964 parameter_pack_p = true;
3965 break;
3966 default:
3967 /* Not a parameter pack. */
3968 break;
3971 if (parameter_pack_p)
3973 /* Add this parameter pack to the list. */
3974 *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
3977 if (has_extra_args_mechanism_p (t) && !PACK_EXPANSION_P (t))
3978 ppd->found_extra_args_tree_p = true;
3980 if (TYPE_P (t))
3981 cp_walk_tree (&TYPE_CONTEXT (t),
3982 &find_parameter_packs_r, ppd, ppd->visited);
3984 /* This switch statement will return immediately if we don't find a
3985 parameter pack. ??? Should some of these be in cp_walk_subtrees? */
3986 switch (TREE_CODE (t))
3988 case BOUND_TEMPLATE_TEMPLATE_PARM:
3989 /* Check the template itself. */
3990 cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)),
3991 &find_parameter_packs_r, ppd, ppd->visited);
3992 return NULL_TREE;
3994 case DECL_EXPR:
3996 tree decl = DECL_EXPR_DECL (t);
3997 /* Ignore the declaration of a capture proxy for a parameter pack. */
3998 if (is_capture_proxy (decl))
3999 *walk_subtrees = 0;
4000 if (is_typedef_decl (decl))
4001 /* Since we stop at typedefs above, we need to look through them at
4002 the point of the DECL_EXPR. */
4003 cp_walk_tree (&DECL_ORIGINAL_TYPE (decl),
4004 &find_parameter_packs_r, ppd, ppd->visited);
4005 return NULL_TREE;
4008 case TEMPLATE_DECL:
4009 if (!DECL_TEMPLATE_TEMPLATE_PARM_P (t))
4010 return NULL_TREE;
4011 cp_walk_tree (&TREE_TYPE (t),
4012 &find_parameter_packs_r, ppd, ppd->visited);
4013 return NULL_TREE;
4015 case TYPE_PACK_EXPANSION:
4016 case EXPR_PACK_EXPANSION:
4017 *walk_subtrees = 0;
4018 return NULL_TREE;
4020 case INTEGER_TYPE:
4021 cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r,
4022 ppd, ppd->visited);
4023 *walk_subtrees = 0;
4024 return NULL_TREE;
4026 case IDENTIFIER_NODE:
4027 cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd,
4028 ppd->visited);
4029 *walk_subtrees = 0;
4030 return NULL_TREE;
4032 case LAMBDA_EXPR:
4034 /* Since we defer implicit capture, look in the parms and body. */
4035 tree fn = lambda_function (t);
4036 cp_walk_tree (&TREE_TYPE (fn), &find_parameter_packs_r, ppd,
4037 ppd->visited);
4038 cp_walk_tree (&DECL_SAVED_TREE (fn), &find_parameter_packs_r, ppd,
4039 ppd->visited);
4040 return NULL_TREE;
4043 case DECLTYPE_TYPE:
4045 /* When traversing a DECLTYPE_TYPE_EXPR, we need to set
4046 type_pack_expansion_p to false so that any placeholders
4047 within the expression don't get marked as parameter packs. */
4048 bool type_pack_expansion_p = ppd->type_pack_expansion_p;
4049 ppd->type_pack_expansion_p = false;
4050 cp_walk_tree (&DECLTYPE_TYPE_EXPR (t), &find_parameter_packs_r,
4051 ppd, ppd->visited);
4052 ppd->type_pack_expansion_p = type_pack_expansion_p;
4053 *walk_subtrees = 0;
4054 return NULL_TREE;
4057 case IF_STMT:
4058 cp_walk_tree (&IF_COND (t), &find_parameter_packs_r,
4059 ppd, ppd->visited);
4060 cp_walk_tree (&THEN_CLAUSE (t), &find_parameter_packs_r,
4061 ppd, ppd->visited);
4062 cp_walk_tree (&ELSE_CLAUSE (t), &find_parameter_packs_r,
4063 ppd, ppd->visited);
4064 /* Don't walk into IF_STMT_EXTRA_ARGS. */
4065 *walk_subtrees = 0;
4066 return NULL_TREE;
4068 case TAG_DEFN:
4069 t = TREE_TYPE (t);
4070 if (CLASS_TYPE_P (t))
4072 /* Local class, need to look through the whole definition.
4073 TYPE_BINFO might be unset for a partial instantiation. */
4074 if (TYPE_BINFO (t))
4075 for (tree bb : BINFO_BASE_BINFOS (TYPE_BINFO (t)))
4076 cp_walk_tree (&BINFO_TYPE (bb), &find_parameter_packs_r,
4077 ppd, ppd->visited);
4079 else
4080 /* Enum, look at the values. */
4081 for (tree l = TYPE_VALUES (t); l; l = TREE_CHAIN (l))
4082 cp_walk_tree (&DECL_INITIAL (TREE_VALUE (l)),
4083 &find_parameter_packs_r,
4084 ppd, ppd->visited);
4085 return NULL_TREE;
4087 case FUNCTION_TYPE:
4088 case METHOD_TYPE:
4089 WALK_SUBTREE (TYPE_RAISES_EXCEPTIONS (t));
4090 break;
4092 default:
4093 return NULL_TREE;
4096 #undef WALK_SUBTREE
4098 return NULL_TREE;
4101 /* Determines if the expression or type T uses any parameter packs. */
4102 tree
4103 uses_parameter_packs (tree t)
4105 tree parameter_packs = NULL_TREE;
4106 struct find_parameter_pack_data ppd;
4107 ppd.parameter_packs = &parameter_packs;
4108 ppd.visited = new hash_set<tree>;
4109 ppd.type_pack_expansion_p = false;
4110 cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4111 delete ppd.visited;
4112 return parameter_packs;
4115 /* Turn ARG, which may be an expression, type, or a TREE_LIST
4116 representation a base-class initializer into a parameter pack
4117 expansion. If all goes well, the resulting node will be an
4118 EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
4119 respectively. */
4120 tree
4121 make_pack_expansion (tree arg, tsubst_flags_t complain)
4123 tree result;
4124 tree parameter_packs = NULL_TREE;
4125 bool for_types = false;
4126 struct find_parameter_pack_data ppd;
4128 if (!arg || arg == error_mark_node)
4129 return arg;
4131 if (TREE_CODE (arg) == TREE_LIST && TREE_PURPOSE (arg))
4133 /* A TREE_LIST with a non-null TREE_PURPOSE is for a base
4134 class initializer. In this case, the TREE_PURPOSE will be a
4135 _TYPE node (representing the base class expansion we're
4136 initializing) and the TREE_VALUE will be a TREE_LIST
4137 containing the initialization arguments.
4139 The resulting expansion looks somewhat different from most
4140 expansions. Rather than returning just one _EXPANSION, we
4141 return a TREE_LIST whose TREE_PURPOSE is a
4142 TYPE_PACK_EXPANSION containing the bases that will be
4143 initialized. The TREE_VALUE will be identical to the
4144 original TREE_VALUE, which is a list of arguments that will
4145 be passed to each base. We do not introduce any new pack
4146 expansion nodes into the TREE_VALUE (although it is possible
4147 that some already exist), because the TREE_PURPOSE and
4148 TREE_VALUE all need to be expanded together with the same
4149 _EXPANSION node. Note that the TYPE_PACK_EXPANSION in the
4150 resulting TREE_PURPOSE will mention the parameter packs in
4151 both the bases and the arguments to the bases. */
4152 tree purpose;
4153 tree value;
4154 tree parameter_packs = NULL_TREE;
4156 /* Determine which parameter packs will be used by the base
4157 class expansion. */
4158 ppd.visited = new hash_set<tree>;
4159 ppd.parameter_packs = &parameter_packs;
4160 ppd.type_pack_expansion_p = false;
4161 gcc_assert (TYPE_P (TREE_PURPOSE (arg)));
4162 cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r,
4163 &ppd, ppd.visited);
4165 if (parameter_packs == NULL_TREE)
4167 if (complain & tf_error)
4168 error ("base initializer expansion %qT contains no parameter packs",
4169 arg);
4170 delete ppd.visited;
4171 return error_mark_node;
4174 if (TREE_VALUE (arg) != void_type_node)
4176 /* Collect the sets of parameter packs used in each of the
4177 initialization arguments. */
4178 for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
4180 /* Determine which parameter packs will be expanded in this
4181 argument. */
4182 cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r,
4183 &ppd, ppd.visited);
4187 delete ppd.visited;
4189 /* Create the pack expansion type for the base type. */
4190 purpose = cxx_make_type (TYPE_PACK_EXPANSION);
4191 PACK_EXPANSION_PATTERN (purpose) = TREE_PURPOSE (arg);
4192 PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
4193 PACK_EXPANSION_LOCAL_P (purpose) = at_function_scope_p ();
4195 /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
4196 they will rarely be compared to anything. */
4197 SET_TYPE_STRUCTURAL_EQUALITY (purpose);
4199 return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
4202 if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
4203 for_types = true;
4205 /* Build the PACK_EXPANSION_* node. */
4206 result = for_types
4207 ? cxx_make_type (TYPE_PACK_EXPANSION)
4208 : make_node (EXPR_PACK_EXPANSION);
4209 PACK_EXPANSION_PATTERN (result) = arg;
4210 if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
4212 /* Propagate type and const-expression information. */
4213 TREE_TYPE (result) = TREE_TYPE (arg);
4214 TREE_CONSTANT (result) = TREE_CONSTANT (arg);
4215 /* Mark this read now, since the expansion might be length 0. */
4216 mark_exp_read (arg);
4218 else
4219 /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
4220 they will rarely be compared to anything. */
4221 SET_TYPE_STRUCTURAL_EQUALITY (result);
4223 /* Determine which parameter packs will be expanded. */
4224 ppd.parameter_packs = &parameter_packs;
4225 ppd.visited = new hash_set<tree>;
4226 ppd.type_pack_expansion_p = TYPE_P (arg);
4227 cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
4228 delete ppd.visited;
4230 /* Make sure we found some parameter packs. */
4231 if (parameter_packs == NULL_TREE)
4233 if (complain & tf_error)
4235 if (TYPE_P (arg))
4236 error ("expansion pattern %qT contains no parameter packs", arg);
4237 else
4238 error ("expansion pattern %qE contains no parameter packs", arg);
4240 return error_mark_node;
4242 PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
4244 PACK_EXPANSION_LOCAL_P (result) = at_function_scope_p ();
4245 if (ppd.found_extra_args_tree_p)
4246 /* If the pattern of this pack expansion contains a subtree that has
4247 the extra args mechanism for avoiding partial instantiation, then
4248 force this pack expansion to also use extra args. Otherwise
4249 partial instantiation of this pack expansion may not lower the
4250 level of some parameter packs within the pattern, which would
4251 confuse tsubst_pack_expansion later (PR101764). */
4252 PACK_EXPANSION_FORCE_EXTRA_ARGS_P (result) = true;
4254 return result;
4257 /* Checks T for any "bare" parameter packs, which have not yet been
4258 expanded, and issues an error if any are found. This operation can
4259 only be done on full expressions or types (e.g., an expression
4260 statement, "if" condition, etc.), because we could have expressions like:
4262 foo(f(g(h(args)))...)
4264 where "args" is a parameter pack. check_for_bare_parameter_packs
4265 should not be called for the subexpressions args, h(args),
4266 g(h(args)), or f(g(h(args))), because we would produce erroneous
4267 error messages.
4269 Returns TRUE and emits an error if there were bare parameter packs,
4270 returns FALSE otherwise. */
4271 bool
4272 check_for_bare_parameter_packs (tree t, location_t loc /* = UNKNOWN_LOCATION */)
4274 tree parameter_packs = NULL_TREE;
4275 struct find_parameter_pack_data ppd;
4277 if (!processing_template_decl || !t || t == error_mark_node)
4278 return false;
4280 if (TREE_CODE (t) == TYPE_DECL)
4281 t = TREE_TYPE (t);
4283 ppd.parameter_packs = &parameter_packs;
4284 ppd.visited = new hash_set<tree>;
4285 ppd.type_pack_expansion_p = false;
4286 cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4287 delete ppd.visited;
4289 if (!parameter_packs)
4290 return false;
4292 if (loc == UNKNOWN_LOCATION)
4293 loc = cp_expr_loc_or_input_loc (t);
4295 /* It's OK for a lambda to have an unexpanded parameter pack from the
4296 containing context, but do complain about unexpanded capture packs. */
4297 tree lam = current_lambda_expr ();
4298 if (lam)
4299 lam = TREE_TYPE (lam);
4301 if (lam && lam != current_class_type)
4303 /* We're in a lambda, but it isn't the innermost class.
4304 This should work, but currently doesn't. */
4305 sorry_at (loc, "unexpanded parameter pack in local class in lambda");
4306 return true;
4309 if (lam && CLASSTYPE_TEMPLATE_INFO (lam))
4310 for (; parameter_packs;
4311 parameter_packs = TREE_CHAIN (parameter_packs))
4313 tree pack = TREE_VALUE (parameter_packs);
4314 if (is_capture_proxy (pack)
4315 || (TREE_CODE (pack) == PARM_DECL
4316 && DECL_CONTEXT (DECL_CONTEXT (pack)) == lam))
4317 break;
4320 if (parameter_packs)
4322 error_at (loc, "parameter packs not expanded with %<...%>:");
4323 while (parameter_packs)
4325 tree pack = TREE_VALUE (parameter_packs);
4326 tree name = NULL_TREE;
4328 if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
4329 || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
4330 name = TYPE_NAME (pack);
4331 else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
4332 name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
4333 else if (TREE_CODE (pack) == CALL_EXPR)
4334 name = DECL_NAME (CALL_EXPR_FN (pack));
4335 else
4336 name = DECL_NAME (pack);
4338 if (name)
4339 inform (loc, " %qD", name);
4340 else
4341 inform (loc, " %s", "<anonymous>");
4343 parameter_packs = TREE_CHAIN (parameter_packs);
4346 return true;
4349 return false;
4352 /* Expand any parameter packs that occur in the template arguments in
4353 ARGS. */
4354 tree
4355 expand_template_argument_pack (tree args)
4357 if (args == error_mark_node)
4358 return error_mark_node;
4360 tree result_args = NULL_TREE;
4361 int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
4362 int num_result_args = -1;
4363 int non_default_args_count = -1;
4365 /* First, determine if we need to expand anything, and the number of
4366 slots we'll need. */
4367 for (in_arg = 0; in_arg < nargs; ++in_arg)
4369 tree arg = TREE_VEC_ELT (args, in_arg);
4370 if (arg == NULL_TREE)
4371 return args;
4372 if (ARGUMENT_PACK_P (arg))
4374 int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
4375 if (num_result_args < 0)
4376 num_result_args = in_arg + num_packed;
4377 else
4378 num_result_args += num_packed;
4380 else
4382 if (num_result_args >= 0)
4383 num_result_args++;
4387 /* If no expansion is necessary, we're done. */
4388 if (num_result_args < 0)
4389 return args;
4391 /* Expand arguments. */
4392 result_args = make_tree_vec (num_result_args);
4393 if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
4394 non_default_args_count =
4395 GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
4396 for (in_arg = 0; in_arg < nargs; ++in_arg)
4398 tree arg = TREE_VEC_ELT (args, in_arg);
4399 if (ARGUMENT_PACK_P (arg))
4401 tree packed = ARGUMENT_PACK_ARGS (arg);
4402 int i, num_packed = TREE_VEC_LENGTH (packed);
4403 for (i = 0; i < num_packed; ++i, ++out_arg)
4404 TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
4405 if (non_default_args_count > 0)
4406 non_default_args_count += num_packed - 1;
4408 else
4410 TREE_VEC_ELT (result_args, out_arg) = arg;
4411 ++out_arg;
4414 if (non_default_args_count >= 0)
4415 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
4416 return result_args;
4419 /* Checks if DECL shadows a template parameter.
4421 [temp.local]: A template-parameter shall not be redeclared within its
4422 scope (including nested scopes).
4424 Emits an error and returns TRUE if the DECL shadows a parameter,
4425 returns FALSE otherwise. */
4427 bool
4428 check_template_shadow (tree decl)
4430 tree olddecl;
4432 /* If we're not in a template, we can't possibly shadow a template
4433 parameter. */
4434 if (!current_template_parms)
4435 return true;
4437 /* Figure out what we're shadowing. */
4438 decl = OVL_FIRST (decl);
4439 olddecl = innermost_non_namespace_value (DECL_NAME (decl));
4441 /* If there's no previous binding for this name, we're not shadowing
4442 anything, let alone a template parameter. */
4443 if (!olddecl)
4444 return true;
4446 /* If we're not shadowing a template parameter, we're done. Note
4447 that OLDDECL might be an OVERLOAD (or perhaps even an
4448 ERROR_MARK), so we can't just blithely assume it to be a _DECL
4449 node. */
4450 if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
4451 return true;
4453 /* We check for decl != olddecl to avoid bogus errors for using a
4454 name inside a class. We check TPFI to avoid duplicate errors for
4455 inline member templates. */
4456 if (decl == olddecl
4457 || (DECL_TEMPLATE_PARM_P (decl)
4458 && TEMPLATE_PARMS_FOR_INLINE (current_template_parms)))
4459 return true;
4461 /* Don't complain about the injected class name, as we've already
4462 complained about the class itself. */
4463 if (DECL_SELF_REFERENCE_P (decl))
4464 return false;
4466 if (DECL_TEMPLATE_PARM_P (decl))
4467 error ("declaration of template parameter %q+D shadows "
4468 "template parameter", decl);
4469 else
4470 error ("declaration of %q+#D shadows template parameter", decl);
4471 inform (DECL_SOURCE_LOCATION (olddecl),
4472 "template parameter %qD declared here", olddecl);
4473 return false;
4476 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
4477 ORIG_LEVEL, DECL, and TYPE. */
4479 static tree
4480 build_template_parm_index (int index,
4481 int level,
4482 int orig_level,
4483 tree decl,
4484 tree type)
4486 tree t = make_node (TEMPLATE_PARM_INDEX);
4487 TEMPLATE_PARM_IDX (t) = index;
4488 TEMPLATE_PARM_LEVEL (t) = level;
4489 TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
4490 TEMPLATE_PARM_DECL (t) = decl;
4491 TREE_TYPE (t) = type;
4492 TREE_CONSTANT (t) = TREE_CONSTANT (decl);
4493 TREE_READONLY (t) = TREE_READONLY (decl);
4495 return t;
4498 struct ctp_hasher : ggc_ptr_hash<tree_node>
4500 static hashval_t hash (tree t)
4502 ++comparing_specializations;
4503 tree_code code = TREE_CODE (t);
4504 hashval_t val = iterative_hash_object (code, 0);
4505 val = iterative_hash_object (TEMPLATE_TYPE_LEVEL (t), val);
4506 val = iterative_hash_object (TEMPLATE_TYPE_IDX (t), val);
4507 if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
4508 val = iterative_hash_template_arg (CLASS_PLACEHOLDER_TEMPLATE (t), val);
4509 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
4510 val = iterative_hash_template_arg (TYPE_TI_ARGS (t), val);
4511 --comparing_specializations;
4512 return val;
4515 static bool equal (tree t, tree u)
4517 ++comparing_specializations;
4518 bool eq = comptypes (t, u, COMPARE_STRUCTURAL);
4519 --comparing_specializations;
4520 return eq;
4524 static GTY (()) hash_table<ctp_hasher> *ctp_table;
4526 /* Find the canonical type parameter for the given template type
4527 parameter. Returns the canonical type parameter, which may be TYPE
4528 if no such parameter existed. */
4530 tree
4531 canonical_type_parameter (tree type)
4533 if (ctp_table == NULL)
4534 ctp_table = hash_table<ctp_hasher>::create_ggc (61);
4536 tree& slot = *ctp_table->find_slot (type, INSERT);
4537 if (slot == NULL_TREE)
4538 slot = type;
4539 return slot;
4542 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
4543 TEMPLATE_PARM_LEVEL has been decreased by LEVELS. If such a
4544 TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
4545 new one is created. */
4547 static tree
4548 reduce_template_parm_level (tree index, tree type, int levels, tree args,
4549 tsubst_flags_t complain)
4551 if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
4552 || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
4553 != TEMPLATE_PARM_LEVEL (index) - levels)
4554 || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
4556 tree orig_decl = TEMPLATE_PARM_DECL (index);
4558 tree decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
4559 TREE_CODE (orig_decl), DECL_NAME (orig_decl),
4560 type);
4561 TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
4562 TREE_READONLY (decl) = TREE_READONLY (orig_decl);
4563 DECL_VIRTUAL_P (decl) = DECL_VIRTUAL_P (orig_decl);
4564 DECL_ARTIFICIAL (decl) = 1;
4565 SET_DECL_TEMPLATE_PARM_P (decl);
4567 tree tpi = build_template_parm_index (TEMPLATE_PARM_IDX (index),
4568 TEMPLATE_PARM_LEVEL (index) - levels,
4569 TEMPLATE_PARM_ORIG_LEVEL (index),
4570 decl, type);
4571 TEMPLATE_PARM_DESCENDANTS (index) = tpi;
4572 TEMPLATE_PARM_PARAMETER_PACK (tpi)
4573 = TEMPLATE_PARM_PARAMETER_PACK (index);
4575 /* Template template parameters need this. */
4576 tree inner = decl;
4577 if (TREE_CODE (decl) == TEMPLATE_DECL)
4579 inner = build_lang_decl_loc (DECL_SOURCE_LOCATION (decl),
4580 TYPE_DECL, DECL_NAME (decl), type);
4581 DECL_TEMPLATE_RESULT (decl) = inner;
4582 DECL_ARTIFICIAL (inner) = true;
4583 tree parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (orig_decl),
4584 args, complain);
4585 DECL_TEMPLATE_PARMS (decl) = parms;
4586 tree orig_inner = DECL_TEMPLATE_RESULT (orig_decl);
4587 DECL_TEMPLATE_INFO (inner)
4588 = build_template_info (DECL_TI_TEMPLATE (orig_inner),
4589 template_parms_to_args (parms));
4592 /* Attach the TPI to the decl. */
4593 if (TREE_CODE (inner) == TYPE_DECL)
4594 TEMPLATE_TYPE_PARM_INDEX (type) = tpi;
4595 else
4596 DECL_INITIAL (decl) = tpi;
4599 return TEMPLATE_PARM_DESCENDANTS (index);
4602 /* Process information from new template parameter PARM and append it
4603 to the LIST being built. This new parameter is a non-type
4604 parameter iff IS_NON_TYPE is true. This new parameter is a
4605 parameter pack iff IS_PARAMETER_PACK is true. The location of PARM
4606 is in PARM_LOC. */
4608 tree
4609 process_template_parm (tree list, location_t parm_loc, tree parm,
4610 bool is_non_type, bool is_parameter_pack)
4612 gcc_assert (TREE_CODE (parm) == TREE_LIST);
4613 tree prev = NULL_TREE;
4614 int idx = 0;
4616 if (list)
4618 prev = tree_last (list);
4620 tree p = TREE_VALUE (prev);
4621 if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
4622 idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
4623 else if (TREE_CODE (p) == PARM_DECL)
4624 idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
4626 ++idx;
4629 tree decl = NULL_TREE;
4630 tree defval = TREE_PURPOSE (parm);
4631 tree constr = TREE_TYPE (parm);
4633 if (is_non_type)
4635 parm = TREE_VALUE (parm);
4637 SET_DECL_TEMPLATE_PARM_P (parm);
4639 if (TREE_TYPE (parm) != error_mark_node)
4641 /* [temp.param]
4643 The top-level cv-qualifiers on the template-parameter are
4644 ignored when determining its type. */
4645 TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
4646 if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
4647 TREE_TYPE (parm) = error_mark_node;
4648 else if (uses_parameter_packs (TREE_TYPE (parm))
4649 && !is_parameter_pack
4650 /* If we're in a nested template parameter list, the template
4651 template parameter could be a parameter pack. */
4652 && processing_template_parmlist == 1)
4654 /* This template parameter is not a parameter pack, but it
4655 should be. Complain about "bare" parameter packs. */
4656 check_for_bare_parameter_packs (TREE_TYPE (parm));
4658 /* Recover by calling this a parameter pack. */
4659 is_parameter_pack = true;
4663 /* A template parameter is not modifiable. */
4664 TREE_CONSTANT (parm) = 1;
4665 TREE_READONLY (parm) = 1;
4666 decl = build_decl (parm_loc,
4667 CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
4668 TREE_CONSTANT (decl) = 1;
4669 TREE_READONLY (decl) = 1;
4670 DECL_INITIAL (parm) = DECL_INITIAL (decl)
4671 = build_template_parm_index (idx, current_template_depth,
4672 current_template_depth,
4673 decl, TREE_TYPE (parm));
4675 TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))
4676 = is_parameter_pack;
4678 else
4680 tree t;
4681 parm = TREE_VALUE (TREE_VALUE (parm));
4683 if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
4685 t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
4686 /* This is for distinguishing between real templates and template
4687 template parameters */
4688 TREE_TYPE (parm) = t;
4690 /* any_template_parm_r expects to be able to get the targs of a
4691 DECL_TEMPLATE_RESULT. */
4692 tree result = DECL_TEMPLATE_RESULT (parm);
4693 TREE_TYPE (result) = t;
4694 tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (parm));
4695 tree tinfo = build_template_info (parm, args);
4696 retrofit_lang_decl (result);
4697 DECL_TEMPLATE_INFO (result) = tinfo;
4699 decl = parm;
4701 else
4703 t = cxx_make_type (TEMPLATE_TYPE_PARM);
4704 /* parm is either IDENTIFIER_NODE or NULL_TREE. */
4705 decl = build_decl (parm_loc,
4706 TYPE_DECL, parm, t);
4709 TYPE_NAME (t) = decl;
4710 TYPE_STUB_DECL (t) = decl;
4711 parm = decl;
4712 TEMPLATE_TYPE_PARM_INDEX (t)
4713 = build_template_parm_index (idx, current_template_depth,
4714 current_template_depth,
4715 decl, TREE_TYPE (parm));
4716 TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
4717 TYPE_CANONICAL (t) = canonical_type_parameter (t);
4719 DECL_ARTIFICIAL (decl) = 1;
4720 SET_DECL_TEMPLATE_PARM_P (decl);
4722 if (TREE_CODE (parm) == TEMPLATE_DECL
4723 && !uses_outer_template_parms (parm))
4724 TEMPLATE_TEMPLATE_PARM_SIMPLE_P (TREE_TYPE (parm)) = true;
4726 /* Build requirements for the type/template parameter.
4727 This must be done after SET_DECL_TEMPLATE_PARM_P or
4728 process_template_parm could fail. */
4729 tree reqs = finish_shorthand_constraint (parm, constr);
4731 decl = pushdecl (decl);
4732 if (!is_non_type)
4733 parm = decl;
4735 /* Build the parameter node linking the parameter declaration,
4736 its default argument (if any), and its constraints (if any). */
4737 parm = build_tree_list (defval, parm);
4738 TEMPLATE_PARM_CONSTRAINTS (parm) = reqs;
4740 if (prev)
4741 TREE_CHAIN (prev) = parm;
4742 else
4743 list = parm;
4745 return list;
4748 /* The end of a template parameter list has been reached. Process the
4749 tree list into a parameter vector, converting each parameter into a more
4750 useful form. Type parameters are saved as IDENTIFIER_NODEs, and others
4751 as PARM_DECLs. */
4753 tree
4754 end_template_parm_list (tree parms)
4756 tree saved_parmlist = make_tree_vec (list_length (parms));
4758 /* Pop the dummy parameter level and add the real one. We do not
4759 morph the dummy parameter in place, as it might have been
4760 captured by a (nested) template-template-parm. */
4761 current_template_parms = TREE_CHAIN (current_template_parms);
4763 current_template_parms
4764 = tree_cons (size_int (current_template_depth + 1),
4765 saved_parmlist, current_template_parms);
4767 for (unsigned ix = 0; parms; ix++)
4769 tree parm = parms;
4770 parms = TREE_CHAIN (parms);
4771 TREE_CHAIN (parm) = NULL_TREE;
4773 TREE_VEC_ELT (saved_parmlist, ix) = parm;
4776 --processing_template_parmlist;
4778 return saved_parmlist;
4781 // Explicitly indicate the end of the template parameter list. We assume
4782 // that the current template parameters have been constructed and/or
4783 // managed explicitly, as when creating new template template parameters
4784 // from a shorthand constraint.
4785 void
4786 end_template_parm_list ()
4788 --processing_template_parmlist;
4791 /* end_template_decl is called after a template declaration is seen. */
4793 void
4794 end_template_decl (void)
4796 reset_specialization ();
4798 if (! processing_template_decl)
4799 return;
4801 /* This matches the pushlevel in begin_template_parm_list. */
4802 finish_scope ();
4804 --processing_template_decl;
4805 current_template_parms = TREE_CHAIN (current_template_parms);
4808 /* Takes a TEMPLATE_PARM_P or DECL_TEMPLATE_PARM_P node or a TREE_LIST
4809 thereof, and converts it into an argument suitable to be passed to
4810 the type substitution functions. Note that if the TREE_LIST contains
4811 an error_mark node, the returned argument is error_mark_node. */
4813 tree
4814 template_parm_to_arg (tree t)
4816 if (!t)
4817 return NULL_TREE;
4819 if (TREE_CODE (t) == TREE_LIST)
4820 t = TREE_VALUE (t);
4822 if (error_operand_p (t))
4823 return error_mark_node;
4825 if (DECL_P (t) && DECL_TEMPLATE_PARM_P (t))
4827 if (TREE_CODE (t) == TYPE_DECL
4828 || TREE_CODE (t) == TEMPLATE_DECL)
4829 t = TREE_TYPE (t);
4830 else
4831 t = DECL_INITIAL (t);
4834 gcc_assert (TEMPLATE_PARM_P (t));
4836 if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
4837 || TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
4839 if (TEMPLATE_TYPE_PARAMETER_PACK (t))
4841 /* Turn this argument into a TYPE_ARGUMENT_PACK
4842 with a single element, which expands T. */
4843 tree vec = make_tree_vec (1);
4844 if (CHECKING_P)
4845 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4847 TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4849 t = cxx_make_type (TYPE_ARGUMENT_PACK);
4850 ARGUMENT_PACK_ARGS (t) = vec;
4853 else
4855 if (TEMPLATE_PARM_PARAMETER_PACK (t))
4857 /* Turn this argument into a NONTYPE_ARGUMENT_PACK
4858 with a single element, which expands T. */
4859 tree vec = make_tree_vec (1);
4860 if (CHECKING_P)
4861 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4863 t = convert_from_reference (t);
4864 TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4866 t = make_node (NONTYPE_ARGUMENT_PACK);
4867 ARGUMENT_PACK_ARGS (t) = vec;
4869 else
4870 t = convert_from_reference (t);
4872 return t;
4875 /* If T looks like a generic template argument produced by template_parm_to_arg,
4876 return the corresponding template parameter, otherwise return NULL_TREE. */
4878 static tree
4879 template_arg_to_parm (tree t)
4881 if (t == NULL_TREE)
4882 return NULL_TREE;
4884 if (ARGUMENT_PACK_P (t))
4886 tree args = ARGUMENT_PACK_ARGS (t);
4887 if (TREE_VEC_LENGTH (args) == 1
4888 && PACK_EXPANSION_P (TREE_VEC_ELT (args, 0)))
4889 t = PACK_EXPANSION_PATTERN (TREE_VEC_ELT (args, 0));
4892 if (REFERENCE_REF_P (t))
4893 t = TREE_OPERAND (t, 0);
4895 if (TEMPLATE_PARM_P (t))
4896 return t;
4897 else
4898 return NULL_TREE;
4901 /* Given a single level of template parameters (a TREE_VEC), return it
4902 as a set of template arguments. */
4904 tree
4905 template_parms_level_to_args (tree parms)
4907 parms = copy_node (parms);
4908 TREE_TYPE (parms) = NULL_TREE;
4909 for (tree& parm : tree_vec_range (parms))
4910 parm = template_parm_to_arg (parm);
4912 if (CHECKING_P)
4913 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (parms, TREE_VEC_LENGTH (parms));
4915 return parms;
4918 /* Given a set of template parameters, return them as a set of template
4919 arguments. The template parameters are represented as a TREE_VEC, in
4920 the form documented in cp-tree.h for template arguments. */
4922 tree
4923 template_parms_to_args (tree parms)
4925 tree header;
4926 tree args = NULL_TREE;
4927 int length = TMPL_PARMS_DEPTH (parms);
4928 int l = length;
4930 /* If there is only one level of template parameters, we do not
4931 create a TREE_VEC of TREE_VECs. Instead, we return a single
4932 TREE_VEC containing the arguments. */
4933 if (length > 1)
4934 args = make_tree_vec (length);
4936 for (header = parms; header; header = TREE_CHAIN (header))
4938 tree a = template_parms_level_to_args (TREE_VALUE (header));
4940 if (length > 1)
4941 TREE_VEC_ELT (args, --l) = a;
4942 else
4943 args = a;
4946 return args;
4949 /* Within the declaration of a template, return the currently active
4950 template parameters as an argument TREE_VEC. */
4952 static tree
4953 current_template_args (void)
4955 return template_parms_to_args (current_template_parms);
4958 /* Return the fully generic arguments for of TMPL, i.e. what
4959 current_template_args would be while parsing it. */
4961 tree
4962 generic_targs_for (tree tmpl)
4964 if (tmpl == NULL_TREE)
4965 return NULL_TREE;
4966 if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
4967 || DECL_TEMPLATE_SPECIALIZATION (tmpl))
4968 /* DECL_TEMPLATE_RESULT doesn't have the arguments we want. For a template
4969 template parameter, it has no TEMPLATE_INFO; for a partial
4970 specialization, it has the arguments for the primary template, and we
4971 want the arguments for the partial specialization. */;
4972 else if (tree result = DECL_TEMPLATE_RESULT (tmpl))
4973 if (tree ti = get_template_info (result))
4974 return TI_ARGS (ti);
4975 return template_parms_to_args (DECL_TEMPLATE_PARMS (tmpl));
4978 /* Return the template arguments corresponding to the template parameters of
4979 DECL's enclosing scope. When DECL is a member of a partial specialization,
4980 this returns the arguments for the partial specialization as opposed to those
4981 for the primary template, which is the main difference between this function
4982 and simply using e.g. the TYPE_TI_ARGS of DECL's DECL_CONTEXT. */
4984 tree
4985 outer_template_args (const_tree decl)
4987 if (TREE_CODE (decl) == TEMPLATE_DECL)
4988 decl = DECL_TEMPLATE_RESULT (decl);
4989 tree ti = get_template_info (decl);
4990 if (!ti)
4991 return NULL_TREE;
4992 tree args = TI_ARGS (ti);
4993 if (!PRIMARY_TEMPLATE_P (TI_TEMPLATE (ti)))
4994 return args;
4995 if (TMPL_ARGS_DEPTH (args) == 1)
4996 return NULL_TREE;
4997 return strip_innermost_template_args (args, 1);
5000 /* Update the declared TYPE by doing any lookups which were thought to be
5001 dependent, but are not now that we know the SCOPE of the declarator. */
5003 tree
5004 maybe_update_decl_type (tree orig_type, tree scope)
5006 tree type = orig_type;
5008 if (type == NULL_TREE)
5009 return type;
5011 if (TREE_CODE (orig_type) == TYPE_DECL)
5012 type = TREE_TYPE (type);
5014 if (scope && TYPE_P (scope) && dependent_type_p (scope)
5015 && dependent_type_p (type)
5016 /* Don't bother building up the args in this case. */
5017 && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
5019 /* tsubst in the args corresponding to the template parameters,
5020 including auto if present. Most things will be unchanged, but
5021 make_typename_type and tsubst_qualified_id will resolve
5022 TYPENAME_TYPEs and SCOPE_REFs that were previously dependent. */
5023 tree args = current_template_args ();
5024 tree auto_node = type_uses_auto (type);
5025 tree pushed;
5026 if (auto_node)
5028 tree auto_vec = make_tree_vec (1);
5029 TREE_VEC_ELT (auto_vec, 0) = auto_node;
5030 args = add_to_template_args (args, auto_vec);
5032 pushed = push_scope (scope);
5033 type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
5034 if (pushed)
5035 pop_scope (scope);
5038 if (type == error_mark_node)
5039 return orig_type;
5041 if (TREE_CODE (orig_type) == TYPE_DECL)
5043 if (same_type_p (type, TREE_TYPE (orig_type)))
5044 type = orig_type;
5045 else
5046 type = TYPE_NAME (type);
5048 return type;
5051 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
5052 template PARMS and constraints, CONSTR. If MEMBER_TEMPLATE_P is true,
5053 the new template is a member template. */
5055 static tree
5056 build_template_decl (tree decl, tree parms, bool member_template_p)
5058 gcc_checking_assert (TREE_CODE (decl) != TEMPLATE_DECL);
5060 tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
5061 SET_DECL_LANGUAGE (tmpl, DECL_LANGUAGE (decl));
5062 DECL_TEMPLATE_PARMS (tmpl) = parms;
5063 DECL_TEMPLATE_RESULT (tmpl) = decl;
5064 DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
5065 TREE_TYPE (tmpl) = TREE_TYPE (decl);
5066 DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
5067 DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
5069 /* Propagate module information from the decl. */
5070 DECL_MODULE_EXPORT_P (tmpl) = DECL_MODULE_EXPORT_P (decl);
5072 return tmpl;
5075 struct template_parm_data
5077 /* The level of the template parameters we are currently
5078 processing. */
5079 int level;
5081 /* The index of the specialization argument we are currently
5082 processing. */
5083 int current_arg;
5085 /* An array whose size is the number of template parameters. The
5086 elements are nonzero if the parameter has been used in any one
5087 of the arguments processed so far. */
5088 int* parms;
5090 /* An array whose size is the number of template arguments. The
5091 elements are nonzero if the argument makes use of template
5092 parameters of this level. */
5093 int* arg_uses_template_parms;
5096 /* Subroutine of push_template_decl used to see if each template
5097 parameter in a partial specialization is used in the explicit
5098 argument list. If T is of the LEVEL given in DATA (which is
5099 treated as a template_parm_data*), then DATA->PARMS is marked
5100 appropriately. */
5102 static int
5103 mark_template_parm (tree t, void* data)
5105 int level;
5106 int idx;
5107 struct template_parm_data* tpd = (struct template_parm_data*) data;
5109 template_parm_level_and_index (t, &level, &idx);
5111 if (level == tpd->level)
5113 tpd->parms[idx] = 1;
5114 tpd->arg_uses_template_parms[tpd->current_arg] = 1;
5117 /* In C++17 the type of a non-type argument is a deduced context. */
5118 if (cxx_dialect >= cxx17
5119 && TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5120 for_each_template_parm (TREE_TYPE (t),
5121 &mark_template_parm,
5122 data,
5123 NULL,
5124 /*include_nondeduced_p=*/false);
5126 /* Return zero so that for_each_template_parm will continue the
5127 traversal of the tree; we want to mark *every* template parm. */
5128 return 0;
5131 /* Process the partial specialization DECL. */
5133 static tree
5134 process_partial_specialization (tree decl)
5136 tree type = TREE_TYPE (decl);
5137 tree tinfo = get_template_info (decl);
5138 tree maintmpl = TI_TEMPLATE (tinfo);
5139 tree specargs = TI_ARGS (tinfo);
5140 tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
5141 tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
5142 tree inner_parms;
5143 tree inst;
5144 int nargs = TREE_VEC_LENGTH (inner_args);
5145 int ntparms;
5146 int i;
5147 bool did_error_intro = false;
5148 struct template_parm_data tpd;
5149 struct template_parm_data tpd2;
5151 gcc_assert (current_template_parms);
5153 /* A concept cannot be specialized. */
5154 if (flag_concepts && variable_concept_p (maintmpl))
5156 error ("specialization of variable concept %q#D", maintmpl);
5157 return error_mark_node;
5160 inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
5161 ntparms = TREE_VEC_LENGTH (inner_parms);
5163 /* We check that each of the template parameters given in the
5164 partial specialization is used in the argument list to the
5165 specialization. For example:
5167 template <class T> struct S;
5168 template <class T> struct S<T*>;
5170 The second declaration is OK because `T*' uses the template
5171 parameter T, whereas
5173 template <class T> struct S<int>;
5175 is no good. Even trickier is:
5177 template <class T>
5178 struct S1
5180 template <class U>
5181 struct S2;
5182 template <class U>
5183 struct S2<T>;
5186 The S2<T> declaration is actually invalid; it is a
5187 full-specialization. Of course,
5189 template <class U>
5190 struct S2<T (*)(U)>;
5192 or some such would have been OK. */
5193 tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
5194 tpd.parms = XALLOCAVEC (int, ntparms);
5195 memset (tpd.parms, 0, sizeof (int) * ntparms);
5197 tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
5198 memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
5199 for (i = 0; i < nargs; ++i)
5201 tpd.current_arg = i;
5202 for_each_template_parm (TREE_VEC_ELT (inner_args, i),
5203 &mark_template_parm,
5204 &tpd,
5205 NULL,
5206 /*include_nondeduced_p=*/false);
5208 for (i = 0; i < ntparms; ++i)
5209 if (tpd.parms[i] == 0)
5211 /* One of the template parms was not used in a deduced context in the
5212 specialization. */
5213 if (!did_error_intro)
5215 error ("template parameters not deducible in "
5216 "partial specialization:");
5217 did_error_intro = true;
5220 inform (input_location, " %qD",
5221 TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
5224 if (did_error_intro)
5225 return error_mark_node;
5227 /* [temp.class.spec]
5229 The argument list of the specialization shall not be identical to
5230 the implicit argument list of the primary template. */
5231 tree main_args
5232 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (maintmpl)));
5233 if (comp_template_args (inner_args, INNERMOST_TEMPLATE_ARGS (main_args))
5234 && (!flag_concepts
5235 || !strictly_subsumes (current_template_constraints (), maintmpl)))
5237 if (!flag_concepts)
5238 error ("partial specialization %q+D does not specialize "
5239 "any template arguments; to define the primary template, "
5240 "remove the template argument list", decl);
5241 else
5242 error ("partial specialization %q+D does not specialize any "
5243 "template arguments and is not more constrained than "
5244 "the primary template; to define the primary template, "
5245 "remove the template argument list", decl);
5246 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5249 /* A partial specialization that replaces multiple parameters of the
5250 primary template with a pack expansion is less specialized for those
5251 parameters. */
5252 if (nargs < DECL_NTPARMS (maintmpl))
5254 error ("partial specialization is not more specialized than the "
5255 "primary template because it replaces multiple parameters "
5256 "with a pack expansion");
5257 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5258 /* Avoid crash in process_partial_specialization. */
5259 return decl;
5262 else if (nargs > DECL_NTPARMS (maintmpl))
5264 error ("too many arguments for partial specialization %qT", type);
5265 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5266 /* Avoid crash below. */
5267 return decl;
5270 /* If we aren't in a dependent class, we can actually try deduction. */
5271 else if (tpd.level == 1
5272 /* FIXME we should be able to handle a partial specialization of a
5273 partial instantiation, but currently we can't (c++/41727). */
5274 && TMPL_ARGS_DEPTH (specargs) == 1
5275 && !get_partial_spec_bindings (maintmpl, maintmpl, specargs))
5277 auto_diagnostic_group d;
5278 if (pedwarn (input_location, 0,
5279 "partial specialization %qD is not more specialized than",
5280 decl))
5281 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template %qD",
5282 maintmpl);
5285 /* [temp.spec.partial]
5287 The type of a template parameter corresponding to a specialized
5288 non-type argument shall not be dependent on a parameter of the
5289 specialization.
5291 Also, we verify that pack expansions only occur at the
5292 end of the argument list. */
5293 tpd2.parms = 0;
5294 for (i = 0; i < nargs; ++i)
5296 tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
5297 tree arg = TREE_VEC_ELT (inner_args, i);
5298 tree packed_args = NULL_TREE;
5299 int j, len = 1;
5301 if (ARGUMENT_PACK_P (arg))
5303 /* Extract the arguments from the argument pack. We'll be
5304 iterating over these in the following loop. */
5305 packed_args = ARGUMENT_PACK_ARGS (arg);
5306 len = TREE_VEC_LENGTH (packed_args);
5309 for (j = 0; j < len; j++)
5311 if (packed_args)
5312 /* Get the Jth argument in the parameter pack. */
5313 arg = TREE_VEC_ELT (packed_args, j);
5315 if (PACK_EXPANSION_P (arg))
5317 /* Pack expansions must come at the end of the
5318 argument list. */
5319 if ((packed_args && j < len - 1)
5320 || (!packed_args && i < nargs - 1))
5322 if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5323 error ("parameter pack argument %qE must be at the "
5324 "end of the template argument list", arg);
5325 else
5326 error ("parameter pack argument %qT must be at the "
5327 "end of the template argument list", arg);
5331 if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5332 /* We only care about the pattern. */
5333 arg = PACK_EXPANSION_PATTERN (arg);
5335 if (/* These first two lines are the `non-type' bit. */
5336 !TYPE_P (arg)
5337 && TREE_CODE (arg) != TEMPLATE_DECL
5338 /* This next two lines are the `argument expression is not just a
5339 simple identifier' condition and also the `specialized
5340 non-type argument' bit. */
5341 && TREE_CODE (arg) != TEMPLATE_PARM_INDEX
5342 && !((REFERENCE_REF_P (arg)
5343 || TREE_CODE (arg) == VIEW_CONVERT_EXPR)
5344 && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_PARM_INDEX))
5346 /* Look at the corresponding template parameter,
5347 marking which template parameters its type depends
5348 upon. */
5349 tree type = TREE_TYPE (parm);
5351 if (!tpd2.parms)
5353 /* We haven't yet initialized TPD2. Do so now. */
5354 tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
5355 /* The number of parameters here is the number in the
5356 main template, which, as checked in the assertion
5357 above, is NARGS. */
5358 tpd2.parms = XALLOCAVEC (int, nargs);
5359 tpd2.level =
5360 TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
5363 /* Mark the template parameters. But this time, we're
5364 looking for the template parameters of the main
5365 template, not in the specialization. */
5366 tpd2.current_arg = i;
5367 tpd2.arg_uses_template_parms[i] = 0;
5368 memset (tpd2.parms, 0, sizeof (int) * nargs);
5369 for_each_template_parm (type,
5370 &mark_template_parm,
5371 &tpd2,
5372 NULL,
5373 /*include_nondeduced_p=*/false);
5375 if (tpd2.arg_uses_template_parms [i])
5377 /* The type depended on some template parameters.
5378 If they are fully specialized in the
5379 specialization, that's OK. */
5380 int j;
5381 int count = 0;
5382 for (j = 0; j < nargs; ++j)
5383 if (tpd2.parms[j] != 0
5384 && tpd.arg_uses_template_parms [j])
5385 ++count;
5386 if (count != 0)
5387 error_n (input_location, count,
5388 "type %qT of template argument %qE depends "
5389 "on a template parameter",
5390 "type %qT of template argument %qE depends "
5391 "on template parameters",
5392 type,
5393 arg);
5399 /* We should only get here once. */
5400 if (TREE_CODE (decl) == TYPE_DECL)
5401 gcc_assert (!COMPLETE_TYPE_P (type));
5403 // Build the template decl.
5404 tree tmpl = build_template_decl (decl, current_template_parms,
5405 DECL_MEMBER_TEMPLATE_P (maintmpl));
5406 SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5407 DECL_TEMPLATE_INFO (tmpl) = build_template_info (maintmpl, specargs);
5408 DECL_PRIMARY_TEMPLATE (tmpl) = maintmpl;
5410 /* Give template template parms a DECL_CONTEXT of the template
5411 for which they are a parameter. */
5412 for (i = 0; i < ntparms; ++i)
5414 tree parm = TREE_VALUE (TREE_VEC_ELT (inner_parms, i));
5415 if (TREE_CODE (parm) == TEMPLATE_DECL)
5416 DECL_CONTEXT (parm) = tmpl;
5419 if (VAR_P (decl))
5420 /* We didn't register this in check_explicit_specialization so we could
5421 wait until the constraints were set. */
5422 decl = register_specialization (decl, maintmpl, specargs, false, 0);
5423 else
5424 associate_classtype_constraints (type);
5426 DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
5427 = tree_cons (specargs, tmpl,
5428 DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
5429 TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
5430 /* Link the DECL_TEMPLATE_RESULT back to the partial TEMPLATE_DECL. */
5431 gcc_checking_assert (!TI_PARTIAL_INFO (tinfo));
5432 TI_PARTIAL_INFO (tinfo) = build_template_info (tmpl, NULL_TREE);
5434 for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
5435 inst = TREE_CHAIN (inst))
5437 tree instance = TREE_VALUE (inst);
5438 if (TYPE_P (instance)
5439 ? (COMPLETE_TYPE_P (instance)
5440 && CLASSTYPE_IMPLICIT_INSTANTIATION (instance))
5441 : DECL_TEMPLATE_INSTANTIATION (instance))
5443 tree partial_ti = most_specialized_partial_spec (instance, tf_none,
5444 /*rechecking=*/true);
5445 tree inst_decl = (DECL_P (instance)
5446 ? instance : TYPE_NAME (instance));
5447 if (!partial_ti)
5448 /* OK */;
5449 else if (partial_ti == error_mark_node)
5450 permerror (input_location,
5451 "declaration of %qD ambiguates earlier template "
5452 "instantiation for %qD", decl, inst_decl);
5453 else if (TI_TEMPLATE (partial_ti) == tmpl)
5454 permerror (input_location,
5455 "partial specialization of %qD after instantiation "
5456 "of %qD", decl, inst_decl);
5460 return decl;
5463 /* PARM is a template parameter of some form; return the corresponding
5464 TEMPLATE_PARM_INDEX. */
5466 static tree
5467 get_template_parm_index (tree parm)
5469 if (TREE_CODE (parm) == PARM_DECL
5470 || TREE_CODE (parm) == CONST_DECL)
5471 parm = DECL_INITIAL (parm);
5472 else if (TREE_CODE (parm) == TYPE_DECL
5473 || TREE_CODE (parm) == TEMPLATE_DECL)
5474 parm = TREE_TYPE (parm);
5475 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
5476 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM
5477 || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
5478 parm = TEMPLATE_TYPE_PARM_INDEX (parm);
5479 gcc_assert (TREE_CODE (parm) == TEMPLATE_PARM_INDEX);
5480 return parm;
5483 /* Subroutine of fixed_parameter_pack_p below. Look for any template
5484 parameter packs used by the template parameter PARM. */
5486 static void
5487 fixed_parameter_pack_p_1 (tree parm, struct find_parameter_pack_data *ppd)
5489 /* A type parm can't refer to another parm. */
5490 if (TREE_CODE (parm) == TYPE_DECL || parm == error_mark_node)
5491 return;
5492 else if (TREE_CODE (parm) == PARM_DECL)
5494 cp_walk_tree (&TREE_TYPE (parm), &find_parameter_packs_r,
5495 ppd, ppd->visited);
5496 return;
5499 gcc_assert (TREE_CODE (parm) == TEMPLATE_DECL);
5501 tree vec = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
5502 for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
5504 tree p = TREE_VALUE (TREE_VEC_ELT (vec, i));
5505 if (template_parameter_pack_p (p))
5506 /* Any packs in the type are expanded by this parameter. */;
5507 else
5508 fixed_parameter_pack_p_1 (p, ppd);
5512 /* PARM is a template parameter pack. Return any parameter packs used in
5513 its type or the type of any of its template parameters. If there are
5514 any such packs, it will be instantiated into a fixed template parameter
5515 list by partial instantiation rather than be fully deduced. */
5517 tree
5518 fixed_parameter_pack_p (tree parm)
5520 /* This can only be true in a member template. */
5521 if (TEMPLATE_PARM_ORIG_LEVEL (get_template_parm_index (parm)) < 2)
5522 return NULL_TREE;
5523 /* This can only be true for a parameter pack. */
5524 if (!template_parameter_pack_p (parm))
5525 return NULL_TREE;
5526 /* A type parm can't refer to another parm. */
5527 if (TREE_CODE (parm) == TYPE_DECL)
5528 return NULL_TREE;
5530 tree parameter_packs = NULL_TREE;
5531 struct find_parameter_pack_data ppd;
5532 ppd.parameter_packs = &parameter_packs;
5533 ppd.visited = new hash_set<tree>;
5534 ppd.type_pack_expansion_p = false;
5536 fixed_parameter_pack_p_1 (parm, &ppd);
5538 delete ppd.visited;
5539 return parameter_packs;
5542 /* Check that a template declaration's use of default arguments and
5543 parameter packs is not invalid. Here, PARMS are the template
5544 parameters. IS_PRIMARY is true if DECL is the thing declared by
5545 a primary template. IS_PARTIAL is true if DECL is a partial
5546 specialization.
5548 IS_FRIEND_DECL is nonzero if DECL is either a non-defining friend
5549 function template declaration or a friend class template
5550 declaration. In the function case, 1 indicates a declaration, 2
5551 indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
5552 emitted for extraneous default arguments.
5554 Returns TRUE if there were no errors found, FALSE otherwise. */
5556 bool
5557 check_default_tmpl_args (tree decl, tree parms, bool is_primary,
5558 bool is_partial, int is_friend_decl)
5560 const char *msg;
5561 int last_level_to_check;
5562 tree parm_level;
5563 bool no_errors = true;
5565 /* [temp.param]
5567 A default template-argument shall not be specified in a
5568 function template declaration or a function template definition, nor
5569 in the template-parameter-list of the definition of a member of a
5570 class template. */
5572 if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL
5573 || (TREE_CODE (decl) == FUNCTION_DECL && DECL_LOCAL_DECL_P (decl)))
5574 /* You can't have a function template declaration in a local
5575 scope, nor you can you define a member of a class template in a
5576 local scope. */
5577 return true;
5579 if ((TREE_CODE (decl) == TYPE_DECL
5580 && TREE_TYPE (decl)
5581 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5582 || (TREE_CODE (decl) == FUNCTION_DECL
5583 && LAMBDA_FUNCTION_P (decl)))
5584 /* A lambda doesn't have an explicit declaration; don't complain
5585 about the parms of the enclosing class. */
5586 return true;
5588 if (current_class_type
5589 && !TYPE_BEING_DEFINED (current_class_type)
5590 && DECL_LANG_SPECIFIC (decl)
5591 && DECL_DECLARES_FUNCTION_P (decl)
5592 /* If this is either a friend defined in the scope of the class
5593 or a member function. */
5594 && (DECL_FUNCTION_MEMBER_P (decl)
5595 ? same_type_p (DECL_CONTEXT (decl), current_class_type)
5596 : DECL_FRIEND_CONTEXT (decl)
5597 ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
5598 : false)
5599 /* And, if it was a member function, it really was defined in
5600 the scope of the class. */
5601 && (!DECL_FUNCTION_MEMBER_P (decl)
5602 || DECL_INITIALIZED_IN_CLASS_P (decl)))
5603 /* We already checked these parameters when the template was
5604 declared, so there's no need to do it again now. This function
5605 was defined in class scope, but we're processing its body now
5606 that the class is complete. */
5607 return true;
5609 /* Core issue 226 (C++0x only): the following only applies to class
5610 templates. */
5611 if (is_primary
5612 && ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL))
5614 /* [temp.param]
5616 If a template-parameter has a default template-argument, all
5617 subsequent template-parameters shall have a default
5618 template-argument supplied. */
5619 for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
5621 tree inner_parms = TREE_VALUE (parm_level);
5622 int ntparms = TREE_VEC_LENGTH (inner_parms);
5623 int seen_def_arg_p = 0;
5624 int i;
5626 for (i = 0; i < ntparms; ++i)
5628 tree parm = TREE_VEC_ELT (inner_parms, i);
5630 if (parm == error_mark_node)
5631 continue;
5633 if (TREE_PURPOSE (parm))
5634 seen_def_arg_p = 1;
5635 else if (seen_def_arg_p
5636 && !template_parameter_pack_p (TREE_VALUE (parm)))
5638 error ("no default argument for %qD", TREE_VALUE (parm));
5639 /* For better subsequent error-recovery, we indicate that
5640 there should have been a default argument. */
5641 TREE_PURPOSE (parm) = error_mark_node;
5642 no_errors = false;
5644 else if (!is_partial
5645 && !is_friend_decl
5646 /* Don't complain about an enclosing partial
5647 specialization. */
5648 && parm_level == parms
5649 && (TREE_CODE (decl) == TYPE_DECL || VAR_P (decl))
5650 && i < ntparms - 1
5651 && template_parameter_pack_p (TREE_VALUE (parm))
5652 /* A fixed parameter pack will be partially
5653 instantiated into a fixed length list. */
5654 && !fixed_parameter_pack_p (TREE_VALUE (parm)))
5656 /* A primary class template, primary variable template
5657 (DR 2032), or alias template can only have one
5658 parameter pack, at the end of the template
5659 parameter list. */
5661 error ("parameter pack %q+D must be at the end of the"
5662 " template parameter list", TREE_VALUE (parm));
5664 TREE_VALUE (TREE_VEC_ELT (inner_parms, i))
5665 = error_mark_node;
5666 no_errors = false;
5672 if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
5673 || is_partial
5674 || !is_primary
5675 || is_friend_decl)
5676 /* For an ordinary class template, default template arguments are
5677 allowed at the innermost level, e.g.:
5678 template <class T = int>
5679 struct S {};
5680 but, in a partial specialization, they're not allowed even
5681 there, as we have in [temp.class.spec]:
5683 The template parameter list of a specialization shall not
5684 contain default template argument values.
5686 So, for a partial specialization, or for a function template
5687 (in C++98/C++03), we look at all of them. */
5689 else
5690 /* But, for a primary class template that is not a partial
5691 specialization we look at all template parameters except the
5692 innermost ones. */
5693 parms = TREE_CHAIN (parms);
5695 /* Figure out what error message to issue. */
5696 if (is_friend_decl == 2)
5697 msg = G_("default template arguments may not be used in function template "
5698 "friend re-declaration");
5699 else if (is_friend_decl)
5700 msg = G_("default template arguments may not be used in template "
5701 "friend declarations");
5702 else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
5703 msg = G_("default template arguments may not be used in function templates "
5704 "without %<-std=c++11%> or %<-std=gnu++11%>");
5705 else if (is_partial)
5706 msg = G_("default template arguments may not be used in "
5707 "partial specializations");
5708 else if (current_class_type && CLASSTYPE_IS_TEMPLATE (current_class_type))
5709 msg = G_("default argument for template parameter for class enclosing %qD");
5710 else
5711 /* Per [temp.param]/9, "A default template-argument shall not be
5712 specified in the template-parameter-lists of the definition of
5713 a member of a class template that appears outside of the member's
5714 class.", thus if we aren't handling a member of a class template
5715 there is no need to examine the parameters. */
5716 return true;
5718 if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
5719 /* If we're inside a class definition, there's no need to
5720 examine the parameters to the class itself. On the one
5721 hand, they will be checked when the class is defined, and,
5722 on the other, default arguments are valid in things like:
5723 template <class T = double>
5724 struct S { template <class U> void f(U); };
5725 Here the default argument for `S' has no bearing on the
5726 declaration of `f'. */
5727 last_level_to_check = template_class_depth (current_class_type) + 1;
5728 else
5729 /* Check everything. */
5730 last_level_to_check = 0;
5732 for (parm_level = parms;
5733 parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
5734 parm_level = TREE_CHAIN (parm_level))
5736 tree inner_parms = TREE_VALUE (parm_level);
5737 int i;
5738 int ntparms;
5740 ntparms = TREE_VEC_LENGTH (inner_parms);
5741 for (i = 0; i < ntparms; ++i)
5743 if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
5744 continue;
5746 if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
5748 if (msg)
5750 no_errors = false;
5751 if (is_friend_decl == 2)
5752 return no_errors;
5754 error (msg, decl);
5755 msg = 0;
5758 /* Clear out the default argument so that we are not
5759 confused later. */
5760 TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
5764 /* At this point, if we're still interested in issuing messages,
5765 they must apply to classes surrounding the object declared. */
5766 if (msg)
5767 msg = G_("default argument for template parameter for class "
5768 "enclosing %qD");
5771 return no_errors;
5774 /* Worker for push_template_decl_real, called via
5775 for_each_template_parm. DATA is really an int, indicating the
5776 level of the parameters we are interested in. If T is a template
5777 parameter of that level, return nonzero. */
5779 static int
5780 template_parm_this_level_p (tree t, void* data)
5782 int this_level = *(int *)data;
5783 int level;
5785 if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5786 level = TEMPLATE_PARM_LEVEL (t);
5787 else
5788 level = TEMPLATE_TYPE_LEVEL (t);
5789 return level == this_level;
5792 /* Worker for uses_outer_template_parms, called via for_each_template_parm.
5793 DATA is really an int, indicating the innermost outer level of parameters.
5794 If T is a template parameter of that level or further out, return
5795 nonzero. */
5797 static int
5798 template_parm_outer_level (tree t, void *data)
5800 int this_level = *(int *)data;
5801 int level;
5803 if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5804 level = TEMPLATE_PARM_LEVEL (t);
5805 else
5806 level = TEMPLATE_TYPE_LEVEL (t);
5807 return level <= this_level;
5810 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
5811 parameters given by current_template_args, or reuses a
5812 previously existing one, if appropriate. Returns the DECL, or an
5813 equivalent one, if it is replaced via a call to duplicate_decls.
5815 If IS_FRIEND is true, DECL is a friend declaration. */
5817 tree
5818 push_template_decl (tree decl, bool is_friend)
5820 if (decl == error_mark_node || !current_template_parms)
5821 return error_mark_node;
5823 /* See if this is a partial specialization. */
5824 bool is_partial = ((DECL_IMPLICIT_TYPEDEF_P (decl)
5825 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
5826 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
5827 || (VAR_P (decl)
5828 && DECL_LANG_SPECIFIC (decl)
5829 && DECL_TEMPLATE_SPECIALIZATION (decl)
5830 && TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl))));
5832 /* No surprising friend functions. */
5833 gcc_checking_assert (is_friend
5834 || !(TREE_CODE (decl) == FUNCTION_DECL
5835 && DECL_UNIQUE_FRIEND_P (decl)));
5837 tree ctx;
5838 if (is_friend)
5839 /* For a friend, we want the context of the friend, not
5840 the type of which it is a friend. */
5841 ctx = CP_DECL_CONTEXT (decl);
5842 else if (CP_DECL_CONTEXT (decl)
5843 && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
5844 /* In the case of a virtual function, we want the class in which
5845 it is defined. */
5846 ctx = CP_DECL_CONTEXT (decl);
5847 else
5848 /* Otherwise, if we're currently defining some class, the DECL
5849 is assumed to be a member of the class. */
5850 ctx = current_scope ();
5852 if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
5853 ctx = NULL_TREE;
5855 if (!DECL_CONTEXT (decl))
5856 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5858 /* See if this is a primary template. */
5859 bool is_primary = false;
5860 if (is_friend && ctx
5861 && uses_template_parms_level (ctx, current_template_depth))
5862 /* A friend template that specifies a class context, i.e.
5863 template <typename T> friend void A<T>::f();
5864 is not primary. */
5866 else if (TREE_CODE (decl) == TYPE_DECL && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5867 /* Lambdas are not primary. */
5869 else
5870 is_primary = template_parm_scope_p ();
5872 /* True if the template is a member template, in the sense of
5873 [temp.mem]. */
5874 bool member_template_p = false;
5876 if (is_primary)
5878 warning (OPT_Wtemplates, "template %qD declared", decl);
5880 if (DECL_CLASS_SCOPE_P (decl))
5881 member_template_p = true;
5883 if (TREE_CODE (decl) == TYPE_DECL
5884 && IDENTIFIER_ANON_P (DECL_NAME (decl)))
5886 error ("template class without a name");
5887 return error_mark_node;
5889 else if (TREE_CODE (decl) == FUNCTION_DECL)
5891 if (member_template_p)
5893 if (DECL_OVERRIDE_P (decl) || DECL_FINAL_P (decl))
5894 error ("member template %qD may not have virt-specifiers", decl);
5896 if (DECL_DESTRUCTOR_P (decl))
5898 /* [temp.mem]
5900 A destructor shall not be a member template. */
5901 error_at (DECL_SOURCE_LOCATION (decl),
5902 "destructor %qD declared as member template", decl);
5903 return error_mark_node;
5905 if (IDENTIFIER_NEWDEL_OP_P (DECL_NAME (decl))
5906 && (!prototype_p (TREE_TYPE (decl))
5907 || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
5908 || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5909 || (TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5910 == void_list_node)))
5912 /* [basic.stc.dynamic.allocation]
5914 An allocation function can be a function
5915 template. ... Template allocation functions shall
5916 have two or more parameters. */
5917 error ("invalid template declaration of %qD", decl);
5918 return error_mark_node;
5921 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5922 && CLASS_TYPE_P (TREE_TYPE (decl)))
5923 /* Class template. */;
5924 else if (TREE_CODE (decl) == TYPE_DECL
5925 && TYPE_DECL_ALIAS_P (decl))
5926 /* alias-declaration */
5927 gcc_assert (!DECL_ARTIFICIAL (decl));
5928 else if (VAR_P (decl))
5929 /* C++14 variable template. */;
5930 else if (TREE_CODE (decl) == CONCEPT_DECL)
5931 /* C++20 concept definitions. */;
5932 else
5934 error ("template declaration of %q#D", decl);
5935 return error_mark_node;
5939 bool local_p = (!DECL_IMPLICIT_TYPEDEF_P (decl)
5940 && ((ctx && TREE_CODE (ctx) == FUNCTION_DECL)
5941 || (VAR_OR_FUNCTION_DECL_P (decl)
5942 && DECL_LOCAL_DECL_P (decl))));
5944 /* Check to see that the rules regarding the use of default
5945 arguments are not being violated. We check args for a friend
5946 functions when we know whether it's a definition, introducing
5947 declaration or re-declaration. */
5948 if (!local_p && (!is_friend || TREE_CODE (decl) != FUNCTION_DECL))
5949 check_default_tmpl_args (decl, current_template_parms,
5950 is_primary, is_partial, is_friend);
5952 /* Ensure that there are no parameter packs in the type of this
5953 declaration that have not been expanded. */
5954 if (TREE_CODE (decl) == FUNCTION_DECL)
5956 /* Check each of the arguments individually to see if there are
5957 any bare parameter packs. */
5958 tree type = TREE_TYPE (decl);
5959 tree arg = DECL_ARGUMENTS (decl);
5960 tree argtype = TYPE_ARG_TYPES (type);
5962 while (arg && argtype)
5964 if (!DECL_PACK_P (arg)
5965 && check_for_bare_parameter_packs (TREE_TYPE (arg)))
5967 /* This is a PARM_DECL that contains unexpanded parameter
5968 packs. We have already complained about this in the
5969 check_for_bare_parameter_packs call, so just replace
5970 these types with ERROR_MARK_NODE. */
5971 TREE_TYPE (arg) = error_mark_node;
5972 TREE_VALUE (argtype) = error_mark_node;
5975 arg = DECL_CHAIN (arg);
5976 argtype = TREE_CHAIN (argtype);
5979 /* Check for bare parameter packs in the return type and the
5980 exception specifiers. */
5981 if (check_for_bare_parameter_packs (TREE_TYPE (type)))
5982 /* Errors were already issued, set return type to int
5983 as the frontend doesn't expect error_mark_node as
5984 the return type. */
5985 TREE_TYPE (type) = integer_type_node;
5986 if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
5987 TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
5989 else
5991 if (check_for_bare_parameter_packs (is_typedef_decl (decl)
5992 ? DECL_ORIGINAL_TYPE (decl)
5993 : TREE_TYPE (decl)))
5995 TREE_TYPE (decl) = error_mark_node;
5996 return error_mark_node;
5999 if (is_partial && VAR_P (decl)
6000 && check_for_bare_parameter_packs (DECL_TI_ARGS (decl)))
6001 return error_mark_node;
6004 if (is_partial)
6005 return process_partial_specialization (decl);
6007 tree args = current_template_args ();
6008 tree tmpl = NULL_TREE;
6009 bool new_template_p = false;
6010 if (local_p)
6012 /* Does not get a template head. */
6013 tmpl = NULL_TREE;
6014 gcc_checking_assert (!is_primary);
6016 else if (!ctx
6017 || TREE_CODE (ctx) == FUNCTION_DECL
6018 || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
6019 || (TREE_CODE (decl) == TYPE_DECL && LAMBDA_TYPE_P (TREE_TYPE (decl)))
6020 || (is_friend && !(DECL_LANG_SPECIFIC (decl)
6021 && DECL_TEMPLATE_INFO (decl))))
6023 if (DECL_LANG_SPECIFIC (decl)
6024 && DECL_TEMPLATE_INFO (decl)
6025 && DECL_TI_TEMPLATE (decl))
6026 tmpl = DECL_TI_TEMPLATE (decl);
6027 /* If DECL is a TYPE_DECL for a class-template, then there won't
6028 be DECL_LANG_SPECIFIC. The information equivalent to
6029 DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead. */
6030 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
6031 && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
6032 && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
6034 /* Since a template declaration already existed for this
6035 class-type, we must be redeclaring it here. Make sure
6036 that the redeclaration is valid. */
6037 redeclare_class_template (TREE_TYPE (decl),
6038 current_template_parms,
6039 current_template_constraints ());
6040 /* We don't need to create a new TEMPLATE_DECL; just use the
6041 one we already had. */
6042 tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
6044 else
6046 tmpl = build_template_decl (decl, current_template_parms,
6047 member_template_p);
6048 new_template_p = true;
6050 if (DECL_LANG_SPECIFIC (decl)
6051 && DECL_TEMPLATE_SPECIALIZATION (decl))
6053 /* A specialization of a member template of a template
6054 class. */
6055 SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
6056 DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
6057 DECL_TEMPLATE_INFO (decl) = NULL_TREE;
6061 else
6063 tree a, t, current, parms;
6064 int i;
6065 tree tinfo = get_template_info (decl);
6067 if (!tinfo)
6069 error ("template definition of non-template %q#D", decl);
6070 return error_mark_node;
6073 tmpl = TI_TEMPLATE (tinfo);
6075 if (DECL_FUNCTION_TEMPLATE_P (tmpl)
6076 && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
6077 && DECL_TEMPLATE_SPECIALIZATION (decl)
6078 && DECL_MEMBER_TEMPLATE_P (tmpl))
6080 /* The declaration is a specialization of a member
6081 template, declared outside the class. Therefore, the
6082 innermost template arguments will be NULL, so we
6083 replace them with the arguments determined by the
6084 earlier call to check_explicit_specialization. */
6085 args = DECL_TI_ARGS (decl);
6087 tree new_tmpl
6088 = build_template_decl (decl, current_template_parms,
6089 member_template_p);
6090 DECL_TI_TEMPLATE (decl) = new_tmpl;
6091 SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
6092 DECL_TEMPLATE_INFO (new_tmpl)
6093 = build_template_info (tmpl, args);
6095 register_specialization (new_tmpl,
6096 most_general_template (tmpl),
6097 args,
6098 is_friend, 0);
6099 return decl;
6102 /* Make sure the template headers we got make sense. */
6104 parms = DECL_TEMPLATE_PARMS (tmpl);
6105 i = TMPL_PARMS_DEPTH (parms);
6106 if (TMPL_ARGS_DEPTH (args) != i)
6108 error ("expected %d levels of template parms for %q#D, got %d",
6109 i, decl, TMPL_ARGS_DEPTH (args));
6110 DECL_INTERFACE_KNOWN (decl) = 1;
6111 return error_mark_node;
6113 else
6114 for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
6116 a = TMPL_ARGS_LEVEL (args, i);
6117 t = INNERMOST_TEMPLATE_PARMS (parms);
6119 if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
6121 if (current == decl)
6122 error ("got %d template parameters for %q#D",
6123 TREE_VEC_LENGTH (a), decl);
6124 else
6125 error ("got %d template parameters for %q#T",
6126 TREE_VEC_LENGTH (a), current);
6127 error (" but %d required", TREE_VEC_LENGTH (t));
6128 /* Avoid crash in import_export_decl. */
6129 DECL_INTERFACE_KNOWN (decl) = 1;
6130 return error_mark_node;
6133 if (current == decl)
6134 current = ctx;
6135 else if (current == NULL_TREE)
6136 /* Can happen in erroneous input. */
6137 break;
6138 else
6139 current = get_containing_scope (current);
6142 /* Check that the parms are used in the appropriate qualifying scopes
6143 in the declarator. */
6144 if (!comp_template_args
6145 (TI_ARGS (tinfo),
6146 TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
6148 error ("template arguments to %qD do not match original "
6149 "template %qD", decl, DECL_TEMPLATE_RESULT (tmpl));
6150 if (!uses_template_parms (TI_ARGS (tinfo)))
6151 inform (input_location, "use %<template<>%> for"
6152 " an explicit specialization");
6153 /* Avoid crash in import_export_decl. */
6154 DECL_INTERFACE_KNOWN (decl) = 1;
6155 return error_mark_node;
6158 /* Check that the constraints for each enclosing template scope are
6159 consistent with the original declarations. */
6160 if (flag_concepts)
6162 tree decl_parms = DECL_TEMPLATE_PARMS (tmpl);
6163 tree scope_parms = current_template_parms;
6164 if (PRIMARY_TEMPLATE_P (tmpl))
6166 decl_parms = TREE_CHAIN (decl_parms);
6167 scope_parms = TREE_CHAIN (scope_parms);
6169 while (decl_parms)
6171 if (!template_requirements_equivalent_p (decl_parms, scope_parms))
6173 error ("redeclaration of %qD with different constraints",
6174 TPARMS_PRIMARY_TEMPLATE (TREE_VALUE (decl_parms)));
6175 break;
6177 decl_parms = TREE_CHAIN (decl_parms);
6178 scope_parms = TREE_CHAIN (scope_parms);
6183 gcc_checking_assert (!tmpl || DECL_TEMPLATE_RESULT (tmpl) == decl);
6185 if (new_template_p)
6187 /* Push template declarations for global functions and types.
6188 Note that we do not try to push a global template friend
6189 declared in a template class; such a thing may well depend on
6190 the template parameters of the class and we'll push it when
6191 instantiating the befriending class. */
6192 if (!ctx
6193 && !(is_friend && template_class_depth (current_class_type) > 0))
6195 tree pushed = pushdecl_namespace_level (tmpl, /*hiding=*/is_friend);
6196 if (pushed == error_mark_node)
6197 return error_mark_node;
6199 /* pushdecl may have found an existing template. */
6200 if (pushed != tmpl)
6202 decl = DECL_TEMPLATE_RESULT (pushed);
6203 tmpl = NULL_TREE;
6206 else if (is_friend)
6208 /* Record this decl as belonging to the current class. It's
6209 not chained onto anything else. */
6210 DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (tmpl) = true;
6211 gcc_checking_assert (!DECL_CHAIN (tmpl));
6212 DECL_CHAIN (tmpl) = current_scope ();
6215 else if (tmpl)
6216 /* The type may have been completed, or (erroneously) changed. */
6217 TREE_TYPE (tmpl) = TREE_TYPE (decl);
6219 if (tmpl)
6221 if (is_primary)
6223 tree parms = DECL_TEMPLATE_PARMS (tmpl);
6225 DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
6227 /* Give template template parms a DECL_CONTEXT of the template
6228 for which they are a parameter. */
6229 parms = INNERMOST_TEMPLATE_PARMS (parms);
6230 for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
6232 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
6233 if (TREE_CODE (parm) == TEMPLATE_DECL)
6234 DECL_CONTEXT (parm) = tmpl;
6237 if (TREE_CODE (decl) == TYPE_DECL
6238 && TYPE_DECL_ALIAS_P (decl))
6240 if (tree constr
6241 = TEMPLATE_PARMS_CONSTRAINTS (DECL_TEMPLATE_PARMS (tmpl)))
6243 /* ??? Why don't we do this here for all templates? */
6244 constr = build_constraints (constr, NULL_TREE);
6245 set_constraints (decl, constr);
6250 /* The DECL_TI_ARGS of DECL contains full set of arguments
6251 referring wback to its most general template. If TMPL is a
6252 specialization, ARGS may only have the innermost set of
6253 arguments. Add the missing argument levels if necessary. */
6254 if (DECL_TEMPLATE_INFO (tmpl))
6255 args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
6257 tree info = build_template_info (tmpl, args);
6259 if (DECL_IMPLICIT_TYPEDEF_P (decl))
6260 SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
6261 else
6263 retrofit_lang_decl (decl);
6264 DECL_TEMPLATE_INFO (decl) = info;
6268 if (flag_implicit_templates
6269 && !is_friend
6270 && TREE_PUBLIC (decl)
6271 && VAR_OR_FUNCTION_DECL_P (decl))
6272 /* Set DECL_COMDAT on template instantiations; if we force
6273 them to be emitted by explicit instantiation,
6274 mark_needed will tell cgraph to do the right thing. */
6275 DECL_COMDAT (decl) = true;
6277 gcc_checking_assert (!tmpl || DECL_TEMPLATE_RESULT (tmpl) == decl);
6279 return decl;
6282 /* FN is an inheriting constructor that inherits from the constructor
6283 template INHERITED; turn FN into a constructor template with a matching
6284 template header. */
6286 tree
6287 add_inherited_template_parms (tree fn, tree inherited)
6289 tree inner_parms
6290 = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (inherited));
6291 inner_parms = copy_node (inner_parms);
6292 tree parms
6293 = tree_cons (size_int (current_template_depth + 1),
6294 inner_parms, current_template_parms);
6295 tree tmpl = build_template_decl (fn, parms, /*member*/true);
6296 tree args = template_parms_to_args (parms);
6297 DECL_TEMPLATE_INFO (fn) = build_template_info (tmpl, args);
6298 DECL_ARTIFICIAL (tmpl) = true;
6299 DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
6300 return tmpl;
6303 /* Called when a class template TYPE is redeclared with the indicated
6304 template PARMS, e.g.:
6306 template <class T> struct S;
6307 template <class T> struct S {}; */
6309 bool
6310 redeclare_class_template (tree type, tree parms, tree cons)
6312 tree tmpl;
6313 tree tmpl_parms;
6314 int i;
6316 if (!TYPE_TEMPLATE_INFO (type))
6318 error ("%qT is not a template type", type);
6319 return false;
6322 tmpl = TYPE_TI_TEMPLATE (type);
6323 if (!PRIMARY_TEMPLATE_P (tmpl))
6324 /* The type is nested in some template class. Nothing to worry
6325 about here; there are no new template parameters for the nested
6326 type. */
6327 return true;
6329 if (!parms)
6331 error ("template specifiers not specified in declaration of %qD",
6332 tmpl);
6333 return false;
6336 parms = INNERMOST_TEMPLATE_PARMS (parms);
6337 tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
6339 if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
6341 error_n (input_location, TREE_VEC_LENGTH (parms),
6342 "redeclared with %d template parameter",
6343 "redeclared with %d template parameters",
6344 TREE_VEC_LENGTH (parms));
6345 inform_n (DECL_SOURCE_LOCATION (tmpl), TREE_VEC_LENGTH (tmpl_parms),
6346 "previous declaration %qD used %d template parameter",
6347 "previous declaration %qD used %d template parameters",
6348 tmpl, TREE_VEC_LENGTH (tmpl_parms));
6349 return false;
6352 for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
6354 tree tmpl_parm;
6355 tree parm;
6357 if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
6358 || TREE_VEC_ELT (parms, i) == error_mark_node)
6359 continue;
6361 tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
6362 if (error_operand_p (tmpl_parm))
6363 return false;
6365 parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
6367 /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
6368 TEMPLATE_DECL. */
6369 if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
6370 || (TREE_CODE (tmpl_parm) != TYPE_DECL
6371 && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
6372 || (TREE_CODE (tmpl_parm) != PARM_DECL
6373 && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
6374 != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
6375 || (TREE_CODE (tmpl_parm) == PARM_DECL
6376 && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
6377 != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
6379 auto_diagnostic_group d;
6380 error ("template parameter %q+#D", tmpl_parm);
6381 if (DECL_P (parm))
6382 inform (DECL_SOURCE_LOCATION (parm), "redeclared here as %q#D", parm);
6383 else
6384 inform (input_location, "redeclared here");
6385 return false;
6388 /* The parameters can be declared to introduce different
6389 constraints. */
6390 tree p1 = TREE_VEC_ELT (tmpl_parms, i);
6391 tree p2 = TREE_VEC_ELT (parms, i);
6392 if (!template_parameter_constraints_equivalent_p (p1, p2))
6394 auto_diagnostic_group d;
6395 error ("declaration of template parameter %q+#D with different "
6396 "constraints", parm);
6397 inform (DECL_SOURCE_LOCATION (tmpl_parm),
6398 "original declaration appeared here");
6399 return false;
6402 /* Give each template template parm in this redeclaration a
6403 DECL_CONTEXT of the template for which they are a parameter. */
6404 if (TREE_CODE (parm) == TEMPLATE_DECL)
6406 gcc_checking_assert (DECL_CONTEXT (parm) == NULL_TREE
6407 || DECL_CONTEXT (parm) == tmpl);
6408 DECL_CONTEXT (parm) = tmpl;
6412 if (!merge_default_template_args (parms, tmpl_parms, /*class_p=*/true))
6413 return false;
6415 tree ci = get_constraints (tmpl);
6416 tree req1 = ci ? CI_TEMPLATE_REQS (ci) : NULL_TREE;
6417 tree req2 = cons ? CI_TEMPLATE_REQS (cons) : NULL_TREE;
6419 /* Two classes with different constraints declare different entities. */
6420 if (!cp_tree_equal (req1, req2))
6422 auto_diagnostic_group d;
6423 error_at (input_location, "redeclaration of %q#D with different "
6424 "constraints", tmpl);
6425 inform (DECL_SOURCE_LOCATION (tmpl),
6426 "original declaration appeared here");
6427 return false;
6430 return true;
6433 /* The actual substitution part of instantiate_non_dependent_expr,
6434 to be used when the caller has already checked
6435 !instantiation_dependent_uneval_expression_p (expr)
6436 and cleared processing_template_decl. */
6438 tree
6439 instantiate_non_dependent_expr_internal (tree expr, tsubst_flags_t complain)
6441 return tsubst_expr (expr, /*args=*/NULL_TREE, complain, /*in_decl=*/NULL_TREE);
6444 /* Instantiate the non-dependent expression EXPR. */
6446 tree
6447 instantiate_non_dependent_expr (tree expr,
6448 tsubst_flags_t complain /* = tf_error */)
6450 if (expr == NULL_TREE)
6451 return NULL_TREE;
6453 if (processing_template_decl)
6455 /* The caller should have checked this already. */
6456 gcc_checking_assert (!instantiation_dependent_uneval_expression_p (expr));
6457 processing_template_decl_sentinel s;
6458 expr = instantiate_non_dependent_expr_internal (expr, complain);
6460 return expr;
6463 /* Like instantiate_non_dependent_expr, but return NULL_TREE if the
6464 expression is dependent or non-constant. */
6466 tree
6467 instantiate_non_dependent_or_null (tree expr)
6469 if (expr == NULL_TREE)
6470 return NULL_TREE;
6471 if (processing_template_decl)
6473 if (!is_nondependent_constant_expression (expr))
6474 expr = NULL_TREE;
6475 else
6477 processing_template_decl_sentinel s;
6478 expr = instantiate_non_dependent_expr_internal (expr, tf_error);
6481 return expr;
6484 /* True iff T is a specialization of a variable template. */
6486 bool
6487 variable_template_specialization_p (tree t)
6489 if (!VAR_P (t) || !DECL_LANG_SPECIFIC (t) || !DECL_TEMPLATE_INFO (t))
6490 return false;
6491 tree tmpl = DECL_TI_TEMPLATE (t);
6492 return variable_template_p (tmpl);
6495 /* Return TRUE iff T is a type alias, a TEMPLATE_DECL for an alias
6496 template declaration, or a TYPE_DECL for an alias declaration. */
6498 bool
6499 alias_type_or_template_p (tree t)
6501 if (t == NULL_TREE)
6502 return false;
6503 return ((TREE_CODE (t) == TYPE_DECL && TYPE_DECL_ALIAS_P (t))
6504 || (TYPE_P (t)
6505 && TYPE_NAME (t)
6506 && TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
6507 || DECL_ALIAS_TEMPLATE_P (t));
6510 /* If T is a specialization of an alias template, return it; otherwise return
6511 NULL_TREE. If TRANSPARENT_TYPEDEFS is true, look through other aliases. */
6513 tree
6514 alias_template_specialization_p (const_tree t,
6515 bool transparent_typedefs)
6517 if (!TYPE_P (t))
6518 return NULL_TREE;
6520 /* It's an alias template specialization if it's an alias and its
6521 TYPE_NAME is a specialization of a primary template. */
6522 if (typedef_variant_p (t))
6524 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
6525 if (PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo)))
6526 return CONST_CAST_TREE (t);
6527 if (transparent_typedefs)
6528 return alias_template_specialization_p (DECL_ORIGINAL_TYPE
6529 (TYPE_NAME (t)),
6530 transparent_typedefs);
6533 return NULL_TREE;
6536 /* A cache of the result of complex_alias_template_p. */
6538 static GTY((deletable)) hash_map<const_tree, tree> *complex_alias_tmpl_info;
6540 /* Data structure for complex_alias_template_*. */
6542 struct uses_all_template_parms_data
6544 int level;
6545 tree *seen;
6548 /* walk_tree callback for complex_alias_template_p. */
6550 static tree
6551 complex_alias_template_r (tree *tp, int *walk_subtrees, void *data_)
6553 tree t = *tp;
6554 auto &data = *(struct uses_all_template_parms_data*)data_;
6556 switch (TREE_CODE (t))
6558 case TEMPLATE_TYPE_PARM:
6559 case TEMPLATE_PARM_INDEX:
6560 case TEMPLATE_TEMPLATE_PARM:
6561 case BOUND_TEMPLATE_TEMPLATE_PARM:
6563 tree idx = get_template_parm_index (t);
6564 if (TEMPLATE_PARM_LEVEL (idx) == data.level)
6565 data.seen[TEMPLATE_PARM_IDX (idx)] = boolean_true_node;
6568 default:;
6571 if (!PACK_EXPANSION_P (t))
6572 return 0;
6574 /* An alias template with a pack expansion that expands a pack from the
6575 enclosing class needs to be considered complex, to avoid confusion with
6576 the same pack being used as an argument to the alias's own template
6577 parameter (91966). */
6578 for (tree pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
6579 pack = TREE_CHAIN (pack))
6581 tree parm_pack = TREE_VALUE (pack);
6582 if (!TEMPLATE_PARM_P (parm_pack))
6583 continue;
6584 int idx, level;
6585 template_parm_level_and_index (parm_pack, &level, &idx);
6586 if (level < data.level)
6587 return t;
6589 /* Consider the expanded packs to be used outside the expansion... */
6590 data.seen[idx] = boolean_true_node;
6593 /* ...but don't walk into the pattern. Consider PR104008:
6595 template <typename T, typename... Ts>
6596 using IsOneOf = disjunction<is_same<T, Ts>...>;
6598 where IsOneOf seemingly uses all of its template parameters in its
6599 expansion (and does not expand a pack from the enclosing class), so the
6600 alias was not marked as complex. However, if it is used like
6601 "IsOneOf<T>", the empty pack for Ts means that T no longer appears in the
6602 expansion. So only Ts is considered used by the pack expansion. */
6603 *walk_subtrees = false;
6605 return 0;
6608 /* An alias template is complex from a SFINAE perspective if a template-id
6609 using that alias can be ill-formed when the expansion is not, as with
6610 the void_t template.
6612 If this predicate returns true in the ordinary case, the out parameter
6613 SEEN_OUT is set to a TREE_VEC containing boolean_true_node at element I if
6614 the I'th template parameter of the alias template is used in the alias. */
6616 static bool
6617 complex_alias_template_p (const_tree tmpl, tree *seen_out)
6619 tmpl = most_general_template (tmpl);
6620 if (!PRIMARY_TEMPLATE_P (tmpl))
6621 return false;
6623 /* A renaming alias isn't complex. */
6624 if (get_underlying_template (CONST_CAST_TREE (tmpl)) != tmpl)
6625 return false;
6627 /* Any other constrained alias is complex. */
6628 if (get_constraints (tmpl))
6629 return true;
6631 if (!complex_alias_tmpl_info)
6632 complex_alias_tmpl_info = hash_map<const_tree, tree>::create_ggc (13);
6634 if (tree *slot = complex_alias_tmpl_info->get (tmpl))
6636 tree result = *slot;
6637 if (result == boolean_false_node)
6638 return false;
6639 if (result == boolean_true_node)
6640 return true;
6641 gcc_assert (TREE_CODE (result) == TREE_VEC);
6642 if (seen_out)
6643 *seen_out = result;
6644 return true;
6647 struct uses_all_template_parms_data data;
6648 tree pat = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6649 tree parms = DECL_TEMPLATE_PARMS (tmpl);
6650 data.level = TMPL_PARMS_DEPTH (parms);
6651 int len = TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS (parms));
6652 tree seen = make_tree_vec (len);
6653 data.seen = TREE_VEC_BEGIN (seen);
6654 for (int i = 0; i < len; ++i)
6655 data.seen[i] = boolean_false_node;
6657 if (cp_walk_tree_without_duplicates (&pat, complex_alias_template_r, &data))
6659 complex_alias_tmpl_info->put (tmpl, boolean_true_node);
6660 return true;
6663 for (int i = 0; i < len; ++i)
6664 if (data.seen[i] != boolean_true_node)
6666 complex_alias_tmpl_info->put (tmpl, seen);
6667 if (seen_out)
6668 *seen_out = seen;
6669 return true;
6672 complex_alias_tmpl_info->put (tmpl, boolean_false_node);
6673 return false;
6676 /* If T is a specialization of a complex alias template with a dependent
6677 argument for an unused template parameter, return it; otherwise return
6678 NULL_TREE. If T is a typedef to such a specialization, return the
6679 specialization. */
6681 tree
6682 dependent_alias_template_spec_p (const_tree t, bool transparent_typedefs)
6684 if (t == error_mark_node)
6685 return NULL_TREE;
6686 gcc_assert (TYPE_P (t));
6688 if (!processing_template_decl || !typedef_variant_p (t))
6689 return NULL_TREE;
6691 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
6693 tree seen = NULL_TREE;
6694 if (complex_alias_template_p (TI_TEMPLATE (tinfo), &seen))
6696 tree args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo));
6697 if (!seen)
6699 if (any_dependent_template_arguments_p (args))
6700 return CONST_CAST_TREE (t);
6702 else
6704 gcc_assert (TREE_VEC_LENGTH (args) == TREE_VEC_LENGTH (seen));
6705 for (int i = 0, len = TREE_VEC_LENGTH (args); i < len; ++i)
6706 if (TREE_VEC_ELT (seen, i) != boolean_true_node
6707 && dependent_template_arg_p (TREE_VEC_ELT (args, i)))
6708 return CONST_CAST_TREE (t);
6711 return NULL_TREE;
6715 if (transparent_typedefs)
6717 tree utype = DECL_ORIGINAL_TYPE (TYPE_NAME (t));
6718 return dependent_alias_template_spec_p (utype, transparent_typedefs);
6721 return NULL_TREE;
6724 /* Return the number of innermost template parameters in TMPL. */
6726 static int
6727 num_innermost_template_parms (const_tree tmpl)
6729 tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
6730 return TREE_VEC_LENGTH (parms);
6733 /* Return either TMPL or another template that it is equivalent to under DR
6734 1286: An alias that just changes the name of a template is equivalent to
6735 the other template. */
6737 static tree
6738 get_underlying_template (tree tmpl)
6740 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
6741 while (DECL_ALIAS_TEMPLATE_P (tmpl))
6743 /* Determine if the alias is equivalent to an underlying template. */
6744 tree orig_type = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6745 /* The underlying type may have been ill-formed. Don't proceed. */
6746 if (!orig_type)
6747 break;
6748 tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (orig_type);
6749 if (!tinfo)
6750 break;
6752 tree underlying = TI_TEMPLATE (tinfo);
6753 if (!PRIMARY_TEMPLATE_P (underlying)
6754 || (num_innermost_template_parms (tmpl)
6755 != num_innermost_template_parms (underlying)))
6756 break;
6758 /* Does the alias add cv-quals? */
6759 if (TYPE_QUALS (TREE_TYPE (underlying)) != TYPE_QUALS (TREE_TYPE (tmpl)))
6760 break;
6762 tree alias_args = INNERMOST_TEMPLATE_ARGS (generic_targs_for (tmpl));
6763 if (!comp_template_args (TI_ARGS (tinfo), alias_args))
6764 break;
6766 /* Are any default template arguments equivalent? */
6767 tree aparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
6768 tree uparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (underlying));
6769 const int nparms = TREE_VEC_LENGTH (aparms);
6770 for (int i = 0; i < nparms; ++i)
6772 tree adefarg = TREE_PURPOSE (TREE_VEC_ELT (aparms, i));
6773 tree udefarg = TREE_PURPOSE (TREE_VEC_ELT (uparms, i));
6774 if (!template_args_equal (adefarg, udefarg))
6775 goto top_break;
6778 /* If TMPL adds or changes any constraints, it isn't equivalent. I think
6779 it's appropriate to treat a less-constrained alias as equivalent. */
6780 if (!at_least_as_constrained (underlying, tmpl))
6781 break;
6783 /* Alias is equivalent. Strip it and repeat. */
6784 tmpl = underlying;
6786 top_break:;
6788 return tmpl;
6791 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
6792 must be a reference-to-function or a pointer-to-function type, as specified
6793 in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
6794 and check that the resulting function has external linkage. */
6796 static tree
6797 convert_nontype_argument_function (tree type, tree expr,
6798 tsubst_flags_t complain)
6800 tree fns = expr;
6801 tree fn, fn_no_ptr;
6802 linkage_kind linkage;
6804 fn = instantiate_type (type, fns, tf_none);
6805 if (fn == error_mark_node)
6806 return error_mark_node;
6808 if (value_dependent_expression_p (fn))
6809 goto accept;
6811 fn_no_ptr = fn;
6812 if (REFERENCE_REF_P (fn_no_ptr))
6813 fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
6814 fn_no_ptr = strip_fnptr_conv (fn_no_ptr);
6815 if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
6816 fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
6817 if (BASELINK_P (fn_no_ptr))
6818 fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
6820 /* [temp.arg.nontype]/1
6822 A template-argument for a non-type, non-template template-parameter
6823 shall be one of:
6824 [...]
6825 -- the address of an object or function with external [C++11: or
6826 internal] linkage. */
6828 STRIP_ANY_LOCATION_WRAPPER (fn_no_ptr);
6829 if (TREE_CODE (fn_no_ptr) != FUNCTION_DECL)
6831 if (complain & tf_error)
6833 location_t loc = cp_expr_loc_or_input_loc (expr);
6834 error_at (loc, "%qE is not a valid template argument for type %qT",
6835 expr, type);
6836 if (TYPE_PTR_P (type))
6837 inform (loc, "it must be the address of a function "
6838 "with external linkage");
6839 else
6840 inform (loc, "it must be the name of a function with "
6841 "external linkage");
6843 return NULL_TREE;
6846 linkage = decl_linkage (fn_no_ptr);
6847 if ((cxx_dialect < cxx11 && linkage != lk_external)
6848 || (cxx_dialect < cxx17 && linkage == lk_none))
6850 if (complain & tf_error)
6852 location_t loc = cp_expr_loc_or_input_loc (expr);
6853 if (cxx_dialect >= cxx11)
6854 error_at (loc, "%qE is not a valid template argument for type "
6855 "%qT because %qD has no linkage",
6856 expr, type, fn_no_ptr);
6857 else
6858 error_at (loc, "%qE is not a valid template argument for type "
6859 "%qT because %qD does not have external linkage",
6860 expr, type, fn_no_ptr);
6862 return NULL_TREE;
6865 accept:
6866 if (TYPE_REF_P (type))
6868 if (REFERENCE_REF_P (fn))
6869 fn = TREE_OPERAND (fn, 0);
6870 else
6871 fn = build_address (fn);
6873 if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (fn)))
6874 fn = build_nop (type, fn);
6876 return fn;
6879 /* Subroutine of convert_nontype_argument.
6880 Check if EXPR of type TYPE is a valid pointer-to-member constant.
6881 Emit an error otherwise. */
6883 static bool
6884 check_valid_ptrmem_cst_expr (tree type, tree expr,
6885 tsubst_flags_t complain)
6887 tree orig_expr = expr;
6888 STRIP_NOPS (expr);
6889 if (null_ptr_cst_p (expr))
6890 return true;
6891 if (TREE_CODE (expr) == PTRMEM_CST
6892 && same_type_p (TYPE_PTRMEM_CLASS_TYPE (type),
6893 PTRMEM_CST_CLASS (expr)))
6894 return true;
6895 if (cxx_dialect >= cxx11 && null_member_pointer_value_p (expr))
6896 return true;
6897 if (processing_template_decl
6898 && TREE_CODE (expr) == ADDR_EXPR
6899 && TREE_CODE (TREE_OPERAND (expr, 0)) == OFFSET_REF)
6900 return true;
6901 if (complain & tf_error)
6903 location_t loc = cp_expr_loc_or_input_loc (orig_expr);
6904 error_at (loc, "%qE is not a valid template argument for type %qT",
6905 orig_expr, type);
6906 if (TREE_CODE (expr) != PTRMEM_CST)
6907 inform (loc, "it must be a pointer-to-member of the form %<&X::Y%>");
6908 else
6909 inform (loc, "because it is a member of %qT", PTRMEM_CST_CLASS (expr));
6911 return false;
6914 /* Returns TRUE iff the address of OP is value-dependent.
6916 14.6.2.4 [temp.dep.temp]:
6917 A non-integral non-type template-argument is dependent if its type is
6918 dependent or it has either of the following forms
6919 qualified-id
6920 & qualified-id
6921 and contains a nested-name-specifier which specifies a class-name that
6922 names a dependent type.
6924 We generalize this to just say that the address of a member of a
6925 dependent class is value-dependent; the above doesn't cover the
6926 address of a static data member named with an unqualified-id. */
6928 static bool
6929 has_value_dependent_address (tree op)
6931 STRIP_ANY_LOCATION_WRAPPER (op);
6933 /* We could use get_inner_reference here, but there's no need;
6934 this is only relevant for template non-type arguments, which
6935 can only be expressed as &id-expression. */
6936 if (DECL_P (op))
6938 tree ctx = CP_DECL_CONTEXT (op);
6940 if (TYPE_P (ctx) && dependent_type_p (ctx))
6941 return true;
6943 if (VAR_P (op)
6944 && TREE_STATIC (op)
6945 && TREE_CODE (ctx) == FUNCTION_DECL
6946 && type_dependent_expression_p (ctx))
6947 return true;
6950 return false;
6953 /* The next set of functions are used for providing helpful explanatory
6954 diagnostics for failed overload resolution. Their messages should be
6955 indented by two spaces for consistency with the messages in
6956 call.cc */
6958 static int
6959 unify_success (bool /*explain_p*/)
6961 return 0;
6964 /* Other failure functions should call this one, to provide a single function
6965 for setting a breakpoint on. */
6967 static int
6968 unify_invalid (bool /*explain_p*/)
6970 return 1;
6973 static int
6974 unify_parameter_deduction_failure (bool explain_p, tree parm)
6976 if (explain_p)
6977 inform (input_location,
6978 " couldn%'t deduce template parameter %qD", parm);
6979 return unify_invalid (explain_p);
6982 static int
6983 unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
6985 if (explain_p)
6986 inform (input_location,
6987 " types %qT and %qT have incompatible cv-qualifiers",
6988 parm, arg);
6989 return unify_invalid (explain_p);
6992 static int
6993 unify_type_mismatch (bool explain_p, tree parm, tree arg)
6995 if (explain_p)
6996 inform (input_location, " mismatched types %qT and %qT", parm, arg);
6997 return unify_invalid (explain_p);
7000 static int
7001 unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
7003 if (explain_p)
7004 inform (input_location,
7005 " template parameter %qD is not a parameter pack, but "
7006 "argument %qD is",
7007 parm, arg);
7008 return unify_invalid (explain_p);
7011 static int
7012 unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
7014 if (explain_p)
7015 inform (input_location,
7016 " template argument %qE does not match "
7017 "pointer-to-member constant %qE",
7018 arg, parm);
7019 return unify_invalid (explain_p);
7022 static int
7023 unify_expression_unequal (bool explain_p, tree parm, tree arg)
7025 if (explain_p)
7026 inform (input_location, " %qE is not equivalent to %qE", parm, arg);
7027 return unify_invalid (explain_p);
7030 static int
7031 unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
7033 if (explain_p)
7034 inform (input_location,
7035 " inconsistent parameter pack deduction with %qT and %qT",
7036 old_arg, new_arg);
7037 return unify_invalid (explain_p);
7040 static int
7041 unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
7043 if (explain_p)
7045 if (TYPE_P (parm))
7046 inform (input_location,
7047 " deduced conflicting types for parameter %qT (%qT and %qT)",
7048 parm, first, second);
7049 else
7050 inform (input_location,
7051 " deduced conflicting values for non-type parameter "
7052 "%qE (%qE and %qE)", parm, first, second);
7054 return unify_invalid (explain_p);
7057 static int
7058 unify_vla_arg (bool explain_p, tree arg)
7060 if (explain_p)
7061 inform (input_location,
7062 " variable-sized array type %qT is not "
7063 "a valid template argument",
7064 arg);
7065 return unify_invalid (explain_p);
7068 static int
7069 unify_method_type_error (bool explain_p, tree arg)
7071 if (explain_p)
7072 inform (input_location,
7073 " member function type %qT is not a valid template argument",
7074 arg);
7075 return unify_invalid (explain_p);
7078 static int
7079 unify_arity (bool explain_p, int have, int wanted, bool least_p = false)
7081 if (explain_p)
7083 if (least_p)
7084 inform_n (input_location, wanted,
7085 " candidate expects at least %d argument, %d provided",
7086 " candidate expects at least %d arguments, %d provided",
7087 wanted, have);
7088 else
7089 inform_n (input_location, wanted,
7090 " candidate expects %d argument, %d provided",
7091 " candidate expects %d arguments, %d provided",
7092 wanted, have);
7094 return unify_invalid (explain_p);
7097 static int
7098 unify_too_many_arguments (bool explain_p, int have, int wanted)
7100 return unify_arity (explain_p, have, wanted);
7103 static int
7104 unify_too_few_arguments (bool explain_p, int have, int wanted,
7105 bool least_p = false)
7107 return unify_arity (explain_p, have, wanted, least_p);
7110 static int
7111 unify_arg_conversion (bool explain_p, tree to_type,
7112 tree from_type, tree arg)
7114 if (explain_p)
7115 inform (cp_expr_loc_or_input_loc (arg),
7116 " cannot convert %qE (type %qT) to type %qT",
7117 arg, from_type, to_type);
7118 return unify_invalid (explain_p);
7121 static int
7122 unify_no_common_base (bool explain_p, enum template_base_result r,
7123 tree parm, tree arg)
7125 if (explain_p)
7126 switch (r)
7128 case tbr_ambiguous_baseclass:
7129 inform (input_location, " %qT is an ambiguous base class of %qT",
7130 parm, arg);
7131 break;
7132 default:
7133 inform (input_location, " %qT is not derived from %qT", arg, parm);
7134 break;
7136 return unify_invalid (explain_p);
7139 static int
7140 unify_inconsistent_template_template_parameters (bool explain_p)
7142 if (explain_p)
7143 inform (input_location,
7144 " template parameters of a template template argument are "
7145 "inconsistent with other deduced template arguments");
7146 return unify_invalid (explain_p);
7149 static int
7150 unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
7152 if (explain_p)
7153 inform (input_location,
7154 " cannot deduce a template for %qT from non-template type %qT",
7155 parm, arg);
7156 return unify_invalid (explain_p);
7159 static int
7160 unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
7162 if (explain_p)
7163 inform (input_location,
7164 " template argument %qE does not match %qE", arg, parm);
7165 return unify_invalid (explain_p);
7168 /* Subroutine of convert_nontype_argument, to check whether EXPR, as an
7169 argument for TYPE, points to an unsuitable object.
7171 Also adjust the type of the index in C++20 array subobject references. */
7173 static bool
7174 invalid_tparm_referent_p (tree type, tree expr, tsubst_flags_t complain)
7176 switch (TREE_CODE (expr))
7178 CASE_CONVERT:
7179 return invalid_tparm_referent_p (type, TREE_OPERAND (expr, 0),
7180 complain);
7182 case TARGET_EXPR:
7183 return invalid_tparm_referent_p (type, TARGET_EXPR_INITIAL (expr),
7184 complain);
7186 case CONSTRUCTOR:
7188 for (auto &e: CONSTRUCTOR_ELTS (expr))
7189 if (invalid_tparm_referent_p (TREE_TYPE (e.value), e.value, complain))
7190 return true;
7192 break;
7194 case ADDR_EXPR:
7196 tree decl = TREE_OPERAND (expr, 0);
7198 if (cxx_dialect >= cxx20)
7199 while (TREE_CODE (decl) == COMPONENT_REF
7200 || TREE_CODE (decl) == ARRAY_REF)
7202 tree &op = TREE_OPERAND (decl, 1);
7203 if (TREE_CODE (decl) == ARRAY_REF
7204 && TREE_CODE (op) == INTEGER_CST)
7205 /* Canonicalize array offsets to ptrdiff_t; how they were
7206 written doesn't matter for subobject identity. */
7207 op = fold_convert (ptrdiff_type_node, op);
7208 decl = TREE_OPERAND (decl, 0);
7211 if (!VAR_OR_FUNCTION_DECL_P (decl))
7213 if (complain & tf_error)
7214 error_at (cp_expr_loc_or_input_loc (expr),
7215 "%qE is not a valid template argument of type %qT "
7216 "because %qE is not a variable or function",
7217 expr, type, decl);
7218 return true;
7220 else if (cxx_dialect < cxx11 && !DECL_EXTERNAL_LINKAGE_P (decl))
7222 if (complain & tf_error)
7223 error_at (cp_expr_loc_or_input_loc (expr),
7224 "%qE is not a valid template argument of type %qT "
7225 "in C++98 because %qD does not have external linkage",
7226 expr, type, decl);
7227 return true;
7229 else if ((cxx_dialect >= cxx11 && cxx_dialect < cxx17)
7230 && decl_linkage (decl) == lk_none)
7232 if (complain & tf_error)
7233 error_at (cp_expr_loc_or_input_loc (expr),
7234 "%qE is not a valid template argument of type %qT "
7235 "because %qD has no linkage", expr, type, decl);
7236 return true;
7238 /* C++17: For a non-type template-parameter of reference or pointer
7239 type, the value of the constant expression shall not refer to (or
7240 for a pointer type, shall not be the address of):
7241 * a subobject (4.5),
7242 * a temporary object (15.2),
7243 * a string literal (5.13.5),
7244 * the result of a typeid expression (8.2.8), or
7245 * a predefined __func__ variable (11.4.1). */
7246 else if (VAR_P (decl) && DECL_ARTIFICIAL (decl)
7247 && !DECL_NTTP_OBJECT_P (decl))
7249 gcc_checking_assert (DECL_TINFO_P (decl) || DECL_FNAME_P (decl));
7250 if (complain & tf_error)
7251 error ("the address of %qD is not a valid template argument",
7252 decl);
7253 return true;
7255 else if (cxx_dialect < cxx20
7256 && !(same_type_ignoring_top_level_qualifiers_p
7257 (strip_array_types (TREE_TYPE (type)),
7258 strip_array_types (TREE_TYPE (decl)))))
7260 if (complain & tf_error)
7261 error ("the address of the %qT subobject of %qD is not a "
7262 "valid template argument", TREE_TYPE (type), decl);
7263 return true;
7265 else if (!TREE_STATIC (decl) && !DECL_EXTERNAL (decl))
7267 if (complain & tf_error)
7268 error ("the address of %qD is not a valid template argument "
7269 "because it does not have static storage duration",
7270 decl);
7271 return true;
7274 break;
7276 default:
7277 if (!INDIRECT_TYPE_P (type))
7278 /* We're only concerned about pointers and references here. */;
7279 else if (cxx_dialect >= cxx11 && integer_zerop (expr))
7280 /* Null pointer values are OK in C++11. */;
7281 else
7283 if (VAR_P (expr))
7285 if (complain & tf_error)
7286 error ("%qD is not a valid template argument "
7287 "because %qD is a variable, not the address of "
7288 "a variable", expr, expr);
7289 return true;
7291 else
7293 if (complain & tf_error)
7294 error ("%qE is not a valid template argument for %qT "
7295 "because it is not the address of a variable",
7296 expr, type);
7297 return true;
7301 return false;
7305 /* Return a VAR_DECL for the C++20 template parameter object corresponding to
7306 template argument EXPR. */
7308 static tree
7309 create_template_parm_object (tree expr, tsubst_flags_t complain)
7311 if (TREE_CODE (expr) == TARGET_EXPR)
7312 expr = TARGET_EXPR_INITIAL (expr);
7314 if (!TREE_CONSTANT (expr))
7316 if ((complain & tf_error)
7317 && require_rvalue_constant_expression (expr))
7318 cxx_constant_value (expr);
7319 return error_mark_node;
7321 if (invalid_tparm_referent_p (TREE_TYPE (expr), expr, complain))
7322 return error_mark_node;
7324 /* This is no longer a compound literal. */
7325 gcc_assert (!TREE_HAS_CONSTRUCTOR (expr));
7327 return get_template_parm_object (expr, mangle_template_parm_object (expr));
7330 /* The template arguments corresponding to template parameter objects of types
7331 that contain pointers to members. */
7333 static GTY(()) hash_map<tree, tree> *tparm_obj_values;
7335 /* Find or build an nttp object for (already-validated) EXPR with name
7336 NAME. */
7338 tree
7339 get_template_parm_object (tree expr, tree name)
7341 tree decl = get_global_binding (name);
7342 if (decl)
7343 return decl;
7345 tree type = cp_build_qualified_type (TREE_TYPE (expr), TYPE_QUAL_CONST);
7346 decl = create_temporary_var (type);
7347 DECL_NTTP_OBJECT_P (decl) = true;
7348 DECL_CONTEXT (decl) = NULL_TREE;
7349 TREE_STATIC (decl) = true;
7350 DECL_DECLARED_CONSTEXPR_P (decl) = true;
7351 TREE_READONLY (decl) = true;
7352 DECL_NAME (decl) = name;
7353 SET_DECL_ASSEMBLER_NAME (decl, name);
7354 comdat_linkage (decl);
7356 if (!zero_init_p (type))
7358 /* If EXPR contains any PTRMEM_CST, they will get clobbered by
7359 lower_var_init before we're done mangling. So store the original
7360 value elsewhere. */
7361 tree copy = unshare_constructor (expr);
7362 hash_map_safe_put<hm_ggc> (tparm_obj_values, decl, copy);
7365 pushdecl_top_level_and_finish (decl, expr);
7367 return decl;
7370 /* Return the actual template argument corresponding to template parameter
7371 object VAR. */
7373 tree
7374 tparm_object_argument (tree var)
7376 if (zero_init_p (TREE_TYPE (var)))
7377 return DECL_INITIAL (var);
7378 return *(tparm_obj_values->get (var));
7381 /* Attempt to convert the non-type template parameter EXPR to the
7382 indicated TYPE. If the conversion is successful, return the
7383 converted value. If the conversion is unsuccessful, return
7384 NULL_TREE if we issued an error message, or error_mark_node if we
7385 did not. We issue error messages for out-and-out bad template
7386 parameters, but not simply because the conversion failed, since we
7387 might be just trying to do argument deduction. Both TYPE and EXPR
7388 must be non-dependent.
7390 The conversion follows the special rules described in
7391 [temp.arg.nontype], and it is much more strict than an implicit
7392 conversion.
7394 This function is called twice for each template argument (see
7395 lookup_template_class for a more accurate description of this
7396 problem). This means that we need to handle expressions which
7397 are not valid in a C++ source, but can be created from the
7398 first call (for instance, casts to perform conversions). These
7399 hacks can go away after we fix the double coercion problem. */
7401 static tree
7402 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
7404 tree expr_type;
7405 location_t loc = cp_expr_loc_or_input_loc (expr);
7407 /* Detect immediately string literals as invalid non-type argument.
7408 This special-case is not needed for correctness (we would easily
7409 catch this later), but only to provide better diagnostic for this
7410 common user mistake. As suggested by DR 100, we do not mention
7411 linkage issues in the diagnostic as this is not the point. */
7412 if (TREE_CODE (expr) == STRING_CST && !CLASS_TYPE_P (type))
7414 if (complain & tf_error)
7415 error ("%qE is not a valid template argument for type %qT "
7416 "because string literals can never be used in this context",
7417 expr, type);
7418 return NULL_TREE;
7421 /* Add the ADDR_EXPR now for the benefit of
7422 value_dependent_expression_p. */
7423 if (TYPE_PTROBV_P (type)
7424 && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
7426 expr = decay_conversion (expr, complain);
7427 if (expr == error_mark_node)
7428 return error_mark_node;
7431 /* If we are in a template, EXPR may be non-dependent, but still
7432 have a syntactic, rather than semantic, form. For example, EXPR
7433 might be a SCOPE_REF, rather than the VAR_DECL to which the
7434 SCOPE_REF refers. Preserving the qualifying scope is necessary
7435 so that access checking can be performed when the template is
7436 instantiated -- but here we need the resolved form so that we can
7437 convert the argument. */
7438 bool non_dep = false;
7439 if (TYPE_REF_OBJ_P (type)
7440 && has_value_dependent_address (expr))
7441 /* If we want the address and it's value-dependent, don't fold. */;
7442 else if (processing_template_decl
7443 && !instantiation_dependent_expression_p (expr))
7444 non_dep = true;
7445 if (error_operand_p (expr))
7446 return error_mark_node;
7447 expr_type = TREE_TYPE (expr);
7449 /* If the argument is non-dependent, perform any conversions in
7450 non-dependent context as well. */
7451 processing_template_decl_sentinel s (non_dep);
7452 if (non_dep)
7453 expr = instantiate_non_dependent_expr_internal (expr, complain);
7455 bool val_dep_p = value_dependent_expression_p (expr);
7456 if (val_dep_p)
7457 expr = canonicalize_expr_argument (expr, complain);
7458 else
7459 STRIP_ANY_LOCATION_WRAPPER (expr);
7461 /* 14.3.2/5: The null pointer{,-to-member} conversion is applied
7462 to a non-type argument of "nullptr". */
7463 if (NULLPTR_TYPE_P (expr_type) && TYPE_PTR_OR_PTRMEM_P (type))
7464 expr = fold_simple (convert (type, expr));
7466 /* In C++11, integral or enumeration non-type template arguments can be
7467 arbitrary constant expressions. Pointer and pointer to
7468 member arguments can be general constant expressions that evaluate
7469 to a null value, but otherwise still need to be of a specific form. */
7470 if (cxx_dialect >= cxx11)
7472 if (TREE_CODE (expr) == PTRMEM_CST && TYPE_PTRMEM_P (type))
7473 /* A PTRMEM_CST is already constant, and a valid template
7474 argument for a parameter of pointer to member type, we just want
7475 to leave it in that form rather than lower it to a
7476 CONSTRUCTOR. */;
7477 else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
7478 || cxx_dialect >= cxx17)
7480 /* C++17: A template-argument for a non-type template-parameter shall
7481 be a converted constant expression (8.20) of the type of the
7482 template-parameter. */
7483 expr = build_converted_constant_expr (type, expr, complain);
7484 if (expr == error_mark_node)
7485 /* Make sure we return NULL_TREE only if we have really issued
7486 an error, as described above. */
7487 return (complain & tf_error) ? NULL_TREE : error_mark_node;
7488 else if (TREE_CODE (expr) == IMPLICIT_CONV_EXPR)
7490 IMPLICIT_CONV_EXPR_NONTYPE_ARG (expr) = true;
7491 return expr;
7493 expr = maybe_constant_value (expr, NULL_TREE, mce_true);
7494 expr = convert_from_reference (expr);
7495 /* EXPR may have become value-dependent. */
7496 val_dep_p = value_dependent_expression_p (expr);
7498 else if (TYPE_PTR_OR_PTRMEM_P (type))
7500 tree folded = maybe_constant_value (expr, NULL_TREE, mce_true);
7501 if (TYPE_PTR_P (type) ? integer_zerop (folded)
7502 : null_member_pointer_value_p (folded))
7503 expr = folded;
7507 if (TYPE_REF_P (type))
7508 expr = mark_lvalue_use (expr);
7509 else
7510 expr = mark_rvalue_use (expr);
7512 /* HACK: Due to double coercion, we can get a
7513 NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
7514 which is the tree that we built on the first call (see
7515 below when coercing to reference to object or to reference to
7516 function). We just strip everything and get to the arg.
7517 See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
7518 for examples. */
7519 if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
7521 /* Check this before we strip *& to avoid redundancy. */
7522 if (!mark_single_function (expr, complain))
7523 return error_mark_node;
7525 tree probe_type, probe = expr;
7526 if (REFERENCE_REF_P (probe))
7527 probe = TREE_OPERAND (probe, 0);
7528 probe_type = TREE_TYPE (probe);
7529 if (TREE_CODE (probe) == NOP_EXPR)
7531 /* ??? Maybe we could use convert_from_reference here, but we
7532 would need to relax its constraints because the NOP_EXPR
7533 could actually change the type to something more cv-qualified,
7534 and this is not folded by convert_from_reference. */
7535 tree addr = TREE_OPERAND (probe, 0);
7536 if (TYPE_REF_P (probe_type)
7537 && TREE_CODE (addr) == ADDR_EXPR
7538 && TYPE_PTR_P (TREE_TYPE (addr))
7539 && (same_type_ignoring_top_level_qualifiers_p
7540 (TREE_TYPE (probe_type),
7541 TREE_TYPE (TREE_TYPE (addr)))))
7543 expr = TREE_OPERAND (addr, 0);
7544 expr_type = TREE_TYPE (probe_type);
7549 /* [temp.arg.nontype]/5, bullet 1
7551 For a non-type template-parameter of integral or enumeration type,
7552 integral promotions (_conv.prom_) and integral conversions
7553 (_conv.integral_) are applied. */
7554 if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
7555 || SCALAR_FLOAT_TYPE_P (type))
7557 if (cxx_dialect < cxx11)
7559 tree t = build_converted_constant_expr (type, expr, complain);
7560 t = maybe_constant_value (t);
7561 if (t != error_mark_node)
7562 expr = t;
7565 if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
7566 return error_mark_node;
7568 /* Notice that there are constant expressions like '4 % 0' which
7569 do not fold into integer constants. */
7570 if (!CONSTANT_CLASS_P (expr) && !val_dep_p)
7572 if (complain & tf_error)
7574 int errs = errorcount, warns = warningcount + werrorcount;
7575 if (!require_potential_constant_expression (expr))
7576 expr = error_mark_node;
7577 else
7578 expr = cxx_constant_value (expr);
7579 if (errorcount > errs || warningcount + werrorcount > warns)
7580 inform (loc, "in template argument for type %qT", type);
7581 if (expr == error_mark_node)
7582 return NULL_TREE;
7583 /* else cxx_constant_value complained but gave us
7584 a real constant, so go ahead. */
7585 if (!CONSTANT_CLASS_P (expr))
7587 /* Some assemble time constant expressions like
7588 (intptr_t)&&lab1 - (intptr_t)&&lab2 or
7589 4 + (intptr_t)&&var satisfy reduced_constant_expression_p
7590 as we can emit them into .rodata initializers of
7591 variables, yet they can't fold into an INTEGER_CST at
7592 compile time. Refuse them here. */
7593 gcc_checking_assert (reduced_constant_expression_p (expr));
7594 error_at (loc, "template argument %qE for type %qT not "
7595 "a compile-time constant", expr, type);
7596 return NULL_TREE;
7599 else
7600 return NULL_TREE;
7603 /* Avoid typedef problems. */
7604 if (TREE_TYPE (expr) != type)
7605 expr = fold_convert (type, expr);
7607 /* [temp.arg.nontype]/5, bullet 2
7609 For a non-type template-parameter of type pointer to object,
7610 qualification conversions (_conv.qual_) and the array-to-pointer
7611 conversion (_conv.array_) are applied. */
7612 else if (TYPE_PTROBV_P (type))
7614 tree decayed = expr;
7616 /* Look through any NOP_EXPRs around an ADDR_EXPR, whether they come from
7617 decay_conversion or an explicit cast. If it's a problematic cast,
7618 we'll complain about it below. */
7619 if (TREE_CODE (expr) == NOP_EXPR)
7621 tree probe = expr;
7622 STRIP_NOPS (probe);
7623 if (TREE_CODE (probe) == ADDR_EXPR
7624 && TYPE_PTR_P (TREE_TYPE (probe)))
7626 expr = probe;
7627 expr_type = TREE_TYPE (expr);
7631 /* [temp.arg.nontype]/1 (TC1 version, DR 49):
7633 A template-argument for a non-type, non-template template-parameter
7634 shall be one of: [...]
7636 -- the name of a non-type template-parameter;
7637 -- the address of an object or function with external linkage, [...]
7638 expressed as "& id-expression" where the & is optional if the name
7639 refers to a function or array, or if the corresponding
7640 template-parameter is a reference.
7642 Here, we do not care about functions, as they are invalid anyway
7643 for a parameter of type pointer-to-object. */
7645 if (val_dep_p)
7646 /* Non-type template parameters are OK. */
7648 else if (cxx_dialect >= cxx11 && integer_zerop (expr))
7649 /* Null pointer values are OK in C++11. */;
7650 else if (TREE_CODE (expr) != ADDR_EXPR
7651 && !INDIRECT_TYPE_P (expr_type))
7652 /* Other values, like integer constants, might be valid
7653 non-type arguments of some other type. */
7654 return error_mark_node;
7655 else if (invalid_tparm_referent_p (type, expr, complain))
7656 return NULL_TREE;
7658 expr = decayed;
7660 expr = perform_qualification_conversions (type, expr);
7661 if (expr == error_mark_node)
7662 return error_mark_node;
7664 /* [temp.arg.nontype]/5, bullet 3
7666 For a non-type template-parameter of type reference to object, no
7667 conversions apply. The type referred to by the reference may be more
7668 cv-qualified than the (otherwise identical) type of the
7669 template-argument. The template-parameter is bound directly to the
7670 template-argument, which must be an lvalue. */
7671 else if (TYPE_REF_OBJ_P (type))
7673 if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
7674 expr_type))
7675 return error_mark_node;
7677 if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
7679 if (complain & tf_error)
7680 error ("%qE is not a valid template argument for type %qT "
7681 "because of conflicts in cv-qualification", expr, type);
7682 return NULL_TREE;
7685 if (!lvalue_p (expr))
7687 if (complain & tf_error)
7688 error ("%qE is not a valid template argument for type %qT "
7689 "because it is not an lvalue", expr, type);
7690 return NULL_TREE;
7693 /* [temp.arg.nontype]/1
7695 A template-argument for a non-type, non-template template-parameter
7696 shall be one of: [...]
7698 -- the address of an object or function with external linkage. */
7699 if (INDIRECT_REF_P (expr)
7700 && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
7702 expr = TREE_OPERAND (expr, 0);
7703 if (DECL_P (expr))
7705 if (complain & tf_error)
7706 error ("%q#D is not a valid template argument for type %qT "
7707 "because a reference variable does not have a constant "
7708 "address", expr, type);
7709 return NULL_TREE;
7713 if (TYPE_REF_OBJ_P (TREE_TYPE (expr)) && val_dep_p)
7714 /* OK, dependent reference. We don't want to ask whether a DECL is
7715 itself value-dependent, since what we want here is its address. */;
7716 else
7718 expr = build_address (expr);
7720 if (invalid_tparm_referent_p (type, expr, complain))
7721 return NULL_TREE;
7724 if (!same_type_p (type, TREE_TYPE (expr)))
7725 expr = build_nop (type, expr);
7727 /* [temp.arg.nontype]/5, bullet 4
7729 For a non-type template-parameter of type pointer to function, only
7730 the function-to-pointer conversion (_conv.func_) is applied. If the
7731 template-argument represents a set of overloaded functions (or a
7732 pointer to such), the matching function is selected from the set
7733 (_over.over_). */
7734 else if (TYPE_PTRFN_P (type))
7736 /* If the argument is a template-id, we might not have enough
7737 context information to decay the pointer. */
7738 if (!type_unknown_p (expr_type))
7740 expr = decay_conversion (expr, complain);
7741 if (expr == error_mark_node)
7742 return error_mark_node;
7745 if (cxx_dialect >= cxx11 && integer_zerop (expr))
7746 /* Null pointer values are OK in C++11. */
7747 return perform_qualification_conversions (type, expr);
7749 expr = convert_nontype_argument_function (type, expr, complain);
7750 if (!expr || expr == error_mark_node)
7751 return expr;
7753 /* [temp.arg.nontype]/5, bullet 5
7755 For a non-type template-parameter of type reference to function, no
7756 conversions apply. If the template-argument represents a set of
7757 overloaded functions, the matching function is selected from the set
7758 (_over.over_). */
7759 else if (TYPE_REFFN_P (type))
7761 if (TREE_CODE (expr) == ADDR_EXPR)
7763 if (complain & tf_error)
7765 error ("%qE is not a valid template argument for type %qT "
7766 "because it is a pointer", expr, type);
7767 inform (input_location, "try using %qE instead",
7768 TREE_OPERAND (expr, 0));
7770 return NULL_TREE;
7773 expr = convert_nontype_argument_function (type, expr, complain);
7774 if (!expr || expr == error_mark_node)
7775 return expr;
7777 /* [temp.arg.nontype]/5, bullet 6
7779 For a non-type template-parameter of type pointer to member function,
7780 no conversions apply. If the template-argument represents a set of
7781 overloaded member functions, the matching member function is selected
7782 from the set (_over.over_). */
7783 else if (TYPE_PTRMEMFUNC_P (type))
7785 expr = instantiate_type (type, expr, tf_none);
7786 if (expr == error_mark_node)
7787 return error_mark_node;
7789 /* [temp.arg.nontype] bullet 1 says the pointer to member
7790 expression must be a pointer-to-member constant. */
7791 if (!val_dep_p
7792 && !check_valid_ptrmem_cst_expr (type, expr, complain))
7793 return NULL_TREE;
7795 /* Repeated conversion can't deal with a conversion that turns PTRMEM_CST
7796 into a CONSTRUCTOR, so build up a new PTRMEM_CST instead. */
7797 if (fnptr_conv_p (type, TREE_TYPE (expr)))
7798 expr = make_ptrmem_cst (type, PTRMEM_CST_MEMBER (expr));
7800 /* [temp.arg.nontype]/5, bullet 7
7802 For a non-type template-parameter of type pointer to data member,
7803 qualification conversions (_conv.qual_) are applied. */
7804 else if (TYPE_PTRDATAMEM_P (type))
7806 /* [temp.arg.nontype] bullet 1 says the pointer to member
7807 expression must be a pointer-to-member constant. */
7808 if (!val_dep_p
7809 && !check_valid_ptrmem_cst_expr (type, expr, complain))
7810 return NULL_TREE;
7812 expr = perform_qualification_conversions (type, expr);
7813 if (expr == error_mark_node)
7814 return expr;
7816 else if (NULLPTR_TYPE_P (type))
7818 if (!NULLPTR_TYPE_P (TREE_TYPE (expr)))
7820 if (complain & tf_error)
7821 error ("%qE is not a valid template argument for type %qT "
7822 "because it is of type %qT", expr, type, TREE_TYPE (expr));
7823 return NULL_TREE;
7825 return expr;
7827 else if (CLASS_TYPE_P (type))
7829 /* Replace the argument with a reference to the corresponding template
7830 parameter object. */
7831 if (!val_dep_p)
7832 expr = create_template_parm_object (expr, complain);
7833 if (expr == error_mark_node)
7834 return NULL_TREE;
7836 /* A template non-type parameter must be one of the above. */
7837 else
7838 gcc_unreachable ();
7840 /* Sanity check: did we actually convert the argument to the
7841 right type? */
7842 gcc_assert (same_type_ignoring_top_level_qualifiers_p
7843 (type, TREE_TYPE (expr)));
7844 return convert_from_reference (expr);
7847 /* Subroutine of coerce_template_template_parms, which returns 1 if
7848 PARM_PARM and ARG_PARM match using the rule for the template
7849 parameters of template template parameters. Both PARM and ARG are
7850 template parameters; the rest of the arguments are the same as for
7851 coerce_template_template_parms.
7853 static int
7854 coerce_template_template_parm (tree parm,
7855 tree arg,
7856 tsubst_flags_t complain,
7857 tree in_decl,
7858 tree outer_args)
7860 if (arg == NULL_TREE || error_operand_p (arg)
7861 || parm == NULL_TREE || error_operand_p (parm))
7862 return 0;
7864 if (TREE_CODE (arg) != TREE_CODE (parm))
7865 return 0;
7867 switch (TREE_CODE (parm))
7869 case TEMPLATE_DECL:
7870 /* We encounter instantiations of templates like
7871 template <template <template <class> class> class TT>
7872 class C; */
7874 if (!coerce_template_template_parms
7875 (parm, arg, complain, in_decl, outer_args))
7876 return 0;
7878 /* Fall through. */
7880 case TYPE_DECL:
7881 if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
7882 && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
7883 /* Argument is a parameter pack but parameter is not. */
7884 return 0;
7885 break;
7887 case PARM_DECL:
7888 /* The tsubst call is used to handle cases such as
7890 template <int> class C {};
7891 template <class T, template <T> class TT> class D {};
7892 D<int, C> d;
7894 i.e. the parameter list of TT depends on earlier parameters. */
7895 if (!uses_template_parms (TREE_TYPE (arg)))
7897 tree t = tsubst (TREE_TYPE (parm), outer_args, complain, in_decl);
7898 if (!uses_template_parms (t)
7899 && !same_type_p (t, TREE_TYPE (arg)))
7900 return 0;
7903 if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
7904 && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
7905 /* Argument is a parameter pack but parameter is not. */
7906 return 0;
7908 break;
7910 default:
7911 gcc_unreachable ();
7914 return 1;
7917 /* Coerce template argument list ARGLIST for use with template
7918 template-parameter TEMPL. */
7920 static tree
7921 coerce_template_args_for_ttp (tree templ, tree arglist,
7922 tsubst_flags_t complain)
7924 /* Consider an example where a template template parameter declared as
7926 template <class T, class U = std::allocator<T> > class TT
7928 The template parameter level of T and U are one level larger than
7929 of TT. To proper process the default argument of U, say when an
7930 instantiation `TT<int>' is seen, we need to build the full
7931 arguments containing {int} as the innermost level. Outer levels,
7932 available when not appearing as default template argument, can be
7933 obtained from the arguments of the enclosing template.
7935 Suppose that TT is later substituted with std::vector. The above
7936 instantiation is `TT<int, std::allocator<T> >' with TT at
7937 level 1, and T at level 2, while the template arguments at level 1
7938 becomes {std::vector} and the inner level 2 is {int}. */
7940 tree outer = DECL_CONTEXT (templ);
7941 if (outer)
7942 outer = generic_targs_for (outer);
7943 else if (current_template_parms)
7945 /* This is an argument of the current template, so we haven't set
7946 DECL_CONTEXT yet. We can also get here when level-lowering a
7947 bound ttp. */
7948 tree relevant_template_parms;
7950 /* Parameter levels that are greater than the level of the given
7951 template template parm are irrelevant. */
7952 relevant_template_parms = current_template_parms;
7953 while (TMPL_PARMS_DEPTH (relevant_template_parms)
7954 != TEMPLATE_TYPE_LEVEL (TREE_TYPE (templ)))
7955 relevant_template_parms = TREE_CHAIN (relevant_template_parms);
7957 outer = template_parms_to_args (relevant_template_parms);
7960 if (outer)
7961 arglist = add_to_template_args (outer, arglist);
7963 tree parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
7964 return coerce_template_parms (parmlist, arglist, templ, complain);
7967 /* A cache of template template parameters with match-all default
7968 arguments. */
7969 static GTY((deletable)) hash_map<tree,tree> *defaulted_ttp_cache;
7971 /* T is a bound template template-parameter. Copy its arguments into default
7972 arguments of the template template-parameter's template parameters. */
7974 static tree
7975 add_defaults_to_ttp (tree otmpl)
7977 if (tree *c = hash_map_safe_get (defaulted_ttp_cache, otmpl))
7978 return *c;
7980 tree ntmpl = copy_node (otmpl);
7982 tree ntype = copy_node (TREE_TYPE (otmpl));
7983 TYPE_STUB_DECL (ntype) = TYPE_NAME (ntype) = ntmpl;
7984 TYPE_MAIN_VARIANT (ntype) = ntype;
7985 TYPE_POINTER_TO (ntype) = TYPE_REFERENCE_TO (ntype) = NULL_TREE;
7986 TYPE_NAME (ntype) = ntmpl;
7987 SET_TYPE_STRUCTURAL_EQUALITY (ntype);
7989 tree idx = TEMPLATE_TYPE_PARM_INDEX (ntype)
7990 = copy_node (TEMPLATE_TYPE_PARM_INDEX (ntype));
7991 TEMPLATE_PARM_DECL (idx) = ntmpl;
7992 TREE_TYPE (ntmpl) = TREE_TYPE (idx) = ntype;
7994 tree oparms = DECL_TEMPLATE_PARMS (otmpl);
7995 tree parms = DECL_TEMPLATE_PARMS (ntmpl) = copy_node (oparms);
7996 TREE_CHAIN (parms) = TREE_CHAIN (oparms);
7997 tree vec = TREE_VALUE (parms) = copy_node (TREE_VALUE (parms));
7998 for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
8000 tree o = TREE_VEC_ELT (vec, i);
8001 if (!template_parameter_pack_p (TREE_VALUE (o)))
8003 tree n = TREE_VEC_ELT (vec, i) = copy_node (o);
8004 TREE_PURPOSE (n) = any_targ_node;
8008 tree oresult = DECL_TEMPLATE_RESULT (otmpl);
8009 tree gen_otmpl = DECL_TI_TEMPLATE (oresult);
8010 tree gen_ntmpl;
8011 if (gen_otmpl == otmpl)
8012 gen_ntmpl = ntmpl;
8013 else
8014 gen_ntmpl = add_defaults_to_ttp (gen_otmpl);
8016 tree nresult = copy_decl (oresult);
8017 DECL_TEMPLATE_INFO (nresult)
8018 = build_template_info (gen_ntmpl, TI_ARGS (DECL_TEMPLATE_INFO (oresult)));
8019 DECL_TEMPLATE_RESULT (ntmpl) = nresult;
8021 hash_map_safe_put<hm_ggc> (defaulted_ttp_cache, otmpl, ntmpl);
8022 return ntmpl;
8025 /* ARG is a bound potential template template-argument, and PARGS is a list
8026 of arguments for the corresponding template template-parameter. Adjust
8027 PARGS as appropriate for application to ARG's template, and if ARG is a
8028 BOUND_TEMPLATE_TEMPLATE_PARM, possibly adjust it to add default template
8029 arguments to the template template parameter. */
8031 static tree
8032 coerce_ttp_args_for_tta (tree& arg, tree pargs, tsubst_flags_t complain)
8034 ++processing_template_decl;
8035 tree arg_tmpl = TYPE_TI_TEMPLATE (arg);
8036 if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
8038 /* When comparing two template template-parameters in partial ordering,
8039 rewrite the one currently being used as an argument to have default
8040 arguments for all parameters. */
8041 arg_tmpl = add_defaults_to_ttp (arg_tmpl);
8042 pargs = coerce_template_args_for_ttp (arg_tmpl, pargs, complain);
8043 if (pargs != error_mark_node)
8044 arg = bind_template_template_parm (TREE_TYPE (arg_tmpl),
8045 TYPE_TI_ARGS (arg));
8047 else
8049 tree aparms
8050 = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (arg_tmpl));
8051 pargs = coerce_template_parms (aparms, pargs, arg_tmpl, complain);
8053 --processing_template_decl;
8054 return pargs;
8057 /* Subroutine of unify for the case when PARM is a
8058 BOUND_TEMPLATE_TEMPLATE_PARM. */
8060 static int
8061 unify_bound_ttp_args (tree tparms, tree targs, tree parm, tree& arg,
8062 bool explain_p)
8064 tree parmvec = TYPE_TI_ARGS (parm);
8065 tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
8067 /* The template template parm might be variadic and the argument
8068 not, so flatten both argument lists. */
8069 parmvec = expand_template_argument_pack (parmvec);
8070 argvec = expand_template_argument_pack (argvec);
8072 if (flag_new_ttp)
8074 /* In keeping with P0522R0, adjust P's template arguments
8075 to apply to A's template; then flatten it again. */
8076 tree nparmvec = coerce_ttp_args_for_tta (arg, parmvec, tf_none);
8077 nparmvec = expand_template_argument_pack (nparmvec);
8079 if (unify (tparms, targs, nparmvec, argvec,
8080 UNIFY_ALLOW_NONE, explain_p))
8081 return 1;
8083 /* If the P0522 adjustment eliminated a pack expansion, deduce
8084 empty packs. */
8085 if (flag_new_ttp
8086 && TREE_VEC_LENGTH (nparmvec) < TREE_VEC_LENGTH (parmvec)
8087 && unify_pack_expansion (tparms, targs, parmvec, argvec,
8088 DEDUCE_EXACT, /*sub*/true, explain_p))
8089 return 1;
8091 else
8093 /* Deduce arguments T, i from TT<T> or TT<i>.
8094 We check each element of PARMVEC and ARGVEC individually
8095 rather than the whole TREE_VEC since they can have
8096 different number of elements, which is allowed under N2555. */
8098 int len = TREE_VEC_LENGTH (parmvec);
8100 /* Check if the parameters end in a pack, making them
8101 variadic. */
8102 int parm_variadic_p = 0;
8103 if (len > 0
8104 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
8105 parm_variadic_p = 1;
8107 for (int i = 0; i < len - parm_variadic_p; ++i)
8108 /* If the template argument list of P contains a pack
8109 expansion that is not the last template argument, the
8110 entire template argument list is a non-deduced
8111 context. */
8112 if (PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, i)))
8113 return unify_success (explain_p);
8115 if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
8116 return unify_too_few_arguments (explain_p,
8117 TREE_VEC_LENGTH (argvec), len);
8119 for (int i = 0; i < len - parm_variadic_p; ++i)
8120 if (unify (tparms, targs,
8121 TREE_VEC_ELT (parmvec, i),
8122 TREE_VEC_ELT (argvec, i),
8123 UNIFY_ALLOW_NONE, explain_p))
8124 return 1;
8126 if (parm_variadic_p
8127 && unify_pack_expansion (tparms, targs,
8128 parmvec, argvec,
8129 DEDUCE_EXACT,
8130 /*subr=*/true, explain_p))
8131 return 1;
8134 return 0;
8137 /* Return 1 if PARM_TMPL and ARG_TMPL match using rule for
8138 template template parameters.
8140 Consider the example:
8141 template <class T> class A;
8142 template<template <class U> class TT> class B;
8144 For B<A>, PARM_TMPL is TT, while ARG_TMPL is A,
8145 and OUTER_ARGS contains A. */
8147 static int
8148 coerce_template_template_parms (tree parm_tmpl,
8149 tree arg_tmpl,
8150 tsubst_flags_t complain,
8151 tree in_decl,
8152 tree outer_args)
8154 int nparms, nargs, i;
8155 tree parm, arg;
8156 int variadic_p = 0;
8158 tree parm_parms = DECL_INNERMOST_TEMPLATE_PARMS (parm_tmpl);
8159 tree arg_parms = DECL_INNERMOST_TEMPLATE_PARMS (arg_tmpl);
8160 tree gen_arg_tmpl = most_general_template (arg_tmpl);
8161 tree gen_arg_parms = DECL_INNERMOST_TEMPLATE_PARMS (gen_arg_tmpl);
8163 nparms = TREE_VEC_LENGTH (parm_parms);
8164 nargs = TREE_VEC_LENGTH (arg_parms);
8166 if (flag_new_ttp)
8168 /* P0522R0: A template template-parameter P is at least as specialized as
8169 a template template-argument A if, given the following rewrite to two
8170 function templates, the function template corresponding to P is at
8171 least as specialized as the function template corresponding to A
8172 according to the partial ordering rules for function templates
8173 ([temp.func.order]). Given an invented class template X with the
8174 template parameter list of A (including default arguments):
8176 * Each of the two function templates has the same template parameters,
8177 respectively, as P or A.
8179 * Each function template has a single function parameter whose type is
8180 a specialization of X with template arguments corresponding to the
8181 template parameters from the respective function template where, for
8182 each template parameter PP in the template parameter list of the
8183 function template, a corresponding template argument AA is formed. If
8184 PP declares a parameter pack, then AA is the pack expansion
8185 PP... ([temp.variadic]); otherwise, AA is the id-expression PP.
8187 If the rewrite produces an invalid type, then P is not at least as
8188 specialized as A. */
8190 /* So coerce P's args to apply to A's parms, and then deduce between A's
8191 args and the converted args. If that succeeds, A is at least as
8192 specialized as P, so they match.*/
8193 processing_template_decl_sentinel ptds (/*reset*/false);
8194 ++processing_template_decl;
8196 tree pargs = template_parms_level_to_args (parm_parms);
8198 /* PARM and ARG might be at different template depths, and we want to
8199 pass the right additional levels of args when coercing PARGS to
8200 ARG_PARMS in case we need to do any substitution into non-type
8201 template parameter types.
8203 OUTER_ARGS are not the right outer levels in this case, as they are
8204 the args we're building up for PARM, and for the coercion we want the
8205 args for ARG. If DECL_CONTEXT isn't set for a template template
8206 parameter, we can assume that it's in the current scope. */
8207 tree ctx = DECL_CONTEXT (arg_tmpl);
8208 if (!ctx && DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
8209 ctx = current_scope ();
8210 tree scope_args = NULL_TREE;
8211 if (tree tinfo = get_template_info (ctx))
8212 scope_args = TI_ARGS (tinfo);
8213 if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
8215 int level = TEMPLATE_TYPE_LEVEL (TREE_TYPE (gen_arg_tmpl));
8216 int scope_depth = TMPL_ARGS_DEPTH (scope_args);
8217 tree full_pargs = make_tree_vec (level + 1);
8219 /* Only use as many levels from the scope as needed
8220 (excluding the level of ARG). */
8221 for (int i = 0; i < level - 1; ++i)
8222 if (i < scope_depth)
8223 TREE_VEC_ELT (full_pargs, i) = TMPL_ARGS_LEVEL (scope_args, i + 1);
8224 else
8225 TREE_VEC_ELT (full_pargs, i) = make_tree_vec (0);
8227 /* Add the arguments that appear at the levels of ARG. */
8228 tree adjacent = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (arg_tmpl));
8229 adjacent = TMPL_ARGS_LEVEL (adjacent, TMPL_ARGS_DEPTH (adjacent) - 1);
8230 TREE_VEC_ELT (full_pargs, level - 1) = adjacent;
8232 TREE_VEC_ELT (full_pargs, level) = pargs;
8233 pargs = full_pargs;
8235 else
8236 pargs = add_to_template_args (scope_args, pargs);
8238 pargs = coerce_template_parms (gen_arg_parms, pargs,
8239 NULL_TREE, tf_none);
8240 if (pargs != error_mark_node)
8242 tree targs = make_tree_vec (nargs);
8243 tree aargs = template_parms_level_to_args (arg_parms);
8244 if (!unify (arg_parms, targs, aargs, pargs, UNIFY_ALLOW_NONE,
8245 /*explain*/false))
8246 return 1;
8250 /* Determine whether we have a parameter pack at the end of the
8251 template template parameter's template parameter list. */
8252 if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
8254 parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
8256 if (error_operand_p (parm))
8257 return 0;
8259 switch (TREE_CODE (parm))
8261 case TEMPLATE_DECL:
8262 case TYPE_DECL:
8263 if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
8264 variadic_p = 1;
8265 break;
8267 case PARM_DECL:
8268 if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
8269 variadic_p = 1;
8270 break;
8272 default:
8273 gcc_unreachable ();
8277 if (nargs != nparms
8278 && !(variadic_p && nargs >= nparms - 1))
8279 return 0;
8281 /* Check all of the template parameters except the parameter pack at
8282 the end (if any). */
8283 for (i = 0; i < nparms - variadic_p; ++i)
8285 if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
8286 || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
8287 continue;
8289 parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
8290 arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
8292 if (!coerce_template_template_parm (parm, arg, complain, in_decl,
8293 outer_args))
8294 return 0;
8298 if (variadic_p)
8300 /* Check each of the template parameters in the template
8301 argument against the template parameter pack at the end of
8302 the template template parameter. */
8303 if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
8304 return 0;
8306 parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
8308 for (; i < nargs; ++i)
8310 if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
8311 continue;
8313 arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
8315 if (!coerce_template_template_parm (parm, arg, complain, in_decl,
8316 outer_args))
8317 return 0;
8321 return 1;
8324 /* Verifies that the deduced template arguments (in TARGS) for the
8325 template template parameters (in TPARMS) represent valid bindings,
8326 by comparing the template parameter list of each template argument
8327 to the template parameter list of its corresponding template
8328 template parameter, in accordance with DR150. This
8329 routine can only be called after all template arguments have been
8330 deduced. It will return TRUE if all of the template template
8331 parameter bindings are okay, FALSE otherwise. */
8332 bool
8333 template_template_parm_bindings_ok_p (tree tparms, tree targs)
8335 int i, ntparms = TREE_VEC_LENGTH (tparms);
8336 bool ret = true;
8338 /* We're dealing with template parms in this process. */
8339 ++processing_template_decl;
8341 targs = INNERMOST_TEMPLATE_ARGS (targs);
8343 for (i = 0; i < ntparms; ++i)
8345 tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
8346 tree targ = TREE_VEC_ELT (targs, i);
8348 if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
8350 tree packed_args = NULL_TREE;
8351 int idx, len = 1;
8353 if (ARGUMENT_PACK_P (targ))
8355 /* Look inside the argument pack. */
8356 packed_args = ARGUMENT_PACK_ARGS (targ);
8357 len = TREE_VEC_LENGTH (packed_args);
8360 for (idx = 0; idx < len; ++idx)
8362 if (packed_args)
8363 /* Extract the next argument from the argument
8364 pack. */
8365 targ = TREE_VEC_ELT (packed_args, idx);
8367 if (PACK_EXPANSION_P (targ))
8368 /* Look at the pattern of the pack expansion. */
8369 targ = PACK_EXPANSION_PATTERN (targ);
8371 /* Extract the template parameters from the template
8372 argument. */
8373 if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
8374 targ = TYPE_NAME (targ);
8376 /* Verify that we can coerce the template template
8377 parameters from the template argument to the template
8378 parameter. This requires an exact match. */
8379 if (TREE_CODE (targ) == TEMPLATE_DECL
8380 && !coerce_template_template_parms
8381 (tparm,
8382 targ,
8383 tf_none,
8384 tparm,
8385 targs))
8387 ret = false;
8388 goto out;
8394 out:
8396 --processing_template_decl;
8397 return ret;
8400 /* Since type attributes aren't mangled, we need to strip them from
8401 template type arguments. */
8403 tree
8404 canonicalize_type_argument (tree arg, tsubst_flags_t complain)
8406 if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
8407 return arg;
8408 bool removed_attributes = false;
8409 tree canon = strip_typedefs (arg, &removed_attributes);
8410 if (removed_attributes
8411 && (complain & tf_warning))
8412 warning (OPT_Wignored_attributes,
8413 "ignoring attributes on template argument %qT", arg);
8414 return canon;
8417 /* And from inside dependent non-type arguments like sizeof(Type). */
8419 static tree
8420 canonicalize_expr_argument (tree arg, tsubst_flags_t complain)
8422 if (!arg || arg == error_mark_node)
8423 return arg;
8424 bool removed_attributes = false;
8425 tree canon = strip_typedefs_expr (arg, &removed_attributes);
8426 if (removed_attributes
8427 && (complain & tf_warning))
8428 warning (OPT_Wignored_attributes,
8429 "ignoring attributes in template argument %qE", arg);
8430 return canon;
8433 /* A template declaration can be substituted for a constrained
8434 template template parameter only when the argument is no more
8435 constrained than the parameter. */
8437 static bool
8438 is_compatible_template_arg (tree parm, tree arg, tree args)
8440 tree parm_cons = get_constraints (parm);
8442 /* For now, allow constrained template template arguments
8443 and unconstrained template template parameters. */
8444 if (parm_cons == NULL_TREE)
8445 return true;
8447 /* If the template parameter is constrained, we need to rewrite its
8448 constraints in terms of the ARG's template parameters. This ensures
8449 that all of the template parameter types will have the same depth.
8451 Note that this is only valid when coerce_template_template_parm is
8452 true for the innermost template parameters of PARM and ARG. In other
8453 words, because coercion is successful, this conversion will be valid. */
8454 tree new_args = NULL_TREE;
8455 if (parm_cons)
8457 tree aparms = DECL_INNERMOST_TEMPLATE_PARMS (arg);
8458 new_args = template_parms_level_to_args (aparms);
8459 new_args = add_to_template_args (args, new_args);
8460 ++processing_template_decl;
8461 parm_cons = tsubst_constraint_info (parm_cons, new_args,
8462 tf_none, NULL_TREE);
8463 --processing_template_decl;
8464 if (parm_cons == error_mark_node)
8465 return false;
8468 return weakly_subsumes (parm_cons, arg);
8471 // Convert a placeholder argument into a binding to the original
8472 // parameter. The original parameter is saved as the TREE_TYPE of
8473 // ARG.
8474 static inline tree
8475 convert_wildcard_argument (tree parm, tree arg)
8477 TREE_TYPE (arg) = parm;
8478 return arg;
8481 /* We can't fully resolve ARG given as a non-type template argument to TYPE,
8482 because one of them is dependent. But we need to represent the
8483 conversion for the benefit of cp_tree_equal. */
8485 static tree
8486 maybe_convert_nontype_argument (tree type, tree arg, bool force)
8488 /* Auto parms get no conversion. */
8489 if (type_uses_auto (type))
8490 return arg;
8491 /* ??? Do we need to push the IMPLICIT_CONV_EXPR into the pack expansion?
8492 That would complicate other things, and it doesn't seem necessary. */
8493 if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
8494 return arg;
8495 /* We don't need or want to add this conversion now if we're going to use the
8496 argument for deduction. */
8497 if (!value_dependent_expression_p (arg))
8498 force = false;
8499 else if (!force)
8500 return arg;
8502 type = cv_unqualified (type);
8503 tree argtype = TREE_TYPE (arg);
8504 if (argtype && same_type_p (type, argtype))
8505 return arg;
8507 arg = build1 (IMPLICIT_CONV_EXPR, type, arg);
8508 IMPLICIT_CONV_EXPR_NONTYPE_ARG (arg) = true;
8509 IMPLICIT_CONV_EXPR_FORCED (arg) = force;
8510 return arg;
8513 /* Convert the indicated template ARG as necessary to match the
8514 indicated template PARM. Returns the converted ARG, or
8515 error_mark_node if the conversion was unsuccessful. Error and
8516 warning messages are issued under control of COMPLAIN. This
8517 conversion is for the Ith parameter in the parameter list. ARGS is
8518 the full set of template arguments deduced so far. */
8520 static tree
8521 convert_template_argument (tree parm,
8522 tree arg,
8523 tree args,
8524 tsubst_flags_t complain,
8525 int i,
8526 tree in_decl)
8528 tree orig_arg;
8529 tree val;
8530 int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
8532 if (parm == error_mark_node || error_operand_p (arg))
8533 return error_mark_node;
8535 /* Trivially convert placeholders. */
8536 if (TREE_CODE (arg) == WILDCARD_DECL)
8537 return convert_wildcard_argument (parm, arg);
8539 if (arg == any_targ_node)
8540 return arg;
8542 if (TREE_CODE (arg) == TREE_LIST
8543 && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
8545 /* The template argument was the name of some
8546 member function. That's usually
8547 invalid, but static members are OK. In any
8548 case, grab the underlying fields/functions
8549 and issue an error later if required. */
8550 TREE_TYPE (arg) = unknown_type_node;
8553 orig_arg = arg;
8555 requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
8556 requires_type = (TREE_CODE (parm) == TYPE_DECL
8557 || requires_tmpl_type);
8559 /* When determining whether an argument pack expansion is a template,
8560 look at the pattern. */
8561 if (PACK_EXPANSION_P (arg))
8562 arg = PACK_EXPANSION_PATTERN (arg);
8564 /* Deal with an injected-class-name used as a template template arg. */
8565 if (requires_tmpl_type && CLASS_TYPE_P (arg))
8567 tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
8568 if (TREE_CODE (t) == TEMPLATE_DECL)
8570 if (cxx_dialect >= cxx11)
8571 /* OK under DR 1004. */;
8572 else if (complain & tf_warning_or_error)
8573 pedwarn (input_location, OPT_Wpedantic, "injected-class-name %qD"
8574 " used as template template argument", TYPE_NAME (arg));
8575 else if (flag_pedantic_errors)
8576 t = arg;
8578 arg = t;
8582 is_tmpl_type =
8583 ((TREE_CODE (arg) == TEMPLATE_DECL
8584 && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
8585 || (requires_tmpl_type && TREE_CODE (arg) == TYPE_ARGUMENT_PACK)
8586 || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
8587 || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
8589 if (is_tmpl_type
8590 && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
8591 || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
8592 arg = TYPE_STUB_DECL (arg);
8594 is_type = TYPE_P (arg) || is_tmpl_type;
8596 if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
8597 && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
8599 if (TREE_CODE (TREE_OPERAND (arg, 1)) == BIT_NOT_EXPR)
8601 if (complain & tf_error)
8602 error ("invalid use of destructor %qE as a type", orig_arg);
8603 return error_mark_node;
8606 permerror (input_location,
8607 "to refer to a type member of a template parameter, "
8608 "use %<typename %E%>", orig_arg);
8610 orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
8611 TREE_OPERAND (arg, 1),
8612 typename_type,
8613 complain);
8614 arg = orig_arg;
8615 is_type = 1;
8617 if (is_type != requires_type)
8619 if (in_decl)
8621 if (complain & tf_error)
8623 error ("type/value mismatch at argument %d in template "
8624 "parameter list for %qD",
8625 i + 1, in_decl);
8626 if (is_type)
8628 /* The template argument is a type, but we're expecting
8629 an expression. */
8630 inform (input_location,
8631 " expected a constant of type %qT, got %qT",
8632 TREE_TYPE (parm),
8633 (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
8634 /* [temp.arg]/2: "In a template-argument, an ambiguity
8635 between a type-id and an expression is resolved to a
8636 type-id, regardless of the form of the corresponding
8637 template-parameter." So give the user a clue. */
8638 if (TREE_CODE (arg) == FUNCTION_TYPE)
8639 inform (input_location, " ambiguous template argument "
8640 "for non-type template parameter is treated as "
8641 "function type");
8643 else if (requires_tmpl_type)
8644 inform (input_location,
8645 " expected a class template, got %qE", orig_arg);
8646 else
8647 inform (input_location,
8648 " expected a type, got %qE", orig_arg);
8651 return error_mark_node;
8653 if (is_tmpl_type ^ requires_tmpl_type)
8655 if (in_decl && (complain & tf_error))
8657 error ("type/value mismatch at argument %d in template "
8658 "parameter list for %qD",
8659 i + 1, in_decl);
8660 if (is_tmpl_type)
8661 inform (input_location,
8662 " expected a type, got %qT", DECL_NAME (arg));
8663 else
8664 inform (input_location,
8665 " expected a class template, got %qT", orig_arg);
8667 return error_mark_node;
8670 if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
8671 /* We already did the appropriate conversion when packing args. */
8672 val = orig_arg;
8673 else if (is_type)
8675 if (requires_tmpl_type)
8677 if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
8678 /* The number of argument required is not known yet.
8679 Just accept it for now. */
8680 val = orig_arg;
8681 else
8683 /* Strip alias templates that are equivalent to another
8684 template. */
8685 arg = get_underlying_template (arg);
8687 if (coerce_template_template_parms (parm, arg,
8688 complain, in_decl,
8689 args))
8691 val = arg;
8693 /* TEMPLATE_TEMPLATE_PARM node is preferred over
8694 TEMPLATE_DECL. */
8695 if (val != error_mark_node)
8697 if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
8698 val = TREE_TYPE (val);
8699 if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
8700 val = make_pack_expansion (val, complain);
8703 else
8705 if (in_decl && (complain & tf_error))
8707 error ("type/value mismatch at argument %d in "
8708 "template parameter list for %qD",
8709 i + 1, in_decl);
8710 inform (input_location,
8711 " expected a template of type %qD, got %qT",
8712 parm, orig_arg);
8715 val = error_mark_node;
8718 // Check that the constraints are compatible before allowing the
8719 // substitution.
8720 if (val != error_mark_node)
8721 if (!is_compatible_template_arg (parm, arg, args))
8723 if (in_decl && (complain & tf_error))
8725 error ("constraint mismatch at argument %d in "
8726 "template parameter list for %qD",
8727 i + 1, in_decl);
8728 inform (input_location, " expected %qD but got %qD",
8729 parm, arg);
8731 val = error_mark_node;
8735 else
8736 val = orig_arg;
8737 /* We only form one instance of each template specialization.
8738 Therefore, if we use a non-canonical variant (i.e., a
8739 typedef), any future messages referring to the type will use
8740 the typedef, which is confusing if those future uses do not
8741 themselves also use the typedef. */
8742 if (TYPE_P (val))
8743 val = canonicalize_type_argument (val, complain);
8745 else
8747 tree t = TREE_TYPE (parm);
8749 if (TEMPLATE_PARM_LEVEL (get_template_parm_index (parm))
8750 > TMPL_ARGS_DEPTH (args))
8751 /* We don't have enough levels of args to do any substitution. This
8752 can happen in the context of -fnew-ttp-matching. */;
8753 else if (tree a = type_uses_auto (t))
8755 t = do_auto_deduction (t, arg, a, complain, adc_unify, args,
8756 LOOKUP_IMPLICIT, /*tmpl=*/in_decl);
8757 if (t == error_mark_node)
8758 return error_mark_node;
8760 else
8761 t = tsubst (t, args, complain, in_decl);
8763 /* Perform array-to-pointer and function-to-pointer conversion
8764 as per [temp.param]/10. */
8765 t = type_decays_to (t);
8767 if (invalid_nontype_parm_type_p (t, complain))
8768 return error_mark_node;
8770 /* Drop top-level cv-qualifiers on the substituted/deduced type of
8771 this non-type template parameter, as per [temp.param]/6. */
8772 t = cv_unqualified (t);
8774 if (t != TREE_TYPE (parm))
8775 t = canonicalize_type_argument (t, complain);
8777 /* We need to handle arguments for alias or concept templates
8778 differently: we need to force building an IMPLICIT_CONV_EXPR, because
8779 these arguments are going to be substituted directly into the
8780 dependent type; they might not get another chance at
8781 convert_nontype_argument. But if the argument ends up here again for
8782 a template that isn't one of those, remove the conversion for
8783 consistency between naming the same dependent type directly or through
8784 an alias. */
8785 bool force_conv = in_decl && (DECL_ALIAS_TEMPLATE_P (in_decl)
8786 || concept_definition_p (in_decl));
8787 if (!force_conv
8788 && TREE_CODE (orig_arg) == IMPLICIT_CONV_EXPR
8789 && IMPLICIT_CONV_EXPR_FORCED (orig_arg)
8790 && same_type_p (TREE_TYPE (orig_arg), t))
8791 orig_arg = TREE_OPERAND (orig_arg, 0);
8793 if (!type_dependent_expression_p (orig_arg)
8794 && !uses_template_parms (t))
8795 /* We used to call digest_init here. However, digest_init
8796 will report errors, which we don't want when complain
8797 is zero. More importantly, digest_init will try too
8798 hard to convert things: for example, `0' should not be
8799 converted to pointer type at this point according to
8800 the standard. Accepting this is not merely an
8801 extension, since deciding whether or not these
8802 conversions can occur is part of determining which
8803 function template to call, or whether a given explicit
8804 argument specification is valid. */
8805 val = convert_nontype_argument (t, orig_arg, complain);
8806 else
8808 val = canonicalize_expr_argument (orig_arg, complain);
8809 val = maybe_convert_nontype_argument (t, val, force_conv);
8812 if (val == NULL_TREE)
8813 val = error_mark_node;
8814 else if (val == error_mark_node && (complain & tf_error))
8815 error_at (cp_expr_loc_or_input_loc (orig_arg),
8816 "could not convert template argument %qE from %qT to %qT",
8817 orig_arg, TREE_TYPE (orig_arg), t);
8819 if (INDIRECT_REF_P (val))
8821 /* Reject template arguments that are references to built-in
8822 functions with no library fallbacks. */
8823 const_tree inner = TREE_OPERAND (val, 0);
8824 const_tree innertype = TREE_TYPE (inner);
8825 if (innertype
8826 && TYPE_REF_P (innertype)
8827 && TREE_CODE (TREE_TYPE (innertype)) == FUNCTION_TYPE
8828 && TREE_OPERAND_LENGTH (inner) > 0
8829 && reject_gcc_builtin (TREE_OPERAND (inner, 0)))
8830 return error_mark_node;
8833 if (TREE_CODE (val) == SCOPE_REF)
8835 /* Strip typedefs from the SCOPE_REF. */
8836 tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
8837 tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
8838 complain);
8839 val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
8840 QUALIFIED_NAME_IS_TEMPLATE (val));
8844 return val;
8847 /* Coerces the remaining template arguments in INNER_ARGS (from
8848 ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
8849 Returns the coerced argument pack. PARM_IDX is the position of this
8850 parameter in the template parameter list. ARGS is the original
8851 template argument list. */
8852 static tree
8853 coerce_template_parameter_pack (tree parms,
8854 int parm_idx,
8855 tree args,
8856 tree inner_args,
8857 int arg_idx,
8858 tree new_args,
8859 int* lost,
8860 tree in_decl,
8861 tsubst_flags_t complain)
8863 tree parm = TREE_VEC_ELT (parms, parm_idx);
8864 int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8865 tree packed_args;
8866 tree argument_pack;
8867 tree packed_parms = NULL_TREE;
8869 if (arg_idx > nargs)
8870 arg_idx = nargs;
8872 if (tree packs = fixed_parameter_pack_p (TREE_VALUE (parm)))
8874 /* When the template parameter is a non-type template parameter pack
8875 or template template parameter pack whose type or template
8876 parameters use parameter packs, we know exactly how many arguments
8877 we are looking for. Build a vector of the instantiated decls for
8878 these template parameters in PACKED_PARMS. */
8879 /* We can't use make_pack_expansion here because it would interpret a
8880 _DECL as a use rather than a declaration. */
8881 tree decl = TREE_VALUE (parm);
8882 tree exp = cxx_make_type (TYPE_PACK_EXPANSION);
8883 PACK_EXPANSION_PATTERN (exp) = decl;
8884 PACK_EXPANSION_PARAMETER_PACKS (exp) = packs;
8885 SET_TYPE_STRUCTURAL_EQUALITY (exp);
8887 TREE_VEC_LENGTH (args)--;
8888 packed_parms = tsubst_pack_expansion (exp, args, complain, decl);
8889 TREE_VEC_LENGTH (args)++;
8891 if (packed_parms == error_mark_node)
8892 return error_mark_node;
8894 /* If we're doing a partial instantiation of a member template,
8895 verify that all of the types used for the non-type
8896 template parameter pack are, in fact, valid for non-type
8897 template parameters. */
8898 if (arg_idx < nargs
8899 && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
8901 int j, len = TREE_VEC_LENGTH (packed_parms);
8902 for (j = 0; j < len; ++j)
8904 tree t = TREE_VEC_ELT (packed_parms, j);
8905 if (TREE_CODE (t) == PARM_DECL
8906 && invalid_nontype_parm_type_p (TREE_TYPE (t), complain))
8907 return error_mark_node;
8909 /* We don't know how many args we have yet, just
8910 use the unconverted ones for now. */
8911 return NULL_TREE;
8914 packed_args = make_tree_vec (TREE_VEC_LENGTH (packed_parms));
8916 /* Check if we have a placeholder pack, which indicates we're
8917 in the context of a introduction list. In that case we want
8918 to match this pack to the single placeholder. */
8919 else if (arg_idx < nargs
8920 && TREE_CODE (TREE_VEC_ELT (inner_args, arg_idx)) == WILDCARD_DECL
8921 && WILDCARD_PACK_P (TREE_VEC_ELT (inner_args, arg_idx)))
8923 nargs = arg_idx + 1;
8924 packed_args = make_tree_vec (1);
8926 else
8927 packed_args = make_tree_vec (nargs - arg_idx);
8929 /* Convert the remaining arguments, which will be a part of the
8930 parameter pack "parm". */
8931 int first_pack_arg = arg_idx;
8932 for (; arg_idx < nargs; ++arg_idx)
8934 tree arg = TREE_VEC_ELT (inner_args, arg_idx);
8935 tree actual_parm = TREE_VALUE (parm);
8936 int pack_idx = arg_idx - first_pack_arg;
8938 if (packed_parms)
8940 /* Once we've packed as many args as we have types, stop. */
8941 if (pack_idx >= TREE_VEC_LENGTH (packed_parms))
8942 break;
8943 else if (PACK_EXPANSION_P (arg))
8944 /* We don't know how many args we have yet, just
8945 use the unconverted ones for now. */
8946 return NULL_TREE;
8947 else
8948 actual_parm = TREE_VEC_ELT (packed_parms, pack_idx);
8951 if (arg == error_mark_node)
8953 if (complain & tf_error)
8954 error ("template argument %d is invalid", arg_idx + 1);
8956 else
8957 arg = convert_template_argument (actual_parm,
8958 arg, new_args, complain, parm_idx,
8959 in_decl);
8960 if (arg == error_mark_node)
8961 (*lost)++;
8962 TREE_VEC_ELT (packed_args, pack_idx) = arg;
8965 if (arg_idx - first_pack_arg < TREE_VEC_LENGTH (packed_args)
8966 && TREE_VEC_LENGTH (packed_args) > 0)
8968 if (complain & tf_error)
8969 error ("wrong number of template arguments (%d, should be %d)",
8970 arg_idx - first_pack_arg, TREE_VEC_LENGTH (packed_args));
8971 return error_mark_node;
8974 if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
8975 || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
8976 argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
8977 else
8979 argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
8980 TREE_CONSTANT (argument_pack) = 1;
8983 ARGUMENT_PACK_ARGS (argument_pack) = packed_args;
8984 if (CHECKING_P)
8985 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
8986 TREE_VEC_LENGTH (packed_args));
8987 return argument_pack;
8990 /* Returns the number of pack expansions in the template argument vector
8991 ARGS. */
8993 static int
8994 pack_expansion_args_count (tree args)
8996 int i;
8997 int count = 0;
8998 if (args)
8999 for (i = 0; i < TREE_VEC_LENGTH (args); ++i)
9001 tree elt = TREE_VEC_ELT (args, i);
9002 if (elt && PACK_EXPANSION_P (elt))
9003 ++count;
9005 return count;
9008 /* Convert all template arguments to their appropriate types, and
9009 return a vector containing the innermost resulting template
9010 arguments. If any error occurs, return error_mark_node. Error and
9011 warning messages are issued under control of COMPLAIN.
9013 If PARMS represents all template parameters levels, this function
9014 returns a vector of vectors representing all the resulting argument
9015 levels. Note that in this case, only the innermost arguments are
9016 coerced because the outermost ones are supposed to have been coerced
9017 already. Otherwise, if PARMS represents only (the innermost) vector
9018 of parameters, this function returns a vector containing just the
9019 innermost resulting arguments.
9021 If REQUIRE_ALL_ARGS is false, argument deduction will be performed
9022 for arguments not specified in ARGS. If REQUIRE_ALL_ARGS is true,
9023 arguments not specified in ARGS must have default arguments which
9024 we'll use to fill in ARGS. */
9026 tree
9027 coerce_template_parms (tree parms,
9028 tree args,
9029 tree in_decl,
9030 tsubst_flags_t complain,
9031 bool require_all_args /* = true */)
9033 int nparms, nargs, parm_idx, arg_idx, lost = 0;
9034 tree orig_inner_args;
9035 tree inner_args;
9037 /* When used as a boolean value, indicates whether this is a
9038 variadic template parameter list. Since it's an int, we can also
9039 subtract it from nparms to get the number of non-variadic
9040 parameters. */
9041 int variadic_p = 0;
9042 int variadic_args_p = 0;
9043 int post_variadic_parms = 0;
9045 /* Adjustment to nparms for fixed parameter packs. */
9046 int fixed_pack_adjust = 0;
9047 int fixed_packs = 0;
9048 int missing = 0;
9050 /* Likewise for parameters with default arguments. */
9051 int default_p = 0;
9053 if (args == error_mark_node)
9054 return error_mark_node;
9056 bool return_full_args = false;
9057 if (TREE_CODE (parms) == TREE_LIST)
9059 if (TMPL_PARMS_DEPTH (parms) > 1)
9061 gcc_assert (TMPL_PARMS_DEPTH (parms) == TMPL_ARGS_DEPTH (args));
9062 return_full_args = true;
9064 parms = INNERMOST_TEMPLATE_PARMS (parms);
9067 nparms = TREE_VEC_LENGTH (parms);
9069 /* Determine if there are any parameter packs or default arguments. */
9070 for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
9072 tree parm = TREE_VEC_ELT (parms, parm_idx);
9073 if (variadic_p)
9074 ++post_variadic_parms;
9075 if (template_parameter_pack_p (TREE_VALUE (parm)))
9076 ++variadic_p;
9077 if (TREE_PURPOSE (parm))
9078 ++default_p;
9081 inner_args = orig_inner_args = INNERMOST_TEMPLATE_ARGS (args);
9082 /* If there are no parameters that follow a parameter pack, we need to
9083 expand any argument packs so that we can deduce a parameter pack from
9084 some non-packed args followed by an argument pack, as in variadic85.C.
9085 If there are such parameters, we need to leave argument packs intact
9086 so the arguments are assigned properly. This can happen when dealing
9087 with a nested class inside a partial specialization of a class
9088 template, as in variadic92.C, or when deducing a template parameter pack
9089 from a sub-declarator, as in variadic114.C. */
9090 if (!post_variadic_parms)
9091 inner_args = expand_template_argument_pack (inner_args);
9093 /* Count any pack expansion args. */
9094 variadic_args_p = pack_expansion_args_count (inner_args);
9096 nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
9097 if ((nargs - variadic_args_p > nparms && !variadic_p)
9098 || (nargs < nparms - variadic_p
9099 && require_all_args
9100 && !variadic_args_p
9101 && (TREE_VEC_ELT (parms, nargs) != error_mark_node
9102 && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs)))))
9104 bad_nargs:
9105 if (complain & tf_error)
9107 if (variadic_p || default_p)
9109 nparms -= variadic_p + default_p;
9110 error ("wrong number of template arguments "
9111 "(%d, should be at least %d)", nargs, nparms);
9113 else
9114 error ("wrong number of template arguments "
9115 "(%d, should be %d)", nargs, nparms);
9117 if (in_decl)
9118 inform (DECL_SOURCE_LOCATION (in_decl),
9119 "provided for %qD", in_decl);
9122 return error_mark_node;
9124 /* We can't pass a pack expansion to a non-pack parameter of an alias
9125 template (DR 1430). */
9126 else if (in_decl
9127 && (DECL_ALIAS_TEMPLATE_P (in_decl)
9128 || concept_definition_p (in_decl))
9129 && variadic_args_p
9130 && nargs - variadic_args_p < nparms - variadic_p)
9132 if (complain & tf_error)
9134 for (int i = 0; i < TREE_VEC_LENGTH (inner_args); ++i)
9136 tree arg = TREE_VEC_ELT (inner_args, i);
9137 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
9139 if (PACK_EXPANSION_P (arg)
9140 && !template_parameter_pack_p (parm))
9142 if (DECL_ALIAS_TEMPLATE_P (in_decl))
9143 error_at (location_of (arg),
9144 "pack expansion argument for non-pack parameter "
9145 "%qD of alias template %qD", parm, in_decl);
9146 else
9147 error_at (location_of (arg),
9148 "pack expansion argument for non-pack parameter "
9149 "%qD of concept %qD", parm, in_decl);
9150 inform (DECL_SOURCE_LOCATION (parm), "declared here");
9151 goto found;
9154 gcc_unreachable ();
9155 found:;
9157 return error_mark_node;
9160 /* We need to evaluate the template arguments, even though this
9161 template-id may be nested within a "sizeof". */
9162 cp_evaluated ev;
9164 tree new_args = add_outermost_template_args (args, make_tree_vec (nparms));
9165 tree& new_inner_args = TMPL_ARGS_LEVEL (new_args, TMPL_ARGS_DEPTH (new_args));
9166 int pack_adjust = 0;
9167 for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
9169 tree arg;
9170 tree parm;
9172 /* Get the Ith template parameter. */
9173 parm = TREE_VEC_ELT (parms, parm_idx);
9175 if (parm == error_mark_node)
9177 TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
9178 continue;
9181 /* Calculate the next argument. */
9182 if (arg_idx < nargs)
9183 arg = TREE_VEC_ELT (inner_args, arg_idx);
9184 else
9185 arg = NULL_TREE;
9187 if (template_parameter_pack_p (TREE_VALUE (parm))
9188 && (arg || require_all_args || !(complain & tf_partial))
9189 && !(arg && ARGUMENT_PACK_P (arg)))
9191 /* Some arguments will be placed in the
9192 template parameter pack PARM. */
9193 arg = coerce_template_parameter_pack (parms, parm_idx, args,
9194 inner_args, arg_idx,
9195 new_args, &lost,
9196 in_decl, complain);
9198 if (arg == NULL_TREE)
9200 /* We don't know how many args we have yet, just use the
9201 unconverted (and still packed) ones for now. */
9202 new_inner_args = orig_inner_args;
9203 arg_idx = nargs;
9204 break;
9207 TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
9209 /* Store this argument. */
9210 if (arg == error_mark_node)
9212 lost++;
9213 /* We are done with all of the arguments. */
9214 arg_idx = nargs;
9215 break;
9217 else
9219 pack_adjust = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg)) - 1;
9220 arg_idx += pack_adjust;
9221 if (fixed_parameter_pack_p (TREE_VALUE (parm)))
9223 ++fixed_packs;
9224 fixed_pack_adjust += pack_adjust;
9228 continue;
9230 else if (arg)
9232 if (PACK_EXPANSION_P (arg))
9234 /* "If every valid specialization of a variadic template
9235 requires an empty template parameter pack, the template is
9236 ill-formed, no diagnostic required." So check that the
9237 pattern works with this parameter. */
9238 tree pattern = PACK_EXPANSION_PATTERN (arg);
9239 tree conv = convert_template_argument (TREE_VALUE (parm),
9240 pattern, new_args,
9241 complain, parm_idx,
9242 in_decl);
9243 if (conv == error_mark_node)
9245 if (complain & tf_error)
9246 inform (input_location, "so any instantiation with a "
9247 "non-empty parameter pack would be ill-formed");
9248 ++lost;
9250 else if (TYPE_P (conv) && !TYPE_P (pattern))
9251 /* Recover from missing typename. */
9252 TREE_VEC_ELT (inner_args, arg_idx)
9253 = make_pack_expansion (conv, complain);
9255 /* We don't know how many args we have yet, just
9256 use the unconverted ones for now. */
9257 new_inner_args = inner_args;
9258 arg_idx = nargs;
9259 break;
9262 else if (require_all_args)
9264 /* There must be a default arg in this case. */
9265 arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
9266 complain, in_decl);
9267 /* The position of the first default template argument,
9268 is also the number of non-defaulted arguments in NEW_INNER_ARGS.
9269 Record that. */
9270 if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
9271 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
9272 arg_idx - pack_adjust);
9274 else
9275 break;
9277 if (arg == error_mark_node)
9279 if (complain & tf_error)
9280 error ("template argument %d is invalid", arg_idx + 1);
9282 else if (!arg)
9284 /* This can occur if there was an error in the template
9285 parameter list itself (which we would already have
9286 reported) that we are trying to recover from, e.g., a class
9287 template with a parameter list such as
9288 template<typename..., typename> (cpp0x/variadic150.C). */
9289 ++lost;
9291 /* This can also happen with a fixed parameter pack (71834). */
9292 if (arg_idx >= nargs)
9293 ++missing;
9295 else
9296 arg = convert_template_argument (TREE_VALUE (parm),
9297 arg, new_args, complain,
9298 parm_idx, in_decl);
9300 if (arg == error_mark_node)
9301 lost++;
9303 TREE_VEC_ELT (new_inner_args, arg_idx - pack_adjust) = arg;
9306 if (missing || arg_idx < nargs - variadic_args_p)
9308 /* If we had fixed parameter packs, we didn't know how many arguments we
9309 actually needed earlier; now we do. */
9310 nparms += fixed_pack_adjust;
9311 variadic_p -= fixed_packs;
9312 goto bad_nargs;
9315 if (arg_idx < nargs)
9317 /* We had some pack expansion arguments that will only work if the packs
9318 are empty, but wait until instantiation time to complain.
9319 See variadic-ttp3.C. */
9321 /* Except that we can't provide empty packs to alias templates or
9322 concepts when there are no corresponding parameters. Basically,
9323 we can get here with this:
9325 template<typename T> concept C = true;
9327 template<typename... Args>
9328 requires C<Args...>
9329 void f();
9331 When parsing C<Args...>, we try to form a concept check of
9332 C<?, Args...>. Without the extra check for substituting an empty
9333 pack past the last parameter, we can accept the check as valid.
9335 FIXME: This may be valid for alias templates (but I doubt it).
9337 FIXME: The error could be better also. */
9338 if (in_decl && concept_definition_p (in_decl))
9340 if (complain & tf_error)
9341 error_at (location_of (TREE_VEC_ELT (args, arg_idx)),
9342 "too many arguments");
9343 return error_mark_node;
9346 int len = nparms + (nargs - arg_idx);
9347 tree args = make_tree_vec (len);
9348 int i = 0;
9349 for (; i < nparms; ++i)
9350 TREE_VEC_ELT (args, i) = TREE_VEC_ELT (new_inner_args, i);
9351 for (; i < len; ++i, ++arg_idx)
9352 TREE_VEC_ELT (args, i) = TREE_VEC_ELT (inner_args,
9353 arg_idx - pack_adjust);
9354 new_inner_args = args;
9357 if (lost)
9359 gcc_assert (!(complain & tf_error) || seen_error ());
9360 return error_mark_node;
9363 if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
9364 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
9365 TREE_VEC_LENGTH (new_inner_args));
9367 return return_full_args ? new_args : new_inner_args;
9370 /* Returns true if T is a wrapper to make a C++20 template parameter
9371 object const. */
9373 static bool
9374 class_nttp_const_wrapper_p (tree t)
9376 if (cxx_dialect < cxx20)
9377 return false;
9378 return (TREE_CODE (t) == VIEW_CONVERT_EXPR
9379 && CP_TYPE_CONST_P (TREE_TYPE (t))
9380 && TREE_CODE (TREE_OPERAND (t, 0)) == TEMPLATE_PARM_INDEX);
9383 /* Returns 1 if template args OT and NT are equivalent. */
9386 template_args_equal (tree ot, tree nt)
9388 if (nt == ot)
9389 return 1;
9390 if (nt == NULL_TREE || ot == NULL_TREE)
9391 return false;
9392 if (nt == any_targ_node || ot == any_targ_node)
9393 return true;
9395 if (class_nttp_const_wrapper_p (nt))
9396 nt = TREE_OPERAND (nt, 0);
9397 if (class_nttp_const_wrapper_p (ot))
9398 ot = TREE_OPERAND (ot, 0);
9400 /* DR 1558: Don't treat an alias template specialization with dependent
9401 arguments as equivalent to its underlying type when used as a template
9402 argument; we need them to be distinct so that we substitute into the
9403 specialization arguments at instantiation time. And aliases can't be
9404 equivalent without being ==, so we don't need to look any deeper.
9406 During partial ordering, however, we need to treat them normally so we can
9407 order uses of the same alias with different cv-qualification (79960). */
9408 auto cso = make_temp_override (comparing_dependent_aliases);
9409 if (!comparing_for_partial_ordering)
9410 ++comparing_dependent_aliases;
9412 if (TREE_CODE (nt) == TREE_VEC || TREE_CODE (ot) == TREE_VEC)
9413 /* For member templates */
9414 return TREE_CODE (ot) == TREE_CODE (nt) && comp_template_args (ot, nt);
9415 else if (PACK_EXPANSION_P (ot) || PACK_EXPANSION_P (nt))
9416 return (PACK_EXPANSION_P (ot) && PACK_EXPANSION_P (nt)
9417 && template_args_equal (PACK_EXPANSION_PATTERN (ot),
9418 PACK_EXPANSION_PATTERN (nt))
9419 && template_args_equal (PACK_EXPANSION_EXTRA_ARGS (ot),
9420 PACK_EXPANSION_EXTRA_ARGS (nt)));
9421 else if (ARGUMENT_PACK_P (ot) || ARGUMENT_PACK_P (nt))
9422 return cp_tree_equal (ot, nt);
9423 else if (TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
9424 gcc_unreachable ();
9425 else if (TYPE_P (nt) || TYPE_P (ot))
9427 if (!(TYPE_P (nt) && TYPE_P (ot)))
9428 return false;
9429 return same_type_p (ot, nt);
9431 else
9433 /* Try to treat a template non-type argument that has been converted
9434 to the parameter type as equivalent to one that hasn't yet. */
9435 for (enum tree_code code1 = TREE_CODE (ot);
9436 CONVERT_EXPR_CODE_P (code1)
9437 || code1 == NON_LVALUE_EXPR;
9438 code1 = TREE_CODE (ot))
9439 ot = TREE_OPERAND (ot, 0);
9441 for (enum tree_code code2 = TREE_CODE (nt);
9442 CONVERT_EXPR_CODE_P (code2)
9443 || code2 == NON_LVALUE_EXPR;
9444 code2 = TREE_CODE (nt))
9445 nt = TREE_OPERAND (nt, 0);
9447 return cp_tree_equal (ot, nt);
9451 /* Returns true iff the OLDARGS and NEWARGS are in fact identical sets of
9452 template arguments. Returns false otherwise, and updates OLDARG_PTR and
9453 NEWARG_PTR with the offending arguments if they are non-NULL. */
9455 bool
9456 comp_template_args (tree oldargs, tree newargs,
9457 tree *oldarg_ptr /* = NULL */, tree *newarg_ptr /* = NULL */)
9459 if (oldargs == newargs)
9460 return true;
9462 if (!oldargs || !newargs)
9463 return false;
9465 if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
9466 return false;
9468 for (int i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
9470 tree nt = TREE_VEC_ELT (newargs, i);
9471 tree ot = TREE_VEC_ELT (oldargs, i);
9473 if (! template_args_equal (ot, nt))
9475 if (oldarg_ptr != NULL)
9476 *oldarg_ptr = ot;
9477 if (newarg_ptr != NULL)
9478 *newarg_ptr = nt;
9479 return false;
9482 return true;
9485 static bool
9486 comp_template_args_porder (tree oargs, tree nargs)
9488 ++comparing_for_partial_ordering;
9489 bool equal = comp_template_args (oargs, nargs);
9490 --comparing_for_partial_ordering;
9491 return equal;
9494 /* Implement a freelist interface for objects of type T.
9496 Head is a separate object, rather than a regular member, so that we
9497 can define it as a GTY deletable pointer, which is highly
9498 desirable. A data member could be declared that way, but then the
9499 containing object would implicitly get GTY((user)), which would
9500 prevent us from instantiating freelists as global objects.
9501 Although this way we can create freelist global objects, they're
9502 such thin wrappers that instantiating temporaries at every use
9503 loses nothing and saves permanent storage for the freelist object.
9505 Member functions next, anew, poison and reinit have default
9506 implementations that work for most of the types we're interested
9507 in, but if they don't work for some type, they should be explicitly
9508 specialized. See the comments before them for requirements, and
9509 the example specializations for the tree_list_freelist. */
9510 template <typename T>
9511 class freelist
9513 /* Return the next object in a chain. We could just do type
9514 punning, but if we access the object with its underlying type, we
9515 avoid strict-aliasing trouble. This needs only work between
9516 poison and reinit. */
9517 static T *&next (T *obj) { return obj->next; }
9519 /* Return a newly allocated, uninitialized or minimally-initialized
9520 object of type T. Any initialization performed by anew should
9521 either remain across the life of the object and the execution of
9522 poison, or be redone by reinit. */
9523 static T *anew () { return ggc_alloc<T> (); }
9525 /* Optionally scribble all over the bits holding the object, so that
9526 they become (mostly?) uninitialized memory. This is called while
9527 preparing to make the object part of the free list. */
9528 static void poison (T *obj) {
9529 T *p ATTRIBUTE_UNUSED = obj;
9530 T **q ATTRIBUTE_UNUSED = &next (obj);
9532 #ifdef ENABLE_GC_CHECKING
9533 /* Poison the data, to indicate the data is garbage. */
9534 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, sizeof (*p)));
9535 memset (p, 0xa5, sizeof (*p));
9536 #endif
9537 /* Let valgrind know the object is free. */
9538 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, sizeof (*p)));
9540 /* Let valgrind know the next portion of the object is available,
9541 but uninitialized. */
9542 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
9545 /* Bring an object that underwent at least one lifecycle after anew
9546 and before the most recent free and poison, back to a usable
9547 state, reinitializing whatever is needed for it to be
9548 functionally equivalent to an object just allocated and returned
9549 by anew. This may poison or clear the next field, used by
9550 freelist housekeeping after poison was called. */
9551 static void reinit (T *obj) {
9552 T **q ATTRIBUTE_UNUSED = &next (obj);
9554 #ifdef ENABLE_GC_CHECKING
9555 memset (q, 0xa5, sizeof (*q));
9556 #endif
9557 /* Let valgrind know the entire object is available, but
9558 uninitialized. */
9559 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (*obj)));
9562 /* Reference a GTY-deletable pointer that points to the first object
9563 in the free list proper. */
9564 T *&head;
9565 public:
9566 /* Construct a freelist object chaining objects off of HEAD. */
9567 freelist (T *&head) : head(head) {}
9569 /* Add OBJ to the free object list. The former head becomes OBJ's
9570 successor. */
9571 void free (T *obj)
9573 poison (obj);
9574 next (obj) = head;
9575 head = obj;
9578 /* Take an object from the free list, if one is available, or
9579 allocate a new one. Objects taken from the free list should be
9580 regarded as filled with garbage, except for bits that are
9581 configured to be preserved across free and alloc. */
9582 T *alloc ()
9584 if (head)
9586 T *obj = head;
9587 head = next (head);
9588 reinit (obj);
9589 return obj;
9591 else
9592 return anew ();
9596 /* Explicitly specialize the interfaces for freelist<tree_node>: we
9597 want to allocate a TREE_LIST using the usual interface, and ensure
9598 TREE_CHAIN remains functional. Alas, we have to duplicate a bit of
9599 build_tree_list logic in reinit, so this could go out of sync. */
9600 template <>
9601 inline tree &
9602 freelist<tree_node>::next (tree obj)
9604 return TREE_CHAIN (obj);
9606 template <>
9607 inline tree
9608 freelist<tree_node>::anew ()
9610 return build_tree_list (NULL, NULL);
9612 template <>
9613 inline void
9614 freelist<tree_node>::poison (tree obj ATTRIBUTE_UNUSED)
9616 int size ATTRIBUTE_UNUSED = sizeof (tree_list);
9617 tree p ATTRIBUTE_UNUSED = obj;
9618 tree_base *b ATTRIBUTE_UNUSED = &obj->base;
9619 tree *q ATTRIBUTE_UNUSED = &next (obj);
9621 #ifdef ENABLE_GC_CHECKING
9622 gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
9624 /* Poison the data, to indicate the data is garbage. */
9625 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, size));
9626 memset (p, 0xa5, size);
9627 #endif
9628 /* Let valgrind know the object is free. */
9629 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, size));
9630 /* But we still want to use the TREE_CODE and TREE_CHAIN parts. */
9631 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9632 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
9634 #ifdef ENABLE_GC_CHECKING
9635 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (b, sizeof (*b)));
9636 /* Keep TREE_CHAIN functional. */
9637 TREE_SET_CODE (obj, TREE_LIST);
9638 #else
9639 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9640 #endif
9642 template <>
9643 inline void
9644 freelist<tree_node>::reinit (tree obj ATTRIBUTE_UNUSED)
9646 tree_common *c ATTRIBUTE_UNUSED = &obj->common;
9648 #ifdef ENABLE_GC_CHECKING
9649 gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
9650 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
9651 memset (obj, 0, sizeof (tree_list));
9652 #endif
9654 /* Let valgrind know the entire object is available, but
9655 uninitialized. */
9656 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
9658 #ifdef ENABLE_GC_CHECKING
9659 TREE_SET_CODE (obj, TREE_LIST);
9660 #else
9661 TREE_CHAIN (obj) = NULL_TREE;
9662 TREE_TYPE (obj) = NULL_TREE;
9663 #endif
9664 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (c, sizeof (*c)));
9667 /* Point to the first object in the TREE_LIST freelist. */
9668 static GTY((deletable)) tree tree_list_freelist_head;
9669 /* Return the/an actual TREE_LIST freelist. */
9670 static inline freelist<tree_node>
9671 tree_list_freelist ()
9673 return tree_list_freelist_head;
9676 /* Point to the first object in the tinst_level freelist. */
9677 static GTY((deletable)) tinst_level *tinst_level_freelist_head;
9678 /* Return the/an actual tinst_level freelist. */
9679 static inline freelist<tinst_level>
9680 tinst_level_freelist ()
9682 return tinst_level_freelist_head;
9685 /* Point to the first object in the pending_template freelist. */
9686 static GTY((deletable)) pending_template *pending_template_freelist_head;
9687 /* Return the/an actual pending_template freelist. */
9688 static inline freelist<pending_template>
9689 pending_template_freelist ()
9691 return pending_template_freelist_head;
9694 /* Build the TREE_LIST object out of a split list, store it
9695 permanently, and return it. */
9696 tree
9697 tinst_level::to_list ()
9699 gcc_assert (split_list_p ());
9700 tree ret = tree_list_freelist ().alloc ();
9701 TREE_PURPOSE (ret) = tldcl;
9702 TREE_VALUE (ret) = targs;
9703 tldcl = ret;
9704 targs = NULL;
9705 gcc_assert (tree_list_p ());
9706 return ret;
9709 const unsigned short tinst_level::refcount_infinity;
9711 /* Increment OBJ's refcount unless it is already infinite. */
9712 static tinst_level *
9713 inc_refcount_use (tinst_level *obj)
9715 if (obj && obj->refcount != tinst_level::refcount_infinity)
9716 ++obj->refcount;
9717 return obj;
9720 /* Release storage for OBJ and node, if it's a TREE_LIST. */
9721 void
9722 tinst_level::free (tinst_level *obj)
9724 if (obj->tree_list_p ())
9725 tree_list_freelist ().free (obj->get_node ());
9726 tinst_level_freelist ().free (obj);
9729 /* Decrement OBJ's refcount if not infinite. If it reaches zero, release
9730 OBJ's DECL and OBJ, and start over with the tinst_level object that
9731 used to be referenced by OBJ's NEXT. */
9732 static void
9733 dec_refcount_use (tinst_level *obj)
9735 while (obj
9736 && obj->refcount != tinst_level::refcount_infinity
9737 && !--obj->refcount)
9739 tinst_level *next = obj->next;
9740 tinst_level::free (obj);
9741 obj = next;
9745 /* Modify PTR so that it points to OBJ, adjusting the refcounts of OBJ
9746 and of the former PTR. Omitting the second argument is equivalent
9747 to passing (T*)NULL; this is allowed because passing the
9748 zero-valued integral constant NULL confuses type deduction and/or
9749 overload resolution. */
9750 template <typename T>
9751 static void
9752 set_refcount_ptr (T *& ptr, T *obj = NULL)
9754 T *save = ptr;
9755 ptr = inc_refcount_use (obj);
9756 dec_refcount_use (save);
9759 static void
9760 add_pending_template (tree d)
9762 tree ti = (TYPE_P (d)
9763 ? CLASSTYPE_TEMPLATE_INFO (d)
9764 : DECL_TEMPLATE_INFO (d));
9765 struct pending_template *pt;
9766 int level;
9768 if (TI_PENDING_TEMPLATE_FLAG (ti))
9769 return;
9771 /* We are called both from instantiate_decl, where we've already had a
9772 tinst_level pushed, and instantiate_template, where we haven't.
9773 Compensate. */
9774 gcc_assert (TREE_CODE (d) != TREE_LIST);
9775 level = !current_tinst_level
9776 || current_tinst_level->maybe_get_node () != d;
9778 if (level)
9779 push_tinst_level (d);
9781 pt = pending_template_freelist ().alloc ();
9782 pt->next = NULL;
9783 pt->tinst = NULL;
9784 set_refcount_ptr (pt->tinst, current_tinst_level);
9785 if (last_pending_template)
9786 last_pending_template->next = pt;
9787 else
9788 pending_templates = pt;
9790 last_pending_template = pt;
9792 TI_PENDING_TEMPLATE_FLAG (ti) = 1;
9794 if (level)
9795 pop_tinst_level ();
9799 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
9800 ARGLIST. Valid choices for FNS are given in the cp-tree.def
9801 documentation for TEMPLATE_ID_EXPR. */
9803 tree
9804 lookup_template_function (tree fns, tree arglist)
9806 if (fns == error_mark_node || arglist == error_mark_node)
9807 return error_mark_node;
9809 gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
9811 if (!is_overloaded_fn (fns) && !identifier_p (fns))
9813 error ("%q#D is not a function template", fns);
9814 return error_mark_node;
9817 if (BASELINK_P (fns))
9819 fns = copy_node (fns);
9820 BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
9821 unknown_type_node,
9822 BASELINK_FUNCTIONS (fns),
9823 arglist);
9824 return fns;
9827 return build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, arglist);
9830 /* Within the scope of a template class S<T>, the name S gets bound
9831 (in build_self_reference) to a TYPE_DECL for the class, not a
9832 TEMPLATE_DECL. If DECL is a TYPE_DECL for current_class_type,
9833 or one of its enclosing classes, and that type is a template,
9834 return the associated TEMPLATE_DECL. Otherwise, the original
9835 DECL is returned.
9837 Also handle the case when DECL is a TREE_LIST of ambiguous
9838 injected-class-names from different bases. */
9840 tree
9841 maybe_get_template_decl_from_type_decl (tree decl)
9843 if (decl == NULL_TREE)
9844 return decl;
9846 /* DR 176: A lookup that finds an injected-class-name (10.2
9847 [class.member.lookup]) can result in an ambiguity in certain cases
9848 (for example, if it is found in more than one base class). If all of
9849 the injected-class-names that are found refer to specializations of
9850 the same class template, and if the name is followed by a
9851 template-argument-list, the reference refers to the class template
9852 itself and not a specialization thereof, and is not ambiguous. */
9853 if (TREE_CODE (decl) == TREE_LIST)
9855 tree t, tmpl = NULL_TREE;
9856 for (t = decl; t; t = TREE_CHAIN (t))
9858 tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
9859 if (!tmpl)
9860 tmpl = elt;
9861 else if (tmpl != elt)
9862 break;
9864 if (tmpl && t == NULL_TREE)
9865 return tmpl;
9866 else
9867 return decl;
9870 return (decl != NULL_TREE
9871 && DECL_SELF_REFERENCE_P (decl)
9872 && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
9873 ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
9876 /* Given an IDENTIFIER_NODE (or type TEMPLATE_DECL) and a chain of
9877 parameters, find the desired type.
9879 D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
9881 IN_DECL, if non-NULL, is the template declaration we are trying to
9882 instantiate.
9884 If ENTERING_SCOPE is nonzero, we are about to enter the scope of
9885 the class we are looking up.
9887 Issue error and warning messages under control of COMPLAIN.
9889 If the template class is really a local class in a template
9890 function, then the FUNCTION_CONTEXT is the function in which it is
9891 being instantiated.
9893 ??? Note that this function is currently called *twice* for each
9894 template-id: the first time from the parser, while creating the
9895 incomplete type (finish_template_type), and the second type during the
9896 real instantiation (instantiate_template_class). This is surely something
9897 that we want to avoid. It also causes some problems with argument
9898 coercion (see convert_nontype_argument for more information on this). */
9900 tree
9901 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
9902 int entering_scope, tsubst_flags_t complain)
9904 auto_timevar tv (TV_TEMPLATE_INST);
9906 tree templ = NULL_TREE, parmlist;
9907 tree t;
9908 spec_entry **slot;
9909 spec_entry *entry;
9910 spec_entry elt;
9911 hashval_t hash;
9913 if (identifier_p (d1))
9915 tree value = innermost_non_namespace_value (d1);
9916 if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
9917 templ = value;
9918 else
9920 if (context)
9921 push_decl_namespace (context);
9922 templ = lookup_name (d1);
9923 templ = maybe_get_template_decl_from_type_decl (templ);
9924 if (context)
9925 pop_decl_namespace ();
9928 else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
9930 tree type = TREE_TYPE (d1);
9932 /* If we are declaring a constructor, say A<T>::A<T>, we will get
9933 an implicit typename for the second A. Deal with it. */
9934 if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
9935 type = TREE_TYPE (type);
9937 if (CLASSTYPE_TEMPLATE_INFO (type))
9939 templ = CLASSTYPE_TI_TEMPLATE (type);
9940 d1 = DECL_NAME (templ);
9943 else if (TREE_CODE (d1) == ENUMERAL_TYPE
9944 || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
9946 templ = TYPE_TI_TEMPLATE (d1);
9947 d1 = DECL_NAME (templ);
9949 else if (DECL_TYPE_TEMPLATE_P (d1))
9951 templ = d1;
9952 d1 = DECL_NAME (templ);
9954 else if (DECL_TEMPLATE_TEMPLATE_PARM_P (d1))
9956 templ = d1;
9957 d1 = DECL_NAME (templ);
9960 /* Issue an error message if we didn't find a template. */
9961 if (! templ)
9963 if (complain & tf_error)
9964 error ("%qT is not a template", d1);
9965 return error_mark_node;
9968 if (TREE_CODE (templ) != TEMPLATE_DECL
9969 /* Make sure it's a user visible template, if it was named by
9970 the user. */
9971 || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
9972 && !PRIMARY_TEMPLATE_P (templ)))
9974 if (complain & tf_error)
9976 error ("non-template type %qT used as a template", d1);
9977 if (in_decl)
9978 error ("for template declaration %q+D", in_decl);
9980 return error_mark_node;
9983 complain &= ~tf_user;
9985 /* An alias that just changes the name of a template is equivalent to the
9986 other template, so if any of the arguments are pack expansions, strip
9987 the alias to avoid problems with a pack expansion passed to a non-pack
9988 alias template parameter (DR 1430). */
9989 if (pack_expansion_args_count (INNERMOST_TEMPLATE_ARGS (arglist)))
9990 templ = get_underlying_template (templ);
9992 if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
9994 tree parm;
9995 tree arglist2 = coerce_template_args_for_ttp (templ, arglist, complain);
9996 if (arglist2 == error_mark_node
9997 || (!uses_template_parms (arglist2)
9998 && check_instantiated_args (templ, arglist2, complain)))
9999 return error_mark_node;
10001 parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
10002 return parm;
10004 else
10006 tree template_type = TREE_TYPE (templ);
10007 tree gen_tmpl;
10008 tree type_decl;
10009 tree found = NULL_TREE;
10010 int arg_depth;
10011 int parm_depth;
10012 int is_dependent_type;
10013 int use_partial_inst_tmpl = false;
10015 if (template_type == error_mark_node)
10016 /* An error occurred while building the template TEMPL, and a
10017 diagnostic has most certainly been emitted for that
10018 already. Let's propagate that error. */
10019 return error_mark_node;
10021 gen_tmpl = most_general_template (templ);
10022 if (modules_p ())
10023 lazy_load_pendings (gen_tmpl);
10025 parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
10026 parm_depth = TMPL_PARMS_DEPTH (parmlist);
10027 arg_depth = TMPL_ARGS_DEPTH (arglist);
10029 if (arg_depth == 1 && parm_depth > 1)
10031 /* We've been given an incomplete set of template arguments.
10032 For example, given:
10034 template <class T> struct S1 {
10035 template <class U> struct S2 {};
10036 template <class U> struct S2<U*> {};
10039 we will be called with an ARGLIST of `U*', but the
10040 TEMPLATE will be `template <class T> template
10041 <class U> struct S1<T>::S2'. We must fill in the missing
10042 arguments. */
10043 tree ti = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (templ));
10044 arglist = add_outermost_template_args (TI_ARGS (ti), arglist);
10045 arg_depth = TMPL_ARGS_DEPTH (arglist);
10048 /* Now we should have enough arguments. */
10049 gcc_assert (parm_depth == arg_depth);
10051 /* From here on, we're only interested in the most general
10052 template. */
10054 /* Shortcut looking up the current class scope again. */
10055 for (tree cur = current_nonlambda_class_type ();
10056 cur != NULL_TREE;
10057 cur = get_containing_scope (cur))
10059 if (!CLASS_TYPE_P (cur))
10060 continue;
10062 tree ti = CLASSTYPE_TEMPLATE_INFO (cur);
10063 if (!ti || arg_depth > TMPL_ARGS_DEPTH (TI_ARGS (ti)))
10064 break;
10066 if (gen_tmpl == most_general_template (TI_TEMPLATE (ti))
10067 && comp_template_args (arglist, TI_ARGS (ti)))
10068 return cur;
10071 /* Calculate the BOUND_ARGS. These will be the args that are
10072 actually tsubst'd into the definition to create the
10073 instantiation. */
10074 if (PRIMARY_TEMPLATE_P (gen_tmpl))
10075 arglist = coerce_template_parms (parmlist, arglist, gen_tmpl, complain);
10077 if (arglist == error_mark_node)
10078 /* We were unable to bind the arguments. */
10079 return error_mark_node;
10081 /* In the scope of a template class, explicit references to the
10082 template class refer to the type of the template, not any
10083 instantiation of it. For example, in:
10085 template <class T> class C { void f(C<T>); }
10087 the `C<T>' is just the same as `C'. Outside of the
10088 class, however, such a reference is an instantiation. */
10089 if (entering_scope
10090 || !PRIMARY_TEMPLATE_P (gen_tmpl)
10091 || currently_open_class (template_type))
10093 tree tinfo = TYPE_TEMPLATE_INFO (template_type);
10095 if (tinfo && comp_template_args (TI_ARGS (tinfo), arglist))
10096 return template_type;
10099 /* If we already have this specialization, return it. */
10100 elt.tmpl = gen_tmpl;
10101 elt.args = arglist;
10102 elt.spec = NULL_TREE;
10103 hash = spec_hasher::hash (&elt);
10104 entry = type_specializations->find_with_hash (&elt, hash);
10106 if (entry)
10107 return entry->spec;
10109 /* If the template's constraints are not satisfied,
10110 then we cannot form a valid type.
10112 Note that the check is deferred until after the hash
10113 lookup. This prevents redundant checks on previously
10114 instantiated specializations. */
10115 if (flag_concepts
10116 && !DECL_ALIAS_TEMPLATE_P (gen_tmpl)
10117 && !constraints_satisfied_p (gen_tmpl, arglist))
10119 if (complain & tf_error)
10121 auto_diagnostic_group d;
10122 error ("template constraint failure for %qD", gen_tmpl);
10123 diagnose_constraints (input_location, gen_tmpl, arglist);
10125 return error_mark_node;
10128 is_dependent_type = uses_template_parms (arglist);
10130 /* If the deduced arguments are invalid, then the binding
10131 failed. */
10132 if (!is_dependent_type
10133 && check_instantiated_args (gen_tmpl,
10134 INNERMOST_TEMPLATE_ARGS (arglist),
10135 complain))
10136 return error_mark_node;
10138 if (!is_dependent_type
10139 && !PRIMARY_TEMPLATE_P (gen_tmpl)
10140 && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
10141 && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
10142 /* This occurs when the user has tried to define a tagged type
10143 in a scope that forbids it. We emitted an error during the
10144 parse. We didn't complete the bail out then, so here we
10145 are. */
10146 return error_mark_node;
10148 context = DECL_CONTEXT (gen_tmpl);
10149 if (context && TYPE_P (context))
10151 if (!uses_template_parms (DECL_CONTEXT (templ)))
10152 /* If the context of the partially instantiated template is
10153 already non-dependent, then we might as well use it. */
10154 context = DECL_CONTEXT (templ);
10155 else
10157 context = tsubst_aggr_type (context, arglist,
10158 complain, in_decl, true);
10159 /* Try completing the enclosing context if it's not already so. */
10160 if (context != error_mark_node
10161 && !COMPLETE_TYPE_P (context))
10163 context = complete_type (context);
10164 if (COMPLETE_TYPE_P (context))
10166 /* Completion could have caused us to register the desired
10167 specialization already, so check the table again. */
10168 entry = type_specializations->find_with_hash (&elt, hash);
10169 if (entry)
10170 return entry->spec;
10175 else
10176 context = tsubst (context, arglist, complain, in_decl);
10178 if (context == error_mark_node)
10179 return error_mark_node;
10181 if (!context)
10182 context = global_namespace;
10184 /* Create the type. */
10185 if (DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10187 /* The user referred to a specialization of an alias
10188 template represented by GEN_TMPL.
10190 [temp.alias]/2 says:
10192 When a template-id refers to the specialization of an
10193 alias template, it is equivalent to the associated
10194 type obtained by substitution of its
10195 template-arguments for the template-parameters in the
10196 type-id of the alias template. */
10198 t = tsubst (TREE_TYPE (gen_tmpl), arglist, complain, in_decl);
10199 /* Note that the call above (by indirectly calling
10200 register_specialization in tsubst_decl) registers the
10201 TYPE_DECL representing the specialization of the alias
10202 template. So next time someone substitutes ARGLIST for
10203 the template parms into the alias template (GEN_TMPL),
10204 she'll get that TYPE_DECL back. */
10206 if (t == error_mark_node)
10207 return t;
10209 else if (TREE_CODE (template_type) == ENUMERAL_TYPE)
10211 if (!is_dependent_type)
10213 set_current_access_from_decl (TYPE_NAME (template_type));
10214 t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
10215 tsubst (ENUM_UNDERLYING_TYPE (template_type),
10216 arglist, complain, in_decl),
10217 tsubst_attributes (TYPE_ATTRIBUTES (template_type),
10218 arglist, complain, in_decl),
10219 SCOPED_ENUM_P (template_type), NULL);
10221 if (t == error_mark_node)
10222 return t;
10224 else
10226 /* We don't want to call start_enum for this type, since
10227 the values for the enumeration constants may involve
10228 template parameters. And, no one should be interested
10229 in the enumeration constants for such a type. */
10230 t = cxx_make_type (ENUMERAL_TYPE);
10231 SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
10233 SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
10234 ENUM_FIXED_UNDERLYING_TYPE_P (t)
10235 = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
10237 else if (CLASS_TYPE_P (template_type))
10239 /* Lambda closures are regenerated in tsubst_lambda_expr, not
10240 instantiated here. */
10241 gcc_assert (!LAMBDA_TYPE_P (template_type));
10243 t = make_class_type (TREE_CODE (template_type));
10244 CLASSTYPE_DECLARED_CLASS (t)
10245 = CLASSTYPE_DECLARED_CLASS (template_type);
10246 SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
10248 /* A local class. Make sure the decl gets registered properly. */
10249 if (context == current_function_decl)
10250 if (pushtag (DECL_NAME (gen_tmpl), t)
10251 == error_mark_node)
10252 return error_mark_node;
10254 if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
10255 /* This instantiation is another name for the primary
10256 template type. Set the TYPE_CANONICAL field
10257 appropriately. */
10258 TYPE_CANONICAL (t) = template_type;
10259 else if (any_template_arguments_need_structural_equality_p (arglist))
10260 SET_TYPE_STRUCTURAL_EQUALITY (t);
10262 else
10263 gcc_unreachable ();
10265 /* If we called start_enum or pushtag above, this information
10266 will already be set up. */
10267 type_decl = TYPE_NAME (t);
10268 if (!type_decl)
10270 TYPE_CONTEXT (t) = FROB_CONTEXT (context);
10272 type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
10273 DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
10274 DECL_SOURCE_LOCATION (type_decl)
10275 = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
10278 set_instantiating_module (type_decl);
10279 /* Although GEN_TMPL is the TEMPLATE_DECL, it has the same value
10280 of export flag. We want to propagate this because it might
10281 be a friend declaration that pushes a new hidden binding. */
10282 DECL_MODULE_EXPORT_P (type_decl) = DECL_MODULE_EXPORT_P (gen_tmpl);
10284 if (CLASS_TYPE_P (template_type))
10286 TREE_PRIVATE (type_decl)
10287 = TREE_PRIVATE (TYPE_MAIN_DECL (template_type));
10288 TREE_PROTECTED (type_decl)
10289 = TREE_PROTECTED (TYPE_MAIN_DECL (template_type));
10290 if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
10292 DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
10293 DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
10297 if (OVERLOAD_TYPE_P (t)
10298 && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10300 static const char *tags[] = {"abi_tag", "may_alias"};
10302 for (unsigned ix = 0; ix != 2; ix++)
10304 tree attributes
10305 = lookup_attribute (tags[ix], TYPE_ATTRIBUTES (template_type));
10307 if (attributes)
10308 TYPE_ATTRIBUTES (t)
10309 = tree_cons (TREE_PURPOSE (attributes),
10310 TREE_VALUE (attributes),
10311 TYPE_ATTRIBUTES (t));
10315 /* Let's consider the explicit specialization of a member
10316 of a class template specialization that is implicitly instantiated,
10317 e.g.:
10318 template<class T>
10319 struct S
10321 template<class U> struct M {}; //#0
10324 template<>
10325 template<>
10326 struct S<int>::M<char> //#1
10328 int i;
10330 [temp.expl.spec]/4 says this is valid.
10332 In this case, when we write:
10333 S<int>::M<char> m;
10335 M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
10336 the one of #0.
10338 When we encounter #1, we want to store the partial instantiation
10339 of M (template<class T> S<int>::M<T>) in its CLASSTYPE_TI_TEMPLATE.
10341 For all cases other than this "explicit specialization of member of a
10342 class template", we just want to store the most general template into
10343 the CLASSTYPE_TI_TEMPLATE of M.
10345 This case of "explicit specialization of member of a class template"
10346 only happens when:
10347 1/ the enclosing class is an instantiation of, and therefore not
10348 the same as, the context of the most general template, and
10349 2/ we aren't looking at the partial instantiation itself, i.e.
10350 the innermost arguments are not the same as the innermost parms of
10351 the most general template.
10353 So it's only when 1/ and 2/ happens that we want to use the partial
10354 instantiation of the member template in lieu of its most general
10355 template. */
10357 if (PRIMARY_TEMPLATE_P (gen_tmpl)
10358 && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
10359 /* the enclosing class must be an instantiation... */
10360 && CLASS_TYPE_P (context)
10361 && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
10363 TREE_VEC_LENGTH (arglist)--;
10364 ++processing_template_decl;
10365 tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (gen_tmpl));
10366 tree partial_inst_args =
10367 tsubst (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)),
10368 arglist, complain, NULL_TREE);
10369 --processing_template_decl;
10370 TREE_VEC_LENGTH (arglist)++;
10371 if (partial_inst_args == error_mark_node)
10372 return error_mark_node;
10373 use_partial_inst_tmpl =
10374 /*...and we must not be looking at the partial instantiation
10375 itself. */
10376 !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
10377 partial_inst_args);
10380 if (!use_partial_inst_tmpl)
10381 /* This case is easy; there are no member templates involved. */
10382 found = gen_tmpl;
10383 else
10385 /* This is a full instantiation of a member template. Find
10386 the partial instantiation of which this is an instance. */
10388 /* Temporarily reduce by one the number of levels in the ARGLIST
10389 so as to avoid comparing the last set of arguments. */
10390 TREE_VEC_LENGTH (arglist)--;
10391 /* We don't use COMPLAIN in the following call because this isn't
10392 the immediate context of deduction. For instance, tf_partial
10393 could be set here as we might be at the beginning of template
10394 argument deduction when any explicitly specified template
10395 arguments are substituted into the function type. tf_partial
10396 could lead into trouble because we wouldn't find the partial
10397 instantiation that might have been created outside tf_partial
10398 context, because the levels of template parameters wouldn't
10399 match, because in a tf_partial context, tsubst doesn't reduce
10400 TEMPLATE_PARM_LEVEL. */
10401 found = tsubst (gen_tmpl, arglist, tf_none, NULL_TREE);
10402 TREE_VEC_LENGTH (arglist)++;
10403 /* FOUND is either a proper class type, or an alias
10404 template specialization. In the later case, it's a
10405 TYPE_DECL, resulting from the substituting of arguments
10406 for parameters in the TYPE_DECL of the alias template
10407 done earlier. So be careful while getting the template
10408 of FOUND. */
10409 found = (TREE_CODE (found) == TEMPLATE_DECL
10410 ? found
10411 : (TREE_CODE (found) == TYPE_DECL
10412 ? DECL_TI_TEMPLATE (found)
10413 : CLASSTYPE_TI_TEMPLATE (found)));
10415 if (DECL_CLASS_TEMPLATE_P (found)
10416 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (found)))
10418 /* If this partial instantiation is specialized, we want to
10419 use it for hash table lookup. */
10420 elt.tmpl = found;
10421 elt.args = arglist = INNERMOST_TEMPLATE_ARGS (arglist);
10422 hash = spec_hasher::hash (&elt);
10426 /* Build template info for the new specialization. */
10427 SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
10429 elt.spec = t;
10430 slot = type_specializations->find_slot_with_hash (&elt, hash, INSERT);
10431 gcc_checking_assert (*slot == NULL);
10432 entry = ggc_alloc<spec_entry> ();
10433 *entry = elt;
10434 *slot = entry;
10436 /* Note this use of the partial instantiation so we can check it
10437 later in maybe_process_partial_specialization. */
10438 DECL_TEMPLATE_INSTANTIATIONS (found)
10439 = tree_cons (arglist, t,
10440 DECL_TEMPLATE_INSTANTIATIONS (found));
10442 if (TREE_CODE (template_type) == ENUMERAL_TYPE
10443 && !uses_template_parms (current_nonlambda_scope ())
10444 && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10445 /* Now that the type has been registered on the instantiations
10446 list, we set up the enumerators. Because the enumeration
10447 constants may involve the enumeration type itself, we make
10448 sure to register the type first, and then create the
10449 constants. That way, doing tsubst_expr for the enumeration
10450 constants won't result in recursive calls here; we'll find
10451 the instantiation and exit above. */
10452 tsubst_enum (template_type, t, arglist);
10454 if (CLASS_TYPE_P (template_type) && is_dependent_type)
10455 /* If the type makes use of template parameters, the
10456 code that generates debugging information will crash. */
10457 DECL_IGNORED_P (TYPE_MAIN_DECL (t)) = 1;
10459 /* Possibly limit visibility based on template args. */
10460 TREE_PUBLIC (type_decl) = 1;
10461 determine_visibility (type_decl);
10463 inherit_targ_abi_tags (t);
10465 return t;
10469 /* Return a TEMPLATE_ID_EXPR for the given variable template and ARGLIST. */
10471 tree
10472 lookup_template_variable (tree templ, tree arglist, tsubst_flags_t complain)
10474 if (flag_concepts && variable_concept_p (templ))
10475 return build_concept_check (templ, arglist, tf_none);
10477 tree gen_templ = most_general_template (templ);
10478 tree parms = DECL_INNERMOST_TEMPLATE_PARMS (gen_templ);
10479 arglist = add_outermost_template_args (templ, arglist);
10480 arglist = coerce_template_parms (parms, arglist, templ, complain);
10481 if (arglist == error_mark_node)
10482 return error_mark_node;
10484 /* The type of the expression is NULL_TREE since the template-id could refer
10485 to an explicit or partial specialization. */
10486 return build2 (TEMPLATE_ID_EXPR, NULL_TREE, templ, arglist);
10489 /* Instantiate a variable declaration from a TEMPLATE_ID_EXPR if it's
10490 not dependent. */
10492 tree
10493 finish_template_variable (tree var, tsubst_flags_t complain)
10495 tree templ = TREE_OPERAND (var, 0);
10496 tree arglist = TREE_OPERAND (var, 1);
10498 /* If the template or arguments are dependent, then we
10499 can't resolve the TEMPLATE_ID_EXPR yet. */
10500 if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (templ)) != 1
10501 || any_dependent_template_arguments_p (arglist))
10502 return var;
10504 if (flag_concepts && !constraints_satisfied_p (templ, arglist))
10506 if (complain & tf_error)
10508 auto_diagnostic_group d;
10509 error ("use of invalid variable template %qE", var);
10510 diagnose_constraints (location_of (var), templ, arglist);
10512 return error_mark_node;
10515 return instantiate_template (templ, arglist, complain);
10518 /* Construct a TEMPLATE_ID_EXPR for the given variable template TEMPL having
10519 TARGS template args, and instantiate it if it's not dependent. */
10521 tree
10522 lookup_and_finish_template_variable (tree templ, tree targs,
10523 tsubst_flags_t complain)
10525 tree var = lookup_template_variable (templ, targs, complain);
10526 if (var == error_mark_node)
10527 return error_mark_node;
10528 var = finish_template_variable (var, complain);
10529 mark_used (var);
10530 return var;
10533 /* If the set of template parameters PARMS contains a template parameter
10534 at the given LEVEL and INDEX, then return this parameter. Otherwise
10535 return NULL_TREE. */
10537 static tree
10538 corresponding_template_parameter_list (tree parms, int level, int index)
10540 while (TMPL_PARMS_DEPTH (parms) > level)
10541 parms = TREE_CHAIN (parms);
10543 if (TMPL_PARMS_DEPTH (parms) != level
10544 || TREE_VEC_LENGTH (TREE_VALUE (parms)) <= index)
10545 return NULL_TREE;
10547 return TREE_VEC_ELT (TREE_VALUE (parms), index);
10550 /* Return the TREE_LIST for the template parameter from PARMS that positionally
10551 corresponds to the template parameter PARM, or else return NULL_TREE. */
10553 static tree
10554 corresponding_template_parameter_list (tree parms, tree parm)
10556 int level, index;
10557 template_parm_level_and_index (parm, &level, &index);
10558 return corresponding_template_parameter_list (parms, level, index);
10561 /* As above, but pull out the actual parameter. */
10563 static tree
10564 corresponding_template_parameter (tree parms, tree parm)
10566 tree list = corresponding_template_parameter_list (parms, parm);
10567 if (!list)
10568 return NULL_TREE;
10570 tree t = TREE_VALUE (list);
10571 /* As in template_parm_to_arg. */
10572 if (TREE_CODE (t) == TYPE_DECL || TREE_CODE (t) == TEMPLATE_DECL)
10573 t = TREE_TYPE (t);
10574 else
10575 t = DECL_INITIAL (t);
10577 gcc_assert (TEMPLATE_PARM_P (t));
10578 return t;
10581 struct pair_fn_data
10583 tree_fn_t fn;
10584 tree_fn_t any_fn;
10585 void *data;
10586 /* True when we should also visit template parameters that occur in
10587 non-deduced contexts. */
10588 bool include_nondeduced_p;
10589 hash_set<tree> *visited;
10592 /* Called from for_each_template_parm via walk_tree. */
10594 static tree
10595 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
10597 tree t = *tp;
10598 struct pair_fn_data *pfd = (struct pair_fn_data *) d;
10599 tree_fn_t fn = pfd->fn;
10600 void *data = pfd->data;
10601 tree result = NULL_TREE;
10603 #define WALK_SUBTREE(NODE) \
10604 do \
10606 result = for_each_template_parm (NODE, fn, data, pfd->visited, \
10607 pfd->include_nondeduced_p, \
10608 pfd->any_fn); \
10609 if (result) goto out; \
10611 while (0)
10613 if (pfd->any_fn && (*pfd->any_fn)(t, data))
10614 return t;
10616 if (TYPE_P (t)
10617 && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE))
10618 WALK_SUBTREE (TYPE_CONTEXT (t));
10620 switch (TREE_CODE (t))
10622 case RECORD_TYPE:
10623 if (TYPE_PTRMEMFUNC_P (t))
10624 break;
10625 /* Fall through. */
10627 case UNION_TYPE:
10628 case ENUMERAL_TYPE:
10629 if (!TYPE_TEMPLATE_INFO (t))
10630 *walk_subtrees = 0;
10631 else
10632 WALK_SUBTREE (TYPE_TI_ARGS (t));
10633 break;
10635 case INTEGER_TYPE:
10636 WALK_SUBTREE (TYPE_MIN_VALUE (t));
10637 WALK_SUBTREE (TYPE_MAX_VALUE (t));
10638 break;
10640 case METHOD_TYPE:
10641 /* Since we're not going to walk subtrees, we have to do this
10642 explicitly here. */
10643 WALK_SUBTREE (TYPE_METHOD_BASETYPE (t));
10644 /* Fall through. */
10646 case FUNCTION_TYPE:
10647 /* Check the return type. */
10648 WALK_SUBTREE (TREE_TYPE (t));
10650 /* Check the parameter types. Since default arguments are not
10651 instantiated until they are needed, the TYPE_ARG_TYPES may
10652 contain expressions that involve template parameters. But,
10653 no-one should be looking at them yet. And, once they're
10654 instantiated, they don't contain template parameters, so
10655 there's no point in looking at them then, either. */
10657 tree parm;
10659 for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
10660 WALK_SUBTREE (TREE_VALUE (parm));
10662 /* Since we've already handled the TYPE_ARG_TYPES, we don't
10663 want walk_tree walking into them itself. */
10664 *walk_subtrees = 0;
10667 if (flag_noexcept_type)
10669 tree spec = TYPE_RAISES_EXCEPTIONS (t);
10670 if (spec)
10671 WALK_SUBTREE (TREE_PURPOSE (spec));
10673 break;
10675 case TYPEOF_TYPE:
10676 case DECLTYPE_TYPE:
10677 if (pfd->include_nondeduced_p
10678 && for_each_template_parm (TYPE_VALUES_RAW (t), fn, data,
10679 pfd->visited,
10680 pfd->include_nondeduced_p,
10681 pfd->any_fn))
10682 return error_mark_node;
10683 *walk_subtrees = false;
10684 break;
10686 case TRAIT_TYPE:
10687 if (pfd->include_nondeduced_p)
10689 WALK_SUBTREE (TRAIT_TYPE_TYPE1 (t));
10690 WALK_SUBTREE (TRAIT_TYPE_TYPE2 (t));
10692 *walk_subtrees = false;
10693 break;
10695 case FUNCTION_DECL:
10696 case VAR_DECL:
10697 if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10698 WALK_SUBTREE (DECL_TI_ARGS (t));
10699 break;
10701 case PARM_DECL:
10702 WALK_SUBTREE (TREE_TYPE (t));
10703 break;
10705 case CONST_DECL:
10706 if (DECL_TEMPLATE_PARM_P (t))
10707 WALK_SUBTREE (DECL_INITIAL (t));
10708 if (DECL_CONTEXT (t)
10709 && pfd->include_nondeduced_p)
10710 WALK_SUBTREE (DECL_CONTEXT (t));
10711 break;
10713 case BOUND_TEMPLATE_TEMPLATE_PARM:
10714 /* Record template parameters such as `T' inside `TT<T>'. */
10715 WALK_SUBTREE (TYPE_TI_ARGS (t));
10716 /* Fall through. */
10718 case TEMPLATE_TEMPLATE_PARM:
10719 case TEMPLATE_TYPE_PARM:
10720 case TEMPLATE_PARM_INDEX:
10721 if (fn && (*fn)(t, data))
10722 return t;
10723 else if (!fn)
10724 return t;
10725 break;
10727 case TEMPLATE_DECL:
10728 /* A template template parameter is encountered. */
10729 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10730 WALK_SUBTREE (TREE_TYPE (t));
10732 /* Already substituted template template parameter */
10733 *walk_subtrees = 0;
10734 break;
10736 case TYPENAME_TYPE:
10737 /* A template-id in a TYPENAME_TYPE might be a deduced context after
10738 partial instantiation. */
10739 WALK_SUBTREE (TYPENAME_TYPE_FULLNAME (t));
10740 *walk_subtrees = 0;
10741 break;
10743 case INDIRECT_REF:
10744 case COMPONENT_REF:
10745 /* If there's no type, then this thing must be some expression
10746 involving template parameters. */
10747 if (!fn && !TREE_TYPE (t))
10748 return error_mark_node;
10749 break;
10751 case CONSTRUCTOR:
10752 case TRAIT_EXPR:
10753 case PLUS_EXPR:
10754 case MULT_EXPR:
10755 case SCOPE_REF:
10756 /* These are non-deduced contexts. */
10757 if (!pfd->include_nondeduced_p)
10758 *walk_subtrees = 0;
10759 break;
10761 case MODOP_EXPR:
10762 case CAST_EXPR:
10763 case IMPLICIT_CONV_EXPR:
10764 case REINTERPRET_CAST_EXPR:
10765 case CONST_CAST_EXPR:
10766 case STATIC_CAST_EXPR:
10767 case DYNAMIC_CAST_EXPR:
10768 case ARROW_EXPR:
10769 case DOTSTAR_EXPR:
10770 case TYPEID_EXPR:
10771 case PSEUDO_DTOR_EXPR:
10772 if (!fn)
10773 return error_mark_node;
10774 break;
10776 default:
10777 break;
10780 #undef WALK_SUBTREE
10782 /* We didn't find any template parameters we liked. */
10783 out:
10784 return result;
10787 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
10788 BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
10789 call FN with the parameter and the DATA.
10790 If FN returns nonzero, the iteration is terminated, and
10791 for_each_template_parm returns 1. Otherwise, the iteration
10792 continues. If FN never returns a nonzero value, the value
10793 returned by for_each_template_parm is 0. If FN is NULL, it is
10794 considered to be the function which always returns 1.
10796 If INCLUDE_NONDEDUCED_P, then this routine will also visit template
10797 parameters that occur in non-deduced contexts. When false, only
10798 visits those template parameters that can be deduced. */
10800 static tree
10801 for_each_template_parm (tree t, tree_fn_t fn, void* data,
10802 hash_set<tree> *visited,
10803 bool include_nondeduced_p,
10804 tree_fn_t any_fn)
10806 struct pair_fn_data pfd;
10807 tree result;
10809 /* Set up. */
10810 pfd.fn = fn;
10811 pfd.any_fn = any_fn;
10812 pfd.data = data;
10813 pfd.include_nondeduced_p = include_nondeduced_p;
10815 /* Walk the tree. (Conceptually, we would like to walk without
10816 duplicates, but for_each_template_parm_r recursively calls
10817 for_each_template_parm, so we would need to reorganize a fair
10818 bit to use walk_tree_without_duplicates, so we keep our own
10819 visited list.) */
10820 if (visited)
10821 pfd.visited = visited;
10822 else
10823 pfd.visited = new hash_set<tree>;
10824 result = cp_walk_tree (&t,
10825 for_each_template_parm_r,
10826 &pfd,
10827 pfd.visited);
10829 /* Clean up. */
10830 if (!visited)
10832 delete pfd.visited;
10833 pfd.visited = 0;
10836 return result;
10839 struct find_template_parameter_info
10841 explicit find_template_parameter_info (tree ctx_parms)
10842 : ctx_parms (ctx_parms),
10843 max_depth (TMPL_PARMS_DEPTH (ctx_parms))
10846 hash_set<tree> visited;
10847 hash_set<tree> parms;
10848 tree parm_list = NULL_TREE;
10849 tree *parm_list_tail = &parm_list;
10850 tree ctx_parms;
10851 int max_depth;
10853 tree find_in (tree);
10854 tree find_in_recursive (tree);
10855 bool found (tree);
10856 unsigned num_found () { return parms.elements (); }
10859 /* Appends the declaration of T to the list in DATA. */
10861 static int
10862 keep_template_parm (tree t, void* data)
10864 find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
10866 /* Template parameters declared within the expression are not part of
10867 the parameter mapping. For example, in this concept:
10869 template<typename T>
10870 concept C = requires { <expr> } -> same_as<int>;
10872 the return specifier same_as<int> declares a new decltype parameter
10873 that must not be part of the parameter mapping. The same is true
10874 for generic lambda parameters, lambda template parameters, etc. */
10875 int level;
10876 int index;
10877 template_parm_level_and_index (t, &level, &index);
10878 if (level == 0 || level > ftpi->max_depth)
10879 return 0;
10881 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
10882 /* We want the underlying TEMPLATE_TEMPLATE_PARM, not the
10883 BOUND_TEMPLATE_TEMPLATE_PARM itself. */
10884 t = TREE_TYPE (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (t));
10886 /* This template parameter might be an argument to a cached dependent
10887 specalization that was formed earlier inside some other template, in
10888 which case the parameter is not among the ones that are in-scope.
10889 Look in CTX_PARMS to find the corresponding in-scope template
10890 parameter, and use it instead. */
10891 if (tree in_scope = corresponding_template_parameter (ftpi->ctx_parms, t))
10892 t = in_scope;
10894 /* Arguments like const T yield parameters like const T. This means that
10895 a template-id like X<T, const T> would yield two distinct parameters:
10896 T and const T. Adjust types to their unqualified versions. */
10897 if (TYPE_P (t))
10898 t = TYPE_MAIN_VARIANT (t);
10899 if (!ftpi->parms.add (t))
10901 /* Append T to PARM_LIST. */
10902 tree node = build_tree_list (NULL_TREE, t);
10903 *ftpi->parm_list_tail = node;
10904 ftpi->parm_list_tail = &TREE_CHAIN (node);
10907 /* Verify the parameter we found has a valid index. */
10908 if (flag_checking)
10910 tree parms = ftpi->ctx_parms;
10911 while (TMPL_PARMS_DEPTH (parms) > level)
10912 parms = TREE_CHAIN (parms);
10913 if (int len = TREE_VEC_LENGTH (TREE_VALUE (parms)))
10914 gcc_assert (index < len);
10917 return 0;
10920 /* Ensure that we recursively examine certain terms that are not normally
10921 visited in for_each_template_parm_r. */
10923 static int
10924 any_template_parm_r (tree t, void *data)
10926 find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
10928 #define WALK_SUBTREE(NODE) \
10929 do \
10931 for_each_template_parm (NODE, keep_template_parm, data, \
10932 &ftpi->visited, true, \
10933 any_template_parm_r); \
10935 while (0)
10937 /* A mention of a member alias/typedef is a use of all of its template
10938 arguments, including those from the enclosing class, so we don't use
10939 alias_template_specialization_p here. */
10940 if (TYPE_P (t) && typedef_variant_p (t))
10941 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
10942 WALK_SUBTREE (TI_ARGS (tinfo));
10944 switch (TREE_CODE (t))
10946 case TEMPLATE_TYPE_PARM:
10947 /* Type constraints of a placeholder type may contain parameters. */
10948 if (is_auto (t))
10949 if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (t))
10950 WALK_SUBTREE (constr);
10951 break;
10953 case TEMPLATE_ID_EXPR:
10954 /* Search through references to variable templates. */
10955 WALK_SUBTREE (TREE_OPERAND (t, 0));
10956 WALK_SUBTREE (TREE_OPERAND (t, 1));
10957 break;
10959 case TEMPLATE_PARM_INDEX:
10960 WALK_SUBTREE (TREE_TYPE (t));
10961 break;
10963 case TEMPLATE_DECL:
10964 /* If T is a member template that shares template parameters with
10965 ctx_parms, we need to mark all those parameters for mapping.
10966 To that end, it should suffice to just walk the DECL_CONTEXT of
10967 the template (assuming the template is not overly general). */
10968 WALK_SUBTREE (DECL_CONTEXT (t));
10969 break;
10971 case LAMBDA_EXPR:
10973 /* Look in the parms and body. */
10974 tree fn = lambda_function (t);
10975 WALK_SUBTREE (TREE_TYPE (fn));
10976 WALK_SUBTREE (DECL_SAVED_TREE (fn));
10978 break;
10980 case IDENTIFIER_NODE:
10981 if (IDENTIFIER_CONV_OP_P (t))
10982 /* The conversion-type-id of a conversion operator may be dependent. */
10983 WALK_SUBTREE (TREE_TYPE (t));
10984 break;
10986 case CONVERT_EXPR:
10987 if (is_dummy_object (t))
10988 WALK_SUBTREE (TREE_TYPE (t));
10989 break;
10991 default:
10992 break;
10995 /* Keep walking. */
10996 return 0;
10999 /* Look through T for template parameters. */
11001 tree
11002 find_template_parameter_info::find_in (tree t)
11004 return for_each_template_parm (t, keep_template_parm, this, &visited,
11005 /*include_nondeduced*/true,
11006 any_template_parm_r);
11009 /* As above, but also recursively look into the default arguments of template
11010 parameters we found. Used for alias CTAD. */
11012 tree
11013 find_template_parameter_info::find_in_recursive (tree t)
11015 if (tree r = find_in (t))
11016 return r;
11017 /* Since newly found parms are added to the end of the list, we
11018 can just walk it until we reach the end. */
11019 for (tree pl = parm_list; pl; pl = TREE_CHAIN (pl))
11021 tree parm = TREE_VALUE (pl);
11022 tree list = corresponding_template_parameter_list (ctx_parms, parm);
11023 if (tree r = find_in (TREE_PURPOSE (list)))
11024 return r;
11026 return NULL_TREE;
11029 /* True if PARM was found by a previous call to find_in. PARM can be a
11030 TREE_LIST, a DECL_TEMPLATE_PARM_P, or a TEMPLATE_PARM_P. */
11032 bool
11033 find_template_parameter_info::found (tree parm)
11035 if (TREE_CODE (parm) == TREE_LIST)
11036 parm = TREE_VALUE (parm);
11037 if (TREE_CODE (parm) == TYPE_DECL)
11038 parm = TREE_TYPE (parm);
11039 else
11040 parm = DECL_INITIAL (parm);
11041 gcc_checking_assert (TEMPLATE_PARM_P (parm));
11042 return parms.contains (parm);
11045 /* Returns a list of unique template parameters found within T, where CTX_PARMS
11046 are the template parameters in scope. */
11048 tree
11049 find_template_parameters (tree t, tree ctx_parms)
11051 if (!ctx_parms)
11052 return NULL_TREE;
11054 find_template_parameter_info ftpi (ctx_parms);
11055 ftpi.find_in (t);
11056 return ftpi.parm_list;
11059 /* Returns true if T depends on any template parameter. */
11061 bool
11062 uses_template_parms (tree t)
11064 if (t == NULL_TREE || t == error_mark_node)
11065 return false;
11067 /* Namespaces can't depend on any template parameters. */
11068 if (TREE_CODE (t) == NAMESPACE_DECL)
11069 return false;
11071 processing_template_decl_sentinel ptds (/*reset*/false);
11072 ++processing_template_decl;
11074 if (TYPE_P (t))
11075 return dependent_type_p (t);
11076 else if (TREE_CODE (t) == TREE_VEC)
11077 return any_dependent_template_arguments_p (t);
11078 else if (TREE_CODE (t) == TREE_LIST)
11079 return (uses_template_parms (TREE_VALUE (t))
11080 || uses_template_parms (TREE_CHAIN (t)));
11081 else if (TREE_CODE (t) == TYPE_DECL)
11082 return dependent_type_p (TREE_TYPE (t));
11083 else
11084 return instantiation_dependent_expression_p (t);
11087 /* Returns true if T depends on any template parameter with level LEVEL. */
11089 bool
11090 uses_template_parms_level (tree t, int level)
11092 return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
11093 /*include_nondeduced_p=*/true);
11096 /* Returns true if the signature of DECL depends on any template parameter from
11097 its enclosing class. */
11099 static bool
11100 uses_outer_template_parms (tree decl)
11102 int depth;
11103 if (DECL_TEMPLATE_TEMPLATE_PARM_P (decl))
11104 depth = TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl)) - 1;
11105 else
11106 depth = template_class_depth (CP_DECL_CONTEXT (decl));
11107 if (depth == 0)
11108 return false;
11109 if (for_each_template_parm (TREE_TYPE (decl), template_parm_outer_level,
11110 &depth, NULL, /*include_nondeduced_p=*/true))
11111 return true;
11112 if (PRIMARY_TEMPLATE_P (decl)
11113 || DECL_TEMPLATE_TEMPLATE_PARM_P (decl))
11115 tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (decl));
11116 for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
11118 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
11119 tree defarg = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
11120 if (TREE_CODE (parm) == PARM_DECL
11121 && for_each_template_parm (TREE_TYPE (parm),
11122 template_parm_outer_level,
11123 &depth, NULL, /*nondeduced*/true))
11124 return true;
11125 if (TREE_CODE (parm) == TEMPLATE_DECL
11126 && uses_outer_template_parms (parm))
11127 return true;
11128 if (defarg
11129 && for_each_template_parm (defarg, template_parm_outer_level,
11130 &depth, NULL, /*nondeduced*/true))
11131 return true;
11134 if (uses_outer_template_parms_in_constraints (decl))
11135 return true;
11136 return false;
11139 /* Returns true if the constraints of DECL depend on any template parameters
11140 from its enclosing scope. */
11142 bool
11143 uses_outer_template_parms_in_constraints (tree decl, tree ctx/*=NULL_TREE*/)
11145 tree ci = get_constraints (decl);
11146 if (ci)
11147 ci = CI_ASSOCIATED_CONSTRAINTS (ci);
11148 if (!ci)
11149 return false;
11150 if (!ctx)
11152 if (tree fc = DECL_FRIEND_CONTEXT (decl))
11153 ctx = fc;
11154 else
11155 ctx = CP_DECL_CONTEXT (decl);
11157 int depth = template_class_depth (ctx);
11158 if (depth == 0)
11159 return false;
11160 return for_each_template_parm (ci, template_parm_outer_level,
11161 &depth, NULL, /*nondeduced*/true);
11164 /* Returns TRUE iff INST is an instantiation we don't need to do in an
11165 ill-formed translation unit, i.e. a variable or function that isn't
11166 usable in a constant expression. */
11168 static inline bool
11169 neglectable_inst_p (tree d)
11171 return (d && DECL_P (d)
11172 && !undeduced_auto_decl (d)
11173 && !(TREE_CODE (d) == FUNCTION_DECL
11174 ? FNDECL_MANIFESTLY_CONST_EVALUATED (d)
11175 : decl_maybe_constant_var_p (d)));
11178 /* Returns TRUE iff we should refuse to instantiate DECL because it's
11179 neglectable and instantiated from within an erroneous instantiation. */
11181 static bool
11182 limit_bad_template_recursion (tree decl)
11184 struct tinst_level *lev = current_tinst_level;
11185 int errs = errorcount + sorrycount;
11186 if (errs == 0 || !neglectable_inst_p (decl))
11187 return false;
11189 /* Avoid instantiating members of an ill-formed class. */
11190 bool refuse
11191 = (DECL_CLASS_SCOPE_P (decl)
11192 && CLASSTYPE_ERRONEOUS (DECL_CONTEXT (decl)));
11194 if (!refuse)
11196 for (; lev; lev = lev->next)
11197 if (neglectable_inst_p (lev->maybe_get_node ()))
11198 break;
11199 refuse = (lev && errs > lev->errors);
11202 if (refuse)
11204 /* Don't warn about it not being defined. */
11205 suppress_warning (decl, OPT_Wunused);
11206 tree clone;
11207 FOR_EACH_CLONE (clone, decl)
11208 suppress_warning (clone, OPT_Wunused);
11210 return refuse;
11213 static int tinst_depth;
11214 extern int max_tinst_depth;
11215 int depth_reached;
11217 static GTY(()) struct tinst_level *last_error_tinst_level;
11219 /* We're starting to instantiate D; record the template instantiation context
11220 at LOC for diagnostics and to restore it later. */
11222 bool
11223 push_tinst_level_loc (tree tldcl, tree targs, location_t loc)
11225 struct tinst_level *new_level;
11227 if (tinst_depth >= max_tinst_depth)
11229 /* Tell error.cc not to try to instantiate any templates. */
11230 at_eof = 3;
11231 fatal_error (input_location,
11232 "template instantiation depth exceeds maximum of %d"
11233 " (use %<-ftemplate-depth=%> to increase the maximum)",
11234 max_tinst_depth);
11235 return false;
11238 /* If the current instantiation caused problems, don't let it instantiate
11239 anything else. Do allow deduction substitution and decls usable in
11240 constant expressions. */
11241 if (!targs && limit_bad_template_recursion (tldcl))
11243 /* Avoid no_linkage_errors and unused function (and all other)
11244 warnings for this decl. */
11245 suppress_warning (tldcl);
11246 return false;
11249 /* When not -quiet, dump template instantiations other than functions, since
11250 announce_function will take care of those. */
11251 if (!quiet_flag && !targs
11252 && TREE_CODE (tldcl) != TREE_LIST
11253 && TREE_CODE (tldcl) != FUNCTION_DECL)
11254 fprintf (stderr, " %s", decl_as_string (tldcl, TFF_DECL_SPECIFIERS));
11256 new_level = tinst_level_freelist ().alloc ();
11257 new_level->tldcl = tldcl;
11258 new_level->targs = targs;
11259 new_level->locus = loc;
11260 new_level->errors = errorcount + sorrycount;
11261 new_level->next = NULL;
11262 new_level->refcount = 0;
11263 new_level->path = new_level->visible = nullptr;
11264 set_refcount_ptr (new_level->next, current_tinst_level);
11265 set_refcount_ptr (current_tinst_level, new_level);
11267 ++tinst_depth;
11268 if (GATHER_STATISTICS && (tinst_depth > depth_reached))
11269 depth_reached = tinst_depth;
11271 return true;
11274 /* We're starting substitution of TMPL<ARGS>; record the template
11275 substitution context for diagnostics and to restore it later. */
11277 bool
11278 push_tinst_level (tree tmpl, tree args)
11280 return push_tinst_level_loc (tmpl, args, input_location);
11283 /* We're starting to instantiate D; record INPUT_LOCATION and the
11284 template instantiation context for diagnostics and to restore it
11285 later. */
11287 bool
11288 push_tinst_level (tree d)
11290 return push_tinst_level_loc (d, input_location);
11293 /* Likewise, but record LOC as the program location. */
11295 bool
11296 push_tinst_level_loc (tree d, location_t loc)
11298 gcc_assert (TREE_CODE (d) != TREE_LIST);
11299 return push_tinst_level_loc (d, NULL, loc);
11302 /* We're done instantiating this template; return to the instantiation
11303 context. */
11305 void
11306 pop_tinst_level (void)
11308 /* Restore the filename and line number stashed away when we started
11309 this instantiation. */
11310 input_location = current_tinst_level->locus;
11311 set_refcount_ptr (current_tinst_level, current_tinst_level->next);
11312 --tinst_depth;
11315 /* We're instantiating a deferred template; restore the template
11316 instantiation context in which the instantiation was requested, which
11317 is one step out from LEVEL. Return the corresponding DECL or TYPE. */
11319 static tree
11320 reopen_tinst_level (struct tinst_level *level)
11322 struct tinst_level *t;
11324 tinst_depth = 0;
11325 for (t = level; t; t = t->next)
11326 ++tinst_depth;
11328 set_refcount_ptr (current_tinst_level, level);
11329 pop_tinst_level ();
11330 if (current_tinst_level)
11331 current_tinst_level->errors = errorcount+sorrycount;
11332 return level->maybe_get_node ();
11335 /* Returns the TINST_LEVEL which gives the original instantiation
11336 context. */
11338 struct tinst_level *
11339 outermost_tinst_level (void)
11341 struct tinst_level *level = current_tinst_level;
11342 if (level)
11343 while (level->next)
11344 level = level->next;
11345 return level;
11348 /* True iff T is a friend function declaration that is not itself a template
11349 and is not defined in a class template. */
11351 bool
11352 non_templated_friend_p (tree t)
11354 if (t && TREE_CODE (t) == FUNCTION_DECL
11355 && DECL_UNIQUE_FRIEND_P (t))
11357 tree ti = DECL_TEMPLATE_INFO (t);
11358 if (!ti)
11359 return true;
11360 /* DECL_FRIEND_CONTEXT is set for a friend defined in class. */
11361 if (DECL_FRIEND_CONTEXT (t))
11362 return false;
11363 /* Non-templated friends in a class template are still represented with a
11364 TEMPLATE_DECL; check that its primary template is the befriending
11365 class. Note that DECL_PRIMARY_TEMPLATE is null for
11366 template <class T> friend A<T>::f(); */
11367 tree tmpl = TI_TEMPLATE (ti);
11368 tree primary = DECL_PRIMARY_TEMPLATE (tmpl);
11369 return (primary && primary != tmpl);
11371 else
11372 return false;
11375 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL. ARGS is the
11376 vector of template arguments, as for tsubst.
11378 Returns an appropriate tsubst'd friend declaration. */
11380 static tree
11381 tsubst_friend_function (tree decl, tree args)
11383 tree new_friend;
11385 if (TREE_CODE (decl) == FUNCTION_DECL
11386 && DECL_TEMPLATE_INSTANTIATION (decl)
11387 && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
11388 /* This was a friend declared with an explicit template
11389 argument list, e.g.:
11391 friend void f<>(T);
11393 to indicate that f was a template instantiation, not a new
11394 function declaration. Now, we have to figure out what
11395 instantiation of what template. */
11397 tree template_id, arglist, fns;
11398 tree new_args;
11399 tree tmpl;
11400 tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
11402 /* Friend functions are looked up in the containing namespace scope.
11403 We must enter that scope, to avoid finding member functions of the
11404 current class with same name. */
11405 push_nested_namespace (ns);
11406 fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
11407 tf_warning_or_error, NULL_TREE);
11408 pop_nested_namespace (ns);
11409 arglist = tsubst (DECL_TI_ARGS (decl), args,
11410 tf_warning_or_error, NULL_TREE);
11411 template_id = lookup_template_function (fns, arglist);
11413 new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
11414 tmpl = determine_specialization (template_id, new_friend,
11415 &new_args,
11416 /*need_member_template=*/0,
11417 TREE_VEC_LENGTH (args),
11418 tsk_none);
11419 return instantiate_template (tmpl, new_args, tf_error);
11422 new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
11423 if (new_friend == error_mark_node)
11424 return error_mark_node;
11426 /* The NEW_FRIEND will look like an instantiation, to the
11427 compiler, but is not an instantiation from the point of view of
11428 the language. For example, we might have had:
11430 template <class T> struct S {
11431 template <class U> friend void f(T, U);
11434 Then, in S<int>, template <class U> void f(int, U) is not an
11435 instantiation of anything. */
11437 DECL_USE_TEMPLATE (new_friend) = 0;
11438 if (TREE_CODE (new_friend) == TEMPLATE_DECL)
11440 DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (new_friend) = false;
11441 DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
11442 DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
11443 = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
11445 /* Substitute TEMPLATE_PARMS_CONSTRAINTS so that parameter levels will
11446 match in decls_match. */
11447 tree parms = DECL_TEMPLATE_PARMS (new_friend);
11448 tree treqs = TEMPLATE_PARMS_CONSTRAINTS (parms);
11449 treqs = maybe_substitute_reqs_for (treqs, new_friend);
11450 if (treqs != TEMPLATE_PARMS_CONSTRAINTS (parms))
11452 TEMPLATE_PARMS_CONSTRAINTS (parms) = treqs;
11453 /* As well as each TEMPLATE_PARM_CONSTRAINTS. */
11454 tsubst_each_template_parm_constraints (parms, args,
11455 tf_warning_or_error);
11459 /* The mangled name for the NEW_FRIEND is incorrect. The function
11460 is not a template instantiation and should not be mangled like
11461 one. Therefore, we forget the mangling here; we'll recompute it
11462 later if we need it. */
11463 if (TREE_CODE (new_friend) != TEMPLATE_DECL)
11465 SET_DECL_RTL (new_friend, NULL);
11466 SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
11469 if (DECL_NAMESPACE_SCOPE_P (new_friend))
11471 tree old_decl;
11472 tree ns;
11474 /* We must save some information from NEW_FRIEND before calling
11475 duplicate decls since that function will free NEW_FRIEND if
11476 possible. */
11477 tree new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
11478 tree new_friend_result_template_info = NULL_TREE;
11479 bool new_friend_is_defn =
11480 (new_friend_template_info
11481 && (DECL_INITIAL (DECL_TEMPLATE_RESULT
11482 (template_for_substitution (new_friend)))
11483 != NULL_TREE));
11484 tree not_tmpl = new_friend;
11486 if (TREE_CODE (new_friend) == TEMPLATE_DECL)
11488 /* This declaration is a `primary' template. */
11489 DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
11491 not_tmpl = DECL_TEMPLATE_RESULT (new_friend);
11492 new_friend_result_template_info = DECL_TEMPLATE_INFO (not_tmpl);
11495 /* Inside pushdecl_namespace_level, we will push into the
11496 current namespace. However, the friend function should go
11497 into the namespace of the template. */
11498 ns = decl_namespace_context (new_friend);
11499 push_nested_namespace (ns);
11500 old_decl = pushdecl_namespace_level (new_friend, /*hiding=*/true);
11501 pop_nested_namespace (ns);
11503 if (old_decl == error_mark_node)
11504 return error_mark_node;
11506 if (old_decl != new_friend)
11508 /* This new friend declaration matched an existing
11509 declaration. For example, given:
11511 template <class T> void f(T);
11512 template <class U> class C {
11513 template <class T> friend void f(T) {}
11516 the friend declaration actually provides the definition
11517 of `f', once C has been instantiated for some type. So,
11518 old_decl will be the out-of-class template declaration,
11519 while new_friend is the in-class definition.
11521 But, if `f' was called before this point, the
11522 instantiation of `f' will have DECL_TI_ARGS corresponding
11523 to `T' but not to `U', references to which might appear
11524 in the definition of `f'. Previously, the most general
11525 template for an instantiation of `f' was the out-of-class
11526 version; now it is the in-class version. Therefore, we
11527 run through all specialization of `f', adding to their
11528 DECL_TI_ARGS appropriately. In particular, they need a
11529 new set of outer arguments, corresponding to the
11530 arguments for this class instantiation.
11532 The same situation can arise with something like this:
11534 friend void f(int);
11535 template <class T> class C {
11536 friend void f(T) {}
11539 when `C<int>' is instantiated. Now, `f(int)' is defined
11540 in the class. */
11542 if (!new_friend_is_defn)
11543 /* On the other hand, if the in-class declaration does
11544 *not* provide a definition, then we don't want to alter
11545 existing definitions. We can just leave everything
11546 alone. */
11548 else
11550 tree new_template = TI_TEMPLATE (new_friend_template_info);
11551 tree new_args = TI_ARGS (new_friend_template_info);
11553 /* Overwrite whatever template info was there before, if
11554 any, with the new template information pertaining to
11555 the declaration. */
11556 DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
11558 if (TREE_CODE (old_decl) != TEMPLATE_DECL)
11560 /* We should have called reregister_specialization in
11561 duplicate_decls. */
11562 gcc_assert (retrieve_specialization (new_template,
11563 new_args, 0)
11564 == old_decl);
11566 /* Instantiate it if the global has already been used. */
11567 if (DECL_ODR_USED (old_decl))
11568 instantiate_decl (old_decl, /*defer_ok=*/true,
11569 /*expl_inst_class_mem_p=*/false);
11571 else
11573 tree t;
11575 /* Indicate that the old function template is a partial
11576 instantiation. */
11577 DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
11578 = new_friend_result_template_info;
11580 gcc_assert (new_template
11581 == most_general_template (new_template));
11582 gcc_assert (new_template != old_decl);
11584 /* Reassign any specializations already in the hash table
11585 to the new more general template, and add the
11586 additional template args. */
11587 for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
11588 t != NULL_TREE;
11589 t = TREE_CHAIN (t))
11591 tree spec = TREE_VALUE (t);
11592 spec_entry elt;
11594 elt.tmpl = old_decl;
11595 elt.args = DECL_TI_ARGS (spec);
11596 elt.spec = NULL_TREE;
11598 decl_specializations->remove_elt (&elt);
11600 DECL_TI_ARGS (spec)
11601 = add_outermost_template_args (new_args,
11602 DECL_TI_ARGS (spec));
11604 register_specialization
11605 (spec, new_template, DECL_TI_ARGS (spec), true, 0);
11608 DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
11612 /* The information from NEW_FRIEND has been merged into OLD_DECL
11613 by duplicate_decls. */
11614 new_friend = old_decl;
11617 /* We've just introduced a namespace-scope function in the purview
11618 without necessarily having opened the enclosing namespace, so
11619 make sure the namespace is in the purview now too. */
11620 if (modules_p ()
11621 && DECL_MODULE_PURVIEW_P (STRIP_TEMPLATE (new_friend))
11622 && TREE_CODE (DECL_CONTEXT (new_friend)) == NAMESPACE_DECL)
11623 DECL_MODULE_PURVIEW_P (DECL_CONTEXT (new_friend)) = true;
11625 else
11627 tree context = DECL_CONTEXT (new_friend);
11628 bool dependent_p;
11630 /* In the code
11631 template <class T> class C {
11632 template <class U> friend void C1<U>::f (); // case 1
11633 friend void C2<T>::f (); // case 2
11635 we only need to make sure CONTEXT is a complete type for
11636 case 2. To distinguish between the two cases, we note that
11637 CONTEXT of case 1 remains dependent type after tsubst while
11638 this isn't true for case 2. */
11639 ++processing_template_decl;
11640 dependent_p = dependent_type_p (context);
11641 --processing_template_decl;
11643 if (!dependent_p
11644 && !complete_type_or_else (context, NULL_TREE))
11645 return error_mark_node;
11647 if (COMPLETE_TYPE_P (context))
11649 tree fn = new_friend;
11650 /* do_friend adds the TEMPLATE_DECL for any member friend
11651 template even if it isn't a member template, i.e.
11652 template <class T> friend A<T>::f();
11653 Look through it in that case. */
11654 if (TREE_CODE (fn) == TEMPLATE_DECL
11655 && !PRIMARY_TEMPLATE_P (fn))
11656 fn = DECL_TEMPLATE_RESULT (fn);
11657 /* Check to see that the declaration is really present, and,
11658 possibly obtain an improved declaration. */
11659 fn = check_classfn (context, fn, NULL_TREE);
11661 if (fn)
11662 new_friend = fn;
11666 return new_friend;
11669 /* FRIEND_TMPL is a friend TEMPLATE_DECL. ARGS is the vector of
11670 template arguments, as for tsubst.
11672 Returns an appropriate tsubst'd friend type or error_mark_node on
11673 failure. */
11675 static tree
11676 tsubst_friend_class (tree friend_tmpl, tree args)
11678 tree tmpl;
11680 if (DECL_TEMPLATE_TEMPLATE_PARM_P (friend_tmpl))
11682 tmpl = tsubst (TREE_TYPE (friend_tmpl), args, tf_none, NULL_TREE);
11683 return TREE_TYPE (tmpl);
11686 tree context = CP_DECL_CONTEXT (friend_tmpl);
11687 if (TREE_CODE (context) == NAMESPACE_DECL)
11688 push_nested_namespace (context);
11689 else
11691 context = tsubst (context, args, tf_error, NULL_TREE);
11692 push_nested_class (context);
11695 tmpl = lookup_name (DECL_NAME (friend_tmpl), LOOK_where::CLASS_NAMESPACE,
11696 LOOK_want::NORMAL | LOOK_want::HIDDEN_FRIEND);
11698 if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
11700 /* The friend template has already been declared. Just
11701 check to see that the declarations match, and install any new
11702 default parameters. We must tsubst the default parameters,
11703 of course. We only need the innermost template parameters
11704 because that is all that redeclare_class_template will look
11705 at. */
11706 if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
11707 > TMPL_ARGS_DEPTH (args))
11709 tree parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
11710 args, tf_warning_or_error);
11711 tsubst_each_template_parm_constraints (parms, args,
11712 tf_warning_or_error);
11713 location_t saved_input_location = input_location;
11714 input_location = DECL_SOURCE_LOCATION (friend_tmpl);
11715 tree cons = get_constraints (friend_tmpl);
11716 ++processing_template_decl;
11717 cons = tsubst_constraint_info (cons, args, tf_warning_or_error,
11718 DECL_FRIEND_CONTEXT (friend_tmpl));
11719 --processing_template_decl;
11720 redeclare_class_template (TREE_TYPE (tmpl), parms, cons);
11721 input_location = saved_input_location;
11724 else
11726 /* The friend template has not already been declared. In this
11727 case, the instantiation of the template class will cause the
11728 injection of this template into the namespace scope. */
11729 tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
11731 if (tmpl != error_mark_node)
11733 /* The new TMPL is not an instantiation of anything, so we
11734 forget its origins. We don't reset CLASSTYPE_TI_TEMPLATE
11735 for the new type because that is supposed to be the
11736 corresponding template decl, i.e., TMPL. */
11737 DECL_USE_TEMPLATE (tmpl) = 0;
11738 DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
11739 CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
11740 CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
11741 = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
11743 /* Substitute into and set the constraints on the new declaration. */
11744 if (tree ci = get_constraints (friend_tmpl))
11746 ++processing_template_decl;
11747 ci = tsubst_constraint_info (ci, args, tf_warning_or_error,
11748 DECL_FRIEND_CONTEXT (friend_tmpl));
11749 --processing_template_decl;
11750 set_constraints (tmpl, ci);
11751 tsubst_each_template_parm_constraints (DECL_TEMPLATE_PARMS (tmpl),
11752 args, tf_warning_or_error);
11755 /* Inject this template into the enclosing namspace scope. */
11756 tmpl = pushdecl_namespace_level (tmpl, /*hiding=*/true);
11760 if (TREE_CODE (context) == NAMESPACE_DECL)
11761 pop_nested_namespace (context);
11762 else
11763 pop_nested_class ();
11765 return TREE_TYPE (tmpl);
11768 /* Returns zero if TYPE cannot be completed later due to circularity.
11769 Otherwise returns one. */
11771 static int
11772 can_complete_type_without_circularity (tree type)
11774 if (type == NULL_TREE || type == error_mark_node)
11775 return 0;
11776 else if (COMPLETE_TYPE_P (type))
11777 return 1;
11778 else if (TREE_CODE (type) == ARRAY_TYPE)
11779 return can_complete_type_without_circularity (TREE_TYPE (type));
11780 else if (CLASS_TYPE_P (type)
11781 && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
11782 return 0;
11783 else
11784 return 1;
11787 static tree tsubst_omp_clauses (tree, enum c_omp_region_type, tree,
11788 tsubst_flags_t, tree);
11790 /* Instantiate the contract statement. */
11792 static tree
11793 tsubst_contract (tree decl, tree t, tree args, tsubst_flags_t complain,
11794 tree in_decl)
11796 tree type = decl ? TREE_TYPE (TREE_TYPE (decl)) : NULL_TREE;
11797 bool auto_p = type_uses_auto (type);
11799 tree r = copy_node (t);
11801 /* Rebuild the result variable. */
11802 if (type && POSTCONDITION_P (t) && POSTCONDITION_IDENTIFIER (t))
11804 tree oldvar = POSTCONDITION_IDENTIFIER (t);
11806 tree newvar = copy_node (oldvar);
11807 TREE_TYPE (newvar) = type;
11808 DECL_CONTEXT (newvar) = decl;
11809 POSTCONDITION_IDENTIFIER (r) = newvar;
11811 /* Make sure the postcondition is valid. */
11812 location_t loc = DECL_SOURCE_LOCATION (oldvar);
11813 if (!auto_p)
11814 if (!check_postcondition_result (decl, type, loc))
11815 return invalidate_contract (r);
11817 /* Make the variable available for lookup. */
11818 register_local_specialization (newvar, oldvar);
11821 /* Instantiate the condition. If the return type is undeduced, process
11822 the expression as if inside a template to avoid spurious type errors. */
11823 if (auto_p)
11824 ++processing_template_decl;
11825 ++processing_contract_condition;
11826 CONTRACT_CONDITION (r)
11827 = tsubst_expr (CONTRACT_CONDITION (t), args, complain, in_decl);
11828 --processing_contract_condition;
11829 if (auto_p)
11830 --processing_template_decl;
11832 /* And the comment. */
11833 CONTRACT_COMMENT (r)
11834 = tsubst_expr (CONTRACT_COMMENT (r), args, complain, in_decl);
11836 return r;
11839 /* Update T by instantiating its contract attribute. */
11841 static void
11842 tsubst_contract_attribute (tree decl, tree t, tree args,
11843 tsubst_flags_t complain, tree in_decl)
11845 /* For non-specializations, adjust the current declaration to the most general
11846 version of in_decl. Because we defer the instantiation of contracts as long
11847 as possible, they are still written in terms of the parameters (and return
11848 type) of the most general template. */
11849 tree tmpl = DECL_TI_TEMPLATE (in_decl);
11850 if (!DECL_TEMPLATE_SPECIALIZATION (tmpl))
11851 in_decl = DECL_TEMPLATE_RESULT (most_general_template (in_decl));
11852 local_specialization_stack specs (lss_copy);
11853 register_parameter_specializations (in_decl, decl);
11855 /* Get the contract to be instantiated. */
11856 tree contract = CONTRACT_STATEMENT (t);
11858 /* Use the complete set of template arguments for instantiation. The
11859 contract may not have been instantiated and still refer to outer levels
11860 of template parameters. */
11861 args = DECL_TI_ARGS (decl);
11863 /* For member functions, make this available for semantic analysis. */
11864 tree save_ccp = current_class_ptr;
11865 tree save_ccr = current_class_ref;
11866 if (DECL_IOBJ_MEMBER_FUNCTION_P (decl))
11868 tree arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
11869 tree this_type = TREE_TYPE (TREE_VALUE (arg_types));
11870 inject_this_parameter (this_type, cp_type_quals (this_type));
11873 contract = tsubst_contract (decl, contract, args, complain, in_decl);
11875 current_class_ptr = save_ccp;
11876 current_class_ref = save_ccr;
11878 /* Rebuild the attribute. */
11879 TREE_VALUE (t) = build_tree_list (NULL_TREE, contract);
11882 /* Rebuild the attribute list for DECL, substituting into contracts
11883 as needed. */
11885 void
11886 tsubst_contract_attributes (tree decl, tree args, tsubst_flags_t complain, tree in_decl)
11888 tree list = copy_list (DECL_ATTRIBUTES (decl));
11889 for (tree attr = list; attr; attr = CONTRACT_CHAIN (attr))
11891 if (cxx_contract_attribute_p (attr))
11892 tsubst_contract_attribute (decl, attr, args, complain, in_decl);
11894 DECL_ATTRIBUTES (decl) = list;
11897 /* Instantiate a single dependent attribute T (a TREE_LIST), and return either
11898 T or a new TREE_LIST, possibly a chain in the case of a pack expansion. */
11900 static tree
11901 tsubst_attribute (tree t, tree *decl_p, tree args,
11902 tsubst_flags_t complain, tree in_decl)
11904 gcc_assert (ATTR_IS_DEPENDENT (t));
11906 /* Note that contract attributes are never substituted from this function.
11907 Their instantiation is triggered by regenerate_from_template_decl when
11908 we instantiate the body of the function. */
11910 tree val = TREE_VALUE (t);
11911 if (val == NULL_TREE)
11912 /* Nothing to do. */;
11913 else if ((flag_openmp || flag_openmp_simd)
11914 && is_attribute_p ("omp declare simd",
11915 get_attribute_name (t)))
11917 tree clauses = TREE_VALUE (val);
11918 clauses = tsubst_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD, args,
11919 complain, in_decl);
11920 c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
11921 clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
11922 tree parms = DECL_ARGUMENTS (*decl_p);
11923 clauses
11924 = c_omp_declare_simd_clauses_to_numbers (parms, clauses);
11925 if (clauses)
11926 val = build_tree_list (NULL_TREE, clauses);
11927 else
11928 val = NULL_TREE;
11930 else if (flag_openmp
11931 && is_attribute_p ("omp declare variant base",
11932 get_attribute_name (t)))
11934 ++cp_unevaluated_operand;
11935 tree varid = tsubst_expr (TREE_PURPOSE (val), args, complain, in_decl);
11936 --cp_unevaluated_operand;
11937 tree chain = TREE_CHAIN (val);
11938 location_t match_loc = cp_expr_loc_or_input_loc (TREE_PURPOSE (chain));
11939 tree ctx = copy_list (TREE_VALUE (val));
11940 for (tree tss = ctx; tss; tss = TREE_CHAIN (tss))
11942 enum omp_tss_code set = OMP_TSS_CODE (tss);
11943 tree selectors = NULL_TREE;
11944 for (tree ts = OMP_TSS_TRAIT_SELECTORS (tss); ts;
11945 ts = TREE_CHAIN (ts))
11947 tree properties = NULL_TREE;
11948 tree scoreval = NULL_TREE;
11949 /* FIXME: The body of this loop should really be dispatching
11950 according to omp_ts_map[OMP_TS_CODE (TS)].tp_type instead
11951 of having hard-wired knowledge of specific selectors. */
11952 if (OMP_TS_CODE (ts) == OMP_TRAIT_CONSTRUCT_SIMD
11953 && set == OMP_TRAIT_SET_CONSTRUCT)
11955 tree clauses = OMP_TS_PROPERTIES (ts);
11956 clauses = tsubst_omp_clauses (clauses,
11957 C_ORT_OMP_DECLARE_SIMD, args,
11958 complain, in_decl);
11959 c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
11960 clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
11961 properties = clauses;
11963 else
11965 tree v = OMP_TS_SCORE (ts);
11966 if (v)
11968 v = tsubst_expr (v, args, complain, in_decl);
11969 v = fold_non_dependent_expr (v);
11970 if (!INTEGRAL_TYPE_P (TREE_TYPE (v))
11971 || TREE_CODE (v) != INTEGER_CST)
11973 location_t loc
11974 = cp_expr_loc_or_loc (OMP_TS_SCORE (ts),
11975 match_loc);
11976 error_at (loc, "score argument must be "
11977 "constant integer expression");
11978 return NULL_TREE;
11980 else if (tree_int_cst_sgn (v) < 0)
11982 location_t loc
11983 = cp_expr_loc_or_loc (OMP_TS_SCORE (ts),
11984 match_loc);
11985 error_at (loc, "score argument must be "
11986 "non-negative");
11987 return NULL_TREE;
11989 scoreval = v;
11991 properties = copy_list (OMP_TS_PROPERTIES (ts));
11992 for (tree p = properties; p; p = TREE_CHAIN (p))
11993 if (OMP_TP_NAME (p) == OMP_TP_NAMELIST_NODE)
11994 continue;
11995 else if (OMP_TP_VALUE (p))
11997 bool allow_string
11998 = (OMP_TS_CODE (ts) != OMP_TRAIT_USER_CONDITION
11999 || set != OMP_TRAIT_SET_USER);
12000 tree v = OMP_TP_VALUE (p);
12001 if (TREE_CODE (v) == STRING_CST && allow_string)
12002 continue;
12003 v = tsubst_expr (v, args, complain, in_decl);
12004 v = fold_non_dependent_expr (v);
12005 if (!INTEGRAL_TYPE_P (TREE_TYPE (v))
12006 || !tree_fits_shwi_p (v))
12008 location_t loc
12009 = cp_expr_loc_or_loc (OMP_TP_VALUE (p),
12010 match_loc);
12011 if (allow_string)
12012 error_at (loc, "property must be constant "
12013 "integer expression or string "
12014 "literal");
12015 else
12016 error_at (loc, "property must be constant "
12017 "integer expression");
12018 return NULL_TREE;
12020 OMP_TP_VALUE (p) = v;
12023 selectors = make_trait_selector (OMP_TS_CODE (ts), scoreval,
12024 properties, selectors);
12026 OMP_TSS_TRAIT_SELECTORS (tss) = nreverse (selectors);
12028 val = tree_cons (varid, ctx, chain);
12030 /* If the first attribute argument is an identifier, don't
12031 pass it through tsubst. Attributes like mode, format,
12032 cleanup and several target specific attributes expect it
12033 unmodified. */
12034 else if (attribute_takes_identifier_p (get_attribute_name (t)))
12036 tree chain
12037 = tsubst_expr (TREE_CHAIN (val), args, complain, in_decl);
12038 if (chain != TREE_CHAIN (val))
12039 val = tree_cons (NULL_TREE, TREE_VALUE (val), chain);
12041 else if (PACK_EXPANSION_P (val))
12043 /* An attribute pack expansion. */
12044 tree purp = TREE_PURPOSE (t);
12045 tree pack = tsubst_pack_expansion (val, args, complain, in_decl);
12046 if (pack == error_mark_node)
12047 return error_mark_node;
12048 int len = TREE_VEC_LENGTH (pack);
12049 tree list = NULL_TREE;
12050 tree *q = &list;
12051 for (int i = 0; i < len; ++i)
12053 tree elt = TREE_VEC_ELT (pack, i);
12054 *q = build_tree_list (purp, elt);
12055 q = &TREE_CHAIN (*q);
12057 return list;
12059 else
12060 val = tsubst_expr (val, args, complain, in_decl);
12062 if (val == error_mark_node)
12063 return error_mark_node;
12064 if (val != TREE_VALUE (t))
12065 return build_tree_list (TREE_PURPOSE (t), val);
12066 return t;
12069 /* Instantiate any dependent attributes in ATTRIBUTES, returning either it
12070 unchanged or a new TREE_LIST chain. */
12072 static tree
12073 tsubst_attributes (tree attributes, tree args,
12074 tsubst_flags_t complain, tree in_decl)
12076 tree last_dep = NULL_TREE;
12078 for (tree t = attributes; t; t = TREE_CHAIN (t))
12079 if (ATTR_IS_DEPENDENT (t))
12081 last_dep = t;
12082 attributes = copy_list (attributes);
12083 break;
12086 if (last_dep)
12087 for (tree *p = &attributes; *p; )
12089 tree t = *p;
12090 if (ATTR_IS_DEPENDENT (t))
12092 tree subst = tsubst_attribute (t, NULL, args, complain, in_decl);
12093 if (subst != t)
12095 *p = subst;
12096 while (*p)
12097 p = &TREE_CHAIN (*p);
12098 *p = TREE_CHAIN (t);
12099 continue;
12102 p = &TREE_CHAIN (*p);
12105 return attributes;
12108 /* Apply any attributes which had to be deferred until instantiation
12109 time. DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
12110 ARGS, COMPLAIN, IN_DECL are as tsubst. Returns true normally,
12111 false on error. */
12113 static bool
12114 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
12115 tree args, tsubst_flags_t complain, tree in_decl)
12117 tree t;
12118 tree *p;
12120 if (attributes == NULL_TREE)
12121 return true;
12123 if (DECL_P (*decl_p))
12125 if (TREE_TYPE (*decl_p) == error_mark_node)
12126 return false;
12127 p = &DECL_ATTRIBUTES (*decl_p);
12128 /* DECL_ATTRIBUTES comes from copy_node in tsubst_decl, and is identical
12129 to our attributes parameter. */
12130 gcc_assert (*p == attributes);
12132 else
12134 p = &TYPE_ATTRIBUTES (*decl_p);
12135 /* TYPE_ATTRIBUTES was set up (with abi_tag and may_alias) in
12136 lookup_template_class_1, and should be preserved. */
12137 gcc_assert (*p != attributes);
12138 while (*p)
12139 p = &TREE_CHAIN (*p);
12142 /* save_template_attributes puts the dependent attributes at the beginning of
12143 the list; find the non-dependent ones. */
12144 for (t = attributes; t; t = TREE_CHAIN (t))
12145 if (!ATTR_IS_DEPENDENT (t))
12146 break;
12147 tree nondep = t;
12149 /* Apply any non-dependent attributes. */
12150 *p = nondep;
12152 if (nondep == attributes)
12153 return true;
12155 /* And then any dependent ones. */
12156 tree late_attrs = NULL_TREE;
12157 tree *q = &late_attrs;
12158 for (t = attributes; t != nondep; t = TREE_CHAIN (t))
12160 *q = tsubst_attribute (t, decl_p, args, complain, in_decl);
12161 if (*q == error_mark_node)
12162 return false;
12163 if (*q == t)
12165 *q = copy_node (t);
12166 TREE_CHAIN (*q) = NULL_TREE;
12168 while (*q)
12169 q = &TREE_CHAIN (*q);
12172 /* cplus_decl_attributes can add some attributes implicitly. For templates,
12173 those attributes should have been added already when those templates were
12174 parsed, and shouldn't be added based on from which context they are
12175 first time instantiated. */
12176 auto o1 = make_temp_override (current_optimize_pragma, NULL_TREE);
12177 auto o2 = make_temp_override (optimization_current_node,
12178 optimization_default_node);
12179 auto o3 = make_temp_override (current_target_pragma, NULL_TREE);
12180 auto o4 = make_temp_override (scope_chain->omp_declare_target_attribute,
12181 NULL);
12182 auto o5 = make_temp_override (scope_chain->omp_begin_assumes, NULL);
12184 cplus_decl_attributes (decl_p, late_attrs, attr_flags);
12186 return true;
12189 /* The template TMPL is being instantiated with the template arguments TARGS.
12190 Perform the access checks that we deferred when parsing the template. */
12192 static void
12193 perform_instantiation_time_access_checks (tree tmpl, tree targs)
12195 unsigned i;
12196 deferred_access_check *chk;
12198 if (!CLASS_TYPE_P (tmpl) && TREE_CODE (tmpl) != FUNCTION_DECL)
12199 return;
12201 if (vec<deferred_access_check, va_gc> *access_checks
12202 = TI_DEFERRED_ACCESS_CHECKS (get_template_info (tmpl)))
12203 FOR_EACH_VEC_ELT (*access_checks, i, chk)
12205 tree decl = chk->decl;
12206 tree diag_decl = chk->diag_decl;
12207 tree type_scope = TREE_TYPE (chk->binfo);
12209 if (uses_template_parms (type_scope))
12210 type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
12212 /* Make access check error messages point to the location
12213 of the use of the typedef. */
12214 iloc_sentinel ils (chk->loc);
12215 perform_or_defer_access_check (TYPE_BINFO (type_scope),
12216 decl, diag_decl, tf_warning_or_error);
12220 tree
12221 instantiate_class_template (tree type)
12223 auto_timevar tv (TV_TEMPLATE_INST);
12225 tree templ, args, pattern, t, member;
12226 tree typedecl;
12227 tree pbinfo;
12228 tree base_list;
12229 unsigned int saved_maximum_field_alignment;
12230 tree fn_context;
12232 if (type == error_mark_node)
12233 return error_mark_node;
12235 if (COMPLETE_OR_OPEN_TYPE_P (type)
12236 || uses_template_parms (type))
12237 return type;
12239 /* Figure out which template is being instantiated. */
12240 templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
12241 gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
12243 /* Mark the type as in the process of being defined. */
12244 TYPE_BEING_DEFINED (type) = 1;
12246 /* We may be in the middle of deferred access check. Disable
12247 it now. */
12248 deferring_access_check_sentinel acs (dk_no_deferred);
12250 /* Determine what specialization of the original template to
12251 instantiate. */
12252 t = most_specialized_partial_spec (type, tf_warning_or_error);
12253 if (t == error_mark_node)
12254 return error_mark_node;
12255 else if (t)
12257 /* This TYPE is actually an instantiation of a partial
12258 specialization. We replace the innermost set of ARGS with
12259 the arguments appropriate for substitution. For example,
12260 given:
12262 template <class T> struct S {};
12263 template <class T> struct S<T*> {};
12265 and supposing that we are instantiating S<int*>, ARGS will
12266 presently be {int*} -- but we need {int}. */
12267 pattern = TREE_TYPE (TI_TEMPLATE (t));
12268 args = TI_ARGS (t);
12270 else
12272 pattern = TREE_TYPE (templ);
12273 args = CLASSTYPE_TI_ARGS (type);
12276 /* If the template we're instantiating is incomplete, then clearly
12277 there's nothing we can do. */
12278 if (!COMPLETE_TYPE_P (pattern))
12280 /* We can try again later. */
12281 TYPE_BEING_DEFINED (type) = 0;
12282 return type;
12285 /* If we've recursively instantiated too many templates, stop. */
12286 if (! push_tinst_level (type))
12287 return type;
12289 int saved_unevaluated_operand = cp_unevaluated_operand;
12290 int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
12292 fn_context = decl_function_context (TYPE_MAIN_DECL (type));
12293 /* Also avoid push_to_top_level for a lambda in an NSDMI. */
12294 if (!fn_context && LAMBDA_TYPE_P (type) && TYPE_CLASS_SCOPE_P (type))
12295 fn_context = error_mark_node;
12296 if (!fn_context)
12297 push_to_top_level ();
12298 else
12300 cp_unevaluated_operand = 0;
12301 c_inhibit_evaluation_warnings = 0;
12304 mark_template_arguments_used (templ, CLASSTYPE_TI_ARGS (type));
12306 /* Use #pragma pack from the template context. */
12307 saved_maximum_field_alignment = maximum_field_alignment;
12308 maximum_field_alignment = TYPE_PRECISION (pattern);
12310 SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
12312 /* Set the input location to the most specialized template definition.
12313 This is needed if tsubsting causes an error. */
12314 typedecl = TYPE_MAIN_DECL (pattern);
12315 input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
12316 DECL_SOURCE_LOCATION (typedecl);
12318 set_instantiating_module (TYPE_NAME (type));
12320 TYPE_PACKED (type) = TYPE_PACKED (pattern);
12321 SET_TYPE_ALIGN (type, TYPE_ALIGN (pattern));
12322 TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
12323 CLASSTYPE_NON_AGGREGATE (type) = CLASSTYPE_NON_AGGREGATE (pattern);
12324 if (ANON_AGGR_TYPE_P (pattern))
12325 SET_ANON_AGGR_TYPE_P (type);
12326 if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
12328 CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
12329 CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
12330 /* Adjust visibility for template arguments. */
12331 determine_visibility (TYPE_MAIN_DECL (type));
12333 if (CLASS_TYPE_P (type))
12334 CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
12336 pbinfo = TYPE_BINFO (pattern);
12338 /* We should never instantiate a nested class before its enclosing
12339 class; we need to look up the nested class by name before we can
12340 instantiate it, and that lookup should instantiate the enclosing
12341 class. */
12342 gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
12343 || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
12345 base_list = NULL_TREE;
12346 /* Defer access checking while we substitute into the types named in
12347 the base-clause. */
12348 push_deferring_access_checks (dk_deferred);
12349 if (BINFO_N_BASE_BINFOS (pbinfo))
12351 tree pbase_binfo;
12352 int i;
12354 /* Substitute into each of the bases to determine the actual
12355 basetypes. */
12356 for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
12358 tree base;
12359 tree access = BINFO_BASE_ACCESS (pbinfo, i);
12360 tree expanded_bases = NULL_TREE;
12361 int idx, len = 1;
12363 if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
12365 expanded_bases =
12366 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
12367 args, tf_error, NULL_TREE);
12368 if (expanded_bases == error_mark_node)
12369 continue;
12371 len = TREE_VEC_LENGTH (expanded_bases);
12374 for (idx = 0; idx < len; idx++)
12376 if (expanded_bases)
12377 /* Extract the already-expanded base class. */
12378 base = TREE_VEC_ELT (expanded_bases, idx);
12379 else
12380 /* Substitute to figure out the base class. */
12381 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error,
12382 NULL_TREE);
12384 if (base == error_mark_node)
12385 continue;
12387 base_list = tree_cons (access, base, base_list);
12388 if (BINFO_VIRTUAL_P (pbase_binfo))
12389 TREE_TYPE (base_list) = integer_type_node;
12393 /* The list is now in reverse order; correct that. */
12394 base_list = nreverse (base_list);
12396 /* Now call xref_basetypes to set up all the base-class
12397 information. */
12398 xref_basetypes (type, base_list);
12400 apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
12401 (int) ATTR_FLAG_TYPE_IN_PLACE,
12402 args, tf_error, NULL_TREE);
12403 fixup_attribute_variants (type);
12405 /* Now that our base classes are set up, enter the scope of the
12406 class, so that name lookups into base classes, etc. will work
12407 correctly. This is precisely analogous to what we do in
12408 begin_class_definition when defining an ordinary non-template
12409 class, except we also need to push the enclosing classes. */
12410 push_nested_class (type);
12412 /* Now check accessibility of the types named in its base-clause,
12413 relative to the scope of the class. */
12414 pop_to_parent_deferring_access_checks ();
12416 /* A vector to hold members marked with attribute used. */
12417 auto_vec<tree> used;
12419 /* Now members are processed in the order of declaration. */
12420 for (member = CLASSTYPE_DECL_LIST (pattern);
12421 member; member = TREE_CHAIN (member))
12423 tree t = TREE_VALUE (member);
12425 if (TREE_PURPOSE (member))
12427 if (TYPE_P (t))
12429 if (LAMBDA_TYPE_P (t))
12430 /* A closure type for a lambda in an NSDMI or default argument.
12431 Ignore it; it will be regenerated when needed. */
12432 continue;
12434 /* If the member is a class template, we've
12435 already substituted its type. */
12436 if (CLASS_TYPE_P (t)
12437 && CLASSTYPE_IS_TEMPLATE (t))
12438 continue;
12440 tree newtag = tsubst (t, args, tf_error, NULL_TREE);
12441 if (newtag == error_mark_node)
12442 continue;
12444 if (TREE_CODE (newtag) != ENUMERAL_TYPE)
12446 tree name = TYPE_IDENTIFIER (t);
12448 /* Now, install the tag. We don't use pushtag
12449 because that does too much work -- creating an
12450 implicit typedef, which we've already done. */
12451 set_identifier_type_value (name, TYPE_NAME (newtag));
12452 maybe_add_class_template_decl_list (type, newtag, false);
12453 TREE_PUBLIC (TYPE_NAME (newtag)) = true;
12454 determine_visibility (TYPE_NAME (newtag));
12457 else if (DECL_DECLARES_FUNCTION_P (t))
12459 tree r;
12461 if (TREE_CODE (t) == TEMPLATE_DECL)
12462 ++processing_template_decl;
12463 r = tsubst (t, args, tf_error, NULL_TREE);
12464 if (TREE_CODE (t) == TEMPLATE_DECL)
12465 --processing_template_decl;
12467 set_current_access_from_decl (r);
12468 finish_member_declaration (r);
12469 /* Instantiate members marked with attribute used. */
12470 if (r != error_mark_node && DECL_PRESERVE_P (r))
12471 used.safe_push (r);
12472 if (TREE_CODE (r) == FUNCTION_DECL
12473 && DECL_OMP_DECLARE_REDUCTION_P (r))
12474 cp_check_omp_declare_reduction (r);
12476 else if ((DECL_CLASS_TEMPLATE_P (t) || DECL_IMPLICIT_TYPEDEF_P (t))
12477 && LAMBDA_TYPE_P (TREE_TYPE (t)))
12478 /* A closure type for a lambda in an NSDMI or default argument.
12479 Ignore it; it will be regenerated when needed. */;
12480 else
12482 /* Build new TYPE_FIELDS. */
12483 if (TREE_CODE (t) == STATIC_ASSERT)
12484 tsubst_stmt (t, args, tf_warning_or_error, NULL_TREE);
12485 else if (TREE_CODE (t) != CONST_DECL)
12487 tree r;
12488 tree vec = NULL_TREE;
12489 int len = 1;
12491 gcc_checking_assert (TREE_CODE (t) != CONST_DECL);
12492 /* The file and line for this declaration, to
12493 assist in error message reporting. Since we
12494 called push_tinst_level above, we don't need to
12495 restore these. */
12496 input_location = DECL_SOURCE_LOCATION (t);
12498 if (TREE_CODE (t) == TEMPLATE_DECL)
12499 ++processing_template_decl;
12500 r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
12501 if (TREE_CODE (t) == TEMPLATE_DECL)
12502 --processing_template_decl;
12504 if (TREE_CODE (r) == TREE_VEC)
12506 /* A capture pack became multiple fields. */
12507 vec = r;
12508 len = TREE_VEC_LENGTH (vec);
12511 for (int i = 0; i < len; ++i)
12513 if (vec)
12514 r = TREE_VEC_ELT (vec, i);
12515 if (VAR_P (r))
12517 /* In [temp.inst]:
12519 [t]he initialization (and any associated
12520 side-effects) of a static data member does
12521 not occur unless the static data member is
12522 itself used in a way that requires the
12523 definition of the static data member to
12524 exist.
12526 Therefore, we do not substitute into the
12527 initialized for the static data member here. */
12528 finish_static_data_member_decl
12530 /*init=*/NULL_TREE,
12531 /*init_const_expr_p=*/false,
12532 /*asmspec_tree=*/NULL_TREE,
12533 /*flags=*/0);
12534 /* Instantiate members marked with attribute used. */
12535 if (r != error_mark_node && DECL_PRESERVE_P (r))
12536 used.safe_push (r);
12538 else if (TREE_CODE (r) == FIELD_DECL)
12540 /* Determine whether R has a valid type and can be
12541 completed later. If R is invalid, then its type
12542 is replaced by error_mark_node. */
12543 tree rtype = TREE_TYPE (r);
12544 if (can_complete_type_without_circularity (rtype))
12545 complete_type (rtype);
12547 if (!complete_or_array_type_p (rtype))
12549 /* If R's type couldn't be completed and
12550 it isn't a flexible array member (whose
12551 type is incomplete by definition) give
12552 an error. */
12553 cxx_incomplete_type_error (r, rtype);
12554 TREE_TYPE (r) = error_mark_node;
12556 else if (TREE_CODE (rtype) == ARRAY_TYPE
12557 && TYPE_DOMAIN (rtype) == NULL_TREE
12558 && (TREE_CODE (type) == UNION_TYPE
12559 || TREE_CODE (type) == QUAL_UNION_TYPE))
12561 error ("flexible array member %qD in union", r);
12562 TREE_TYPE (r) = error_mark_node;
12564 else if (!verify_type_context (input_location,
12565 TCTX_FIELD, rtype))
12566 TREE_TYPE (r) = error_mark_node;
12569 /* If it is a TYPE_DECL for a class-scoped
12570 ENUMERAL_TYPE, such a thing will already have
12571 been added to the field list by tsubst_enum
12572 in finish_member_declaration case above. */
12573 if (!(TREE_CODE (r) == TYPE_DECL
12574 && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
12575 && DECL_ARTIFICIAL (r)))
12577 set_current_access_from_decl (r);
12578 finish_member_declaration (r);
12584 else
12586 if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t)
12587 || DECL_TEMPLATE_TEMPLATE_PARM_P (t))
12589 /* Build new CLASSTYPE_FRIEND_CLASSES. */
12591 tree friend_type = t;
12592 if (TREE_CODE (friend_type) == TEMPLATE_DECL)
12594 /* template <class T> friend class C; */
12595 friend_type = tsubst_friend_class (friend_type, args);
12597 else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
12599 /* template <class T> friend class C::D; */
12600 friend_type = tsubst (friend_type, args,
12601 tf_warning_or_error, NULL_TREE);
12602 if (TREE_CODE (friend_type) == TEMPLATE_DECL)
12603 friend_type = TREE_TYPE (friend_type);
12605 else if (TREE_CODE (friend_type) == TYPENAME_TYPE
12606 || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
12608 /* This could be either
12610 friend class T::C;
12612 when dependent_type_p is false or
12614 template <class U> friend class T::C;
12616 otherwise. */
12617 /* Bump processing_template_decl in case this is something like
12618 template <class T> friend struct A<T>::B. */
12619 ++processing_template_decl;
12620 friend_type = tsubst (friend_type, args,
12621 tf_warning_or_error, NULL_TREE);
12622 --processing_template_decl;
12624 else if (uses_template_parms (friend_type))
12625 /* friend class C<T>; */
12626 friend_type = tsubst (friend_type, args,
12627 tf_warning_or_error, NULL_TREE);
12629 /* Otherwise it's
12631 friend class C;
12633 where C is already declared or
12635 friend class C<int>;
12637 We don't have to do anything in these cases. */
12639 if (friend_type != error_mark_node)
12640 make_friend_class (type, friend_type, /*complain=*/false);
12642 else
12644 /* Build new DECL_FRIENDLIST. */
12645 tree r;
12647 /* The file and line for this declaration, to
12648 assist in error message reporting. Since we
12649 called push_tinst_level above, we don't need to
12650 restore these. */
12651 input_location = DECL_SOURCE_LOCATION (t);
12653 if (TREE_CODE (t) == TEMPLATE_DECL)
12655 ++processing_template_decl;
12656 push_deferring_access_checks (dk_no_check);
12659 r = tsubst_friend_function (t, args);
12660 add_friend (type, r, /*complain=*/false);
12661 if (TREE_CODE (t) == TEMPLATE_DECL)
12663 pop_deferring_access_checks ();
12664 --processing_template_decl;
12670 if (fn_context)
12672 /* Restore these before substituting into the lambda capture
12673 initializers. */
12674 cp_unevaluated_operand = saved_unevaluated_operand;
12675 c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
12678 /* Set the file and line number information to whatever is given for
12679 the class itself. This puts error messages involving generated
12680 implicit functions at a predictable point, and the same point
12681 that would be used for non-template classes. */
12682 input_location = DECL_SOURCE_LOCATION (typedecl);
12684 unreverse_member_declarations (type);
12685 finish_struct_1 (type);
12686 TYPE_BEING_DEFINED (type) = 0;
12688 /* Remember if instantiating this class ran into errors, so we can avoid
12689 instantiating member functions in limit_bad_template_recursion. We set
12690 this flag even if the problem was in another instantiation triggered by
12691 this one, as that will likely also cause trouble for member functions. */
12692 if (errorcount + sorrycount > current_tinst_level->errors)
12693 CLASSTYPE_ERRONEOUS (type) = true;
12695 /* We don't instantiate default arguments for member functions. 14.7.1:
12697 The implicit instantiation of a class template specialization causes
12698 the implicit instantiation of the declarations, but not of the
12699 definitions or default arguments, of the class member functions,
12700 member classes, static data members and member templates.... */
12702 perform_instantiation_time_access_checks (pattern, args);
12703 perform_deferred_access_checks (tf_warning_or_error);
12705 /* Now that we've gone through all the members, instantiate those
12706 marked with attribute used. We must do this in the context of
12707 the class -- not the context we pushed from, as that might be
12708 inside a template and change the behaviour of mark_used. */
12709 for (tree x : used)
12710 mark_used (x);
12712 pop_nested_class ();
12713 maximum_field_alignment = saved_maximum_field_alignment;
12714 if (!fn_context)
12715 pop_from_top_level ();
12716 pop_tinst_level ();
12718 /* The vtable for a template class can be emitted in any translation
12719 unit in which the class is instantiated. When there is no key
12720 method, however, finish_struct_1 will already have added TYPE to
12721 the keyed_classes. */
12722 if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
12723 vec_safe_push (keyed_classes, type);
12725 return type;
12728 tree
12729 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12731 tree r;
12733 if (!t)
12734 r = t;
12735 else if (TYPE_P (t))
12736 r = tsubst (t, args, complain, in_decl);
12737 else
12739 if (!(complain & tf_warning))
12740 ++c_inhibit_evaluation_warnings;
12741 r = tsubst_expr (t, args, complain, in_decl);
12742 if (!(complain & tf_warning))
12743 --c_inhibit_evaluation_warnings;
12746 return r;
12749 /* Given a function parameter pack TMPL_PARM and some function parameters
12750 instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
12751 and set *SPEC_P to point at the next point in the list. */
12753 tree
12754 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
12756 /* Collect all of the extra "packed" parameters into an
12757 argument pack. */
12758 tree argpack;
12759 tree spec_parm = *spec_p;
12760 int len;
12762 for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
12763 if (tmpl_parm
12764 && !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
12765 break;
12767 spec_parm = *spec_p;
12768 if (len == 1 && DECL_PACK_P (spec_parm))
12770 /* The instantiation is still a parameter pack; don't wrap it in a
12771 NONTYPE_ARGUMENT_PACK. */
12772 argpack = spec_parm;
12773 spec_parm = DECL_CHAIN (spec_parm);
12775 else
12777 /* Fill in PARMVEC with all of the parameters. */
12778 tree parmvec = make_tree_vec (len);
12779 argpack = make_node (NONTYPE_ARGUMENT_PACK);
12780 for (int i = 0; i < len; i++)
12782 tree elt = spec_parm;
12783 if (DECL_PACK_P (elt))
12784 elt = make_pack_expansion (elt);
12785 TREE_VEC_ELT (parmvec, i) = elt;
12786 spec_parm = DECL_CHAIN (spec_parm);
12789 /* Build the argument packs. */
12790 ARGUMENT_PACK_ARGS (argpack) = parmvec;
12792 *spec_p = spec_parm;
12794 return argpack;
12797 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
12798 NONTYPE_ARGUMENT_PACK. */
12800 static tree
12801 make_fnparm_pack (tree spec_parm)
12803 return extract_fnparm_pack (NULL_TREE, &spec_parm);
12806 /* Return 1 if the Ith element of the argument pack ARG_PACK is a
12807 pack expansion with no extra args, 2 if it has extra args, or 0
12808 if it is not a pack expansion. */
12810 static int
12811 argument_pack_element_is_expansion_p (tree arg_pack, int i)
12813 if (TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
12814 /* We're being called before this happens in tsubst_pack_expansion. */
12815 arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
12816 tree vec = ARGUMENT_PACK_ARGS (arg_pack);
12817 if (i >= TREE_VEC_LENGTH (vec))
12818 return 0;
12819 tree elt = TREE_VEC_ELT (vec, i);
12820 if (DECL_P (elt))
12821 /* A decl pack is itself an expansion. */
12822 elt = TREE_TYPE (elt);
12823 if (!PACK_EXPANSION_P (elt))
12824 return 0;
12825 if (PACK_EXPANSION_EXTRA_ARGS (elt))
12826 return 2;
12827 return 1;
12831 /* Creates and return an ARGUMENT_PACK_SELECT tree node. */
12833 static tree
12834 make_argument_pack_select (tree arg_pack, unsigned index)
12836 tree aps = make_node (ARGUMENT_PACK_SELECT);
12838 ARGUMENT_PACK_SELECT_FROM_PACK (aps) = arg_pack;
12839 ARGUMENT_PACK_SELECT_INDEX (aps) = index;
12841 return aps;
12844 /* This is a subroutine of tsubst_pack_expansion.
12846 It returns TRUE if we need to use the PACK_EXPANSION_EXTRA_ARGS
12847 mechanism to store the (non complete list of) arguments of the
12848 substitution and return a non substituted pack expansion, in order
12849 to wait for when we have enough arguments to really perform the
12850 substitution. */
12852 static bool
12853 use_pack_expansion_extra_args_p (tree t,
12854 tree parm_packs,
12855 int arg_pack_len,
12856 bool has_empty_arg)
12858 if (has_empty_arg
12859 && PACK_EXPANSION_FORCE_EXTRA_ARGS_P (t))
12860 return true;
12862 /* If one pack has an expansion and another pack has a normal
12863 argument or if one pack has an empty argument and an another
12864 one hasn't then tsubst_pack_expansion cannot perform the
12865 substitution and need to fall back on the
12866 PACK_EXPANSION_EXTRA mechanism. */
12867 if (parm_packs == NULL_TREE)
12868 return false;
12869 else if (has_empty_arg)
12871 /* If all the actual packs are pack expansions, we can still
12872 subsitute directly. */
12873 for (tree p = parm_packs; p; p = TREE_CHAIN (p))
12875 tree a = TREE_VALUE (p);
12876 if (TREE_CODE (a) == ARGUMENT_PACK_SELECT)
12877 a = ARGUMENT_PACK_SELECT_FROM_PACK (a);
12878 a = ARGUMENT_PACK_ARGS (a);
12879 if (TREE_VEC_LENGTH (a) == 1)
12880 a = TREE_VEC_ELT (a, 0);
12881 if (PACK_EXPANSION_P (a))
12882 continue;
12883 return true;
12885 return false;
12888 for (int i = 0 ; i < arg_pack_len; ++i)
12890 bool has_expansion_arg = false;
12891 bool has_non_expansion_arg = false;
12892 for (tree parm_pack = parm_packs;
12893 parm_pack;
12894 parm_pack = TREE_CHAIN (parm_pack))
12896 tree arg = TREE_VALUE (parm_pack);
12898 int exp = argument_pack_element_is_expansion_p (arg, i);
12899 if (exp == 2)
12900 /* We can't substitute a pack expansion with extra args into
12901 our pattern. */
12902 return true;
12903 else if (exp)
12904 has_expansion_arg = true;
12905 else
12906 has_non_expansion_arg = true;
12909 if (has_expansion_arg && has_non_expansion_arg)
12911 gcc_checking_assert (false);
12912 return true;
12915 return false;
12918 /* [temp.variadic]/6 says that:
12920 The instantiation of a pack expansion [...]
12921 produces a list E1,E2, ..., En, where N is the number of elements
12922 in the pack expansion parameters.
12924 This subroutine of tsubst_pack_expansion produces one of these Ei.
12926 PATTERN is the pattern of the pack expansion. PARM_PACKS is a
12927 TREE_LIST in which each TREE_PURPOSE is a parameter pack of
12928 PATTERN, and each TREE_VALUE is its corresponding argument pack.
12929 INDEX is the index 'i' of the element Ei to produce. ARGS,
12930 COMPLAIN, and IN_DECL are the same parameters as for the
12931 tsubst_pack_expansion function.
12933 The function returns the resulting Ei upon successful completion,
12934 or error_mark_node.
12936 Note that this function possibly modifies the ARGS parameter, so
12937 it's the responsibility of the caller to restore it. */
12939 static tree
12940 gen_elem_of_pack_expansion_instantiation (tree pattern,
12941 tree parm_packs,
12942 unsigned index,
12943 tree args /* This parm gets
12944 modified. */,
12945 tsubst_flags_t complain,
12946 tree in_decl)
12948 tree t;
12949 bool ith_elem_is_expansion = false;
12951 /* For each parameter pack, change the substitution of the parameter
12952 pack to the ith argument in its argument pack, then expand the
12953 pattern. */
12954 for (tree pack = parm_packs; pack; pack = TREE_CHAIN (pack))
12956 tree parm = TREE_PURPOSE (pack);
12957 tree arg_pack = TREE_VALUE (pack);
12958 tree aps; /* instance of ARGUMENT_PACK_SELECT. */
12960 ith_elem_is_expansion |=
12961 argument_pack_element_is_expansion_p (arg_pack, index);
12963 /* Select the Ith argument from the pack. */
12964 if (TREE_CODE (parm) == PARM_DECL
12965 || VAR_P (parm)
12966 || TREE_CODE (parm) == FIELD_DECL)
12968 if (index == 0)
12970 aps = make_argument_pack_select (arg_pack, index);
12971 if (!mark_used (parm, complain) && !(complain & tf_error))
12972 return error_mark_node;
12973 register_local_specialization (aps, parm);
12975 else
12976 aps = retrieve_local_specialization (parm);
12978 else
12980 int idx, level;
12981 template_parm_level_and_index (parm, &level, &idx);
12983 if (index == 0)
12985 aps = make_argument_pack_select (arg_pack, index);
12986 /* Update the corresponding argument. */
12987 TMPL_ARG (args, level, idx) = aps;
12989 else
12990 /* Re-use the ARGUMENT_PACK_SELECT. */
12991 aps = TMPL_ARG (args, level, idx);
12993 ARGUMENT_PACK_SELECT_INDEX (aps) = index;
12996 /* Substitute into the PATTERN with the (possibly altered)
12997 arguments. */
12998 if (pattern == in_decl)
12999 /* Expanding a fixed parameter pack from
13000 coerce_template_parameter_pack. */
13001 t = tsubst_decl (pattern, args, complain);
13002 else if (pattern == error_mark_node)
13003 t = error_mark_node;
13004 else if (!TYPE_P (pattern))
13005 t = tsubst_expr (pattern, args, complain, in_decl);
13006 else
13008 t = tsubst (pattern, args, complain, in_decl);
13009 if (is_auto (t) && !ith_elem_is_expansion)
13010 /* When expanding the fake auto... pack expansion from add_capture, we
13011 need to mark that the expansion is no longer a pack. */
13012 TEMPLATE_TYPE_PARAMETER_PACK (t) = false;
13015 /* If the Ith argument pack element is a pack expansion, then
13016 the Ith element resulting from the substituting is going to
13017 be a pack expansion as well. */
13018 if (ith_elem_is_expansion)
13019 t = make_pack_expansion (t, complain);
13021 return t;
13024 /* When the unexpanded parameter pack in a fold expression expands to an empty
13025 sequence, the value of the expression is as follows; the program is
13026 ill-formed if the operator is not listed in this table.
13028 && true
13029 || false
13030 , void() */
13032 tree
13033 expand_empty_fold (tree t, tsubst_flags_t complain)
13035 tree_code code = (tree_code)TREE_INT_CST_LOW (TREE_OPERAND (t, 0));
13036 if (!FOLD_EXPR_MODIFY_P (t))
13037 switch (code)
13039 case TRUTH_ANDIF_EXPR:
13040 return boolean_true_node;
13041 case TRUTH_ORIF_EXPR:
13042 return boolean_false_node;
13043 case COMPOUND_EXPR:
13044 return void_node;
13045 default:
13046 break;
13049 if (complain & tf_error)
13050 error_at (location_of (t),
13051 "fold of empty expansion over %O", code);
13052 return error_mark_node;
13055 /* Given a fold-expression T and a current LEFT and RIGHT operand,
13056 form an expression that combines the two terms using the
13057 operator of T. */
13059 static tree
13060 fold_expression (tree t, tree left, tree right, tsubst_flags_t complain)
13062 tree_code code = FOLD_EXPR_OP (t);
13064 tree lookups = templated_operator_saved_lookups (t);
13066 // Handle compound assignment operators.
13067 if (FOLD_EXPR_MODIFY_P (t))
13068 return build_x_modify_expr (input_location, left, code, right,
13069 lookups, complain);
13071 warning_sentinel s(warn_parentheses);
13072 switch (code)
13074 case COMPOUND_EXPR:
13075 return build_x_compound_expr (input_location, left, right,
13076 lookups, complain);
13077 default:
13078 return build_x_binary_op (input_location, code,
13079 left, TREE_CODE (left),
13080 right, TREE_CODE (right),
13081 lookups, /*overload=*/NULL,
13082 complain);
13086 /* Substitute ARGS into the pack of a fold expression T. */
13088 static inline tree
13089 tsubst_fold_expr_pack (tree t, tree args, tsubst_flags_t complain, tree in_decl)
13091 return tsubst_pack_expansion (FOLD_EXPR_PACK (t), args, complain, in_decl);
13094 /* Substitute ARGS into the pack of a fold expression T. */
13096 static inline tree
13097 tsubst_fold_expr_init (tree t, tree args, tsubst_flags_t complain, tree in_decl)
13099 return tsubst_expr (FOLD_EXPR_INIT (t), args, complain, in_decl);
13102 /* Expand a PACK of arguments into a grouped as left fold.
13103 Given a pack containing elements A0, A1, ..., An and an
13104 operator @, this builds the expression:
13106 ((A0 @ A1) @ A2) ... @ An
13108 Note that PACK must not be empty.
13110 The operator is defined by the original fold expression T. */
13112 static tree
13113 expand_left_fold (tree t, tree pack, tsubst_flags_t complain)
13115 tree left = TREE_VEC_ELT (pack, 0);
13116 for (int i = 1; i < TREE_VEC_LENGTH (pack); ++i)
13118 tree right = TREE_VEC_ELT (pack, i);
13119 left = fold_expression (t, left, right, complain);
13121 return left;
13124 /* Substitute into a unary left fold expression. */
13126 static tree
13127 tsubst_unary_left_fold (tree t, tree args, tsubst_flags_t complain,
13128 tree in_decl)
13130 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
13131 if (pack == error_mark_node)
13132 return error_mark_node;
13133 if (PACK_EXPANSION_P (pack))
13135 tree r = copy_node (t);
13136 FOLD_EXPR_PACK (r) = pack;
13137 return r;
13139 if (TREE_VEC_LENGTH (pack) == 0)
13140 return expand_empty_fold (t, complain);
13141 else
13142 return expand_left_fold (t, pack, complain);
13145 /* Substitute into a binary left fold expression.
13147 Do ths by building a single (non-empty) vector of argumnts and
13148 building the expression from those elements. */
13150 static tree
13151 tsubst_binary_left_fold (tree t, tree args, tsubst_flags_t complain,
13152 tree in_decl)
13154 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
13155 if (pack == error_mark_node)
13156 return error_mark_node;
13157 tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
13158 if (init == error_mark_node)
13159 return error_mark_node;
13161 if (PACK_EXPANSION_P (pack))
13163 tree r = copy_node (t);
13164 FOLD_EXPR_PACK (r) = pack;
13165 FOLD_EXPR_INIT (r) = init;
13166 return r;
13169 tree vec = make_tree_vec (TREE_VEC_LENGTH (pack) + 1);
13170 TREE_VEC_ELT (vec, 0) = init;
13171 for (int i = 0; i < TREE_VEC_LENGTH (pack); ++i)
13172 TREE_VEC_ELT (vec, i + 1) = TREE_VEC_ELT (pack, i);
13174 return expand_left_fold (t, vec, complain);
13177 /* Expand a PACK of arguments into a grouped as right fold.
13178 Given a pack containing elementns A0, A1, ..., and an
13179 operator @, this builds the expression:
13181 A0@ ... (An-2 @ (An-1 @ An))
13183 Note that PACK must not be empty.
13185 The operator is defined by the original fold expression T. */
13187 tree
13188 expand_right_fold (tree t, tree pack, tsubst_flags_t complain)
13190 // Build the expression.
13191 int n = TREE_VEC_LENGTH (pack);
13192 tree right = TREE_VEC_ELT (pack, n - 1);
13193 for (--n; n != 0; --n)
13195 tree left = TREE_VEC_ELT (pack, n - 1);
13196 right = fold_expression (t, left, right, complain);
13198 return right;
13201 /* Substitute into a unary right fold expression. */
13203 static tree
13204 tsubst_unary_right_fold (tree t, tree args, tsubst_flags_t complain,
13205 tree in_decl)
13207 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
13208 if (pack == error_mark_node)
13209 return error_mark_node;
13210 if (PACK_EXPANSION_P (pack))
13212 tree r = copy_node (t);
13213 FOLD_EXPR_PACK (r) = pack;
13214 return r;
13216 if (TREE_VEC_LENGTH (pack) == 0)
13217 return expand_empty_fold (t, complain);
13218 else
13219 return expand_right_fold (t, pack, complain);
13222 /* Substitute into a binary right fold expression.
13224 Do ths by building a single (non-empty) vector of arguments and
13225 building the expression from those elements. */
13227 static tree
13228 tsubst_binary_right_fold (tree t, tree args, tsubst_flags_t complain,
13229 tree in_decl)
13231 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
13232 if (pack == error_mark_node)
13233 return error_mark_node;
13234 tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
13235 if (init == error_mark_node)
13236 return error_mark_node;
13238 if (PACK_EXPANSION_P (pack))
13240 tree r = copy_node (t);
13241 FOLD_EXPR_PACK (r) = pack;
13242 FOLD_EXPR_INIT (r) = init;
13243 return r;
13246 int n = TREE_VEC_LENGTH (pack);
13247 tree vec = make_tree_vec (n + 1);
13248 for (int i = 0; i < n; ++i)
13249 TREE_VEC_ELT (vec, i) = TREE_VEC_ELT (pack, i);
13250 TREE_VEC_ELT (vec, n) = init;
13252 return expand_right_fold (t, vec, complain);
13255 /* Walk through the pattern of a pack expansion, adding everything in
13256 local_specializations to a list. */
13258 class el_data
13260 public:
13261 /* Set of variables declared within the pattern. */
13262 hash_set<tree> internal;
13263 /* Set of AST nodes that have been visited by the traversal. */
13264 hash_set<tree> visited;
13265 /* List of local_specializations used within the pattern. */
13266 tree extra;
13267 tsubst_flags_t complain;
13268 /* True iff we don't want to walk into unevaluated contexts. */
13269 bool skip_unevaluated_operands = false;
13270 /* The unevaluated contexts that we avoided walking. */
13271 auto_vec<tree> skipped_trees;
13273 el_data (tsubst_flags_t c)
13274 : extra (NULL_TREE), complain (c) {}
13276 static tree
13277 extract_locals_r (tree *tp, int *walk_subtrees, void *data_)
13279 el_data &data = *reinterpret_cast<el_data*>(data_);
13280 tree *extra = &data.extra;
13281 tsubst_flags_t complain = data.complain;
13283 if (data.skip_unevaluated_operands
13284 && unevaluated_p (TREE_CODE (*tp)))
13286 data.skipped_trees.safe_push (*tp);
13287 *walk_subtrees = 0;
13288 return NULL_TREE;
13291 if (TYPE_P (*tp) && typedef_variant_p (*tp))
13292 /* Remember local typedefs (85214). */
13293 tp = &TYPE_NAME (*tp);
13295 if (TREE_CODE (*tp) == DECL_EXPR)
13297 tree decl = DECL_EXPR_DECL (*tp);
13298 data.internal.add (decl);
13299 if (VAR_P (decl)
13300 && DECL_DECOMPOSITION_P (decl)
13301 && TREE_TYPE (decl) != error_mark_node)
13303 gcc_assert (DECL_NAME (decl) == NULL_TREE);
13304 for (tree decl2 = DECL_CHAIN (decl);
13305 decl2
13306 && VAR_P (decl2)
13307 && DECL_DECOMPOSITION_P (decl2)
13308 && DECL_NAME (decl2)
13309 && TREE_TYPE (decl2) != error_mark_node;
13310 decl2 = DECL_CHAIN (decl2))
13312 gcc_assert (DECL_DECOMP_BASE (decl2) == decl);
13313 data.internal.add (decl2);
13317 else if (TREE_CODE (*tp) == LAMBDA_EXPR)
13319 /* Since we defer implicit capture, look in the parms and body. */
13320 tree fn = lambda_function (*tp);
13321 cp_walk_tree (&TREE_TYPE (fn), &extract_locals_r, &data,
13322 &data.visited);
13323 cp_walk_tree (&DECL_SAVED_TREE (fn), &extract_locals_r, &data,
13324 &data.visited);
13326 else if (tree spec = retrieve_local_specialization (*tp))
13328 if (data.internal.contains (*tp))
13329 /* Don't mess with variables declared within the pattern. */
13330 return NULL_TREE;
13331 if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
13333 /* Maybe pull out the PARM_DECL for a partial instantiation. */
13334 tree args = ARGUMENT_PACK_ARGS (spec);
13335 if (TREE_VEC_LENGTH (args) == 1)
13337 tree elt = TREE_VEC_ELT (args, 0);
13338 if (PACK_EXPANSION_P (elt))
13339 elt = PACK_EXPANSION_PATTERN (elt);
13340 if (DECL_PACK_P (elt))
13341 spec = elt;
13343 if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
13345 /* Handle lambda capture here, since we aren't doing any
13346 substitution now, and so tsubst_copy won't call
13347 process_outer_var_ref. */
13348 tree args = ARGUMENT_PACK_ARGS (spec);
13349 int len = TREE_VEC_LENGTH (args);
13350 for (int i = 0; i < len; ++i)
13352 tree arg = TREE_VEC_ELT (args, i);
13353 tree carg = arg;
13354 if (outer_automatic_var_p (arg))
13355 carg = process_outer_var_ref (arg, complain);
13356 if (carg != arg)
13358 /* Make a new NONTYPE_ARGUMENT_PACK of the capture
13359 proxies. */
13360 if (i == 0)
13362 spec = copy_node (spec);
13363 args = copy_node (args);
13364 ARGUMENT_PACK_ARGS (spec) = args;
13365 register_local_specialization (spec, *tp);
13367 TREE_VEC_ELT (args, i) = carg;
13372 if (outer_automatic_var_p (spec))
13373 spec = process_outer_var_ref (spec, complain);
13374 *extra = tree_cons (*tp, spec, *extra);
13376 return NULL_TREE;
13378 static tree
13379 extract_local_specs (tree pattern, tsubst_flags_t complain)
13381 el_data data (complain);
13382 /* Walk the pattern twice, ignoring unevaluated operands the first time
13383 around, so that if a local specialization appears in both an evaluated
13384 and unevaluated context we prefer to process it in the evaluated context
13385 (since e.g. process_outer_var_ref is a no-op inside an unevaluated
13386 context). */
13387 data.skip_unevaluated_operands = true;
13388 cp_walk_tree (&pattern, extract_locals_r, &data, &data.visited);
13389 /* Now walk the unevaluated contexts we skipped the first time around. */
13390 data.skip_unevaluated_operands = false;
13391 for (tree t : data.skipped_trees)
13393 data.visited.remove (t);
13394 cp_walk_tree (&t, extract_locals_r, &data, &data.visited);
13396 return data.extra;
13399 /* Extract any uses of local_specializations from PATTERN and add them to ARGS
13400 for use in PACK_EXPANSION_EXTRA_ARGS. */
13402 tree
13403 build_extra_args (tree pattern, tree args, tsubst_flags_t complain)
13405 /* Make a copy of the extra arguments so that they won't get changed
13406 out from under us. */
13407 tree extra = preserve_args (copy_template_args (args), /*cow_p=*/false);
13408 if (local_specializations)
13409 if (tree locals = extract_local_specs (pattern, complain))
13410 extra = tree_cons (NULL_TREE, extra, locals);
13411 return extra;
13414 /* Apply any local specializations from PACK_EXPANSION_EXTRA_ARGS and add the
13415 normal template args to ARGS. */
13417 tree
13418 add_extra_args (tree extra, tree args, tsubst_flags_t complain, tree in_decl)
13420 if (extra && TREE_CODE (extra) == TREE_LIST)
13422 for (tree elt = TREE_CHAIN (extra); elt; elt = TREE_CHAIN (elt))
13424 /* The partial instantiation involved local declarations collected in
13425 extract_local_specs; map from the general template to our local
13426 context. */
13427 tree gen = TREE_PURPOSE (elt);
13428 tree inst = TREE_VALUE (elt);
13429 if (DECL_P (inst))
13430 if (tree local = retrieve_local_specialization (inst))
13431 inst = local;
13432 /* else inst is already a full instantiation of the pack. */
13433 register_local_specialization (inst, gen);
13435 gcc_assert (!TREE_PURPOSE (extra));
13436 extra = TREE_VALUE (extra);
13438 if (uses_template_parms (extra))
13440 /* This can happen after dependent substitution into a
13441 requires-expr or a lambda that uses constexpr if. */
13442 extra = tsubst_template_args (extra, args, complain, in_decl);
13443 args = add_outermost_template_args (args, extra);
13445 else
13446 args = add_to_template_args (extra, args);
13447 return args;
13450 /* Substitute ARGS into T, which is an pack expansion
13451 (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
13452 TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
13453 (if only a partial substitution could be performed) or
13454 ERROR_MARK_NODE if there was an error. */
13455 tree
13456 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
13457 tree in_decl)
13459 tree pattern;
13460 tree pack, packs = NULL_TREE;
13461 bool unsubstituted_packs = false;
13462 int i, len = -1;
13463 tree result;
13464 bool need_local_specializations = false;
13465 int levels;
13467 gcc_assert (PACK_EXPANSION_P (t));
13468 pattern = PACK_EXPANSION_PATTERN (t);
13470 /* Add in any args remembered from an earlier partial instantiation. */
13471 args = add_extra_args (PACK_EXPANSION_EXTRA_ARGS (t), args, complain, in_decl);
13473 levels = TMPL_ARGS_DEPTH (args);
13475 /* Determine the argument packs that will instantiate the parameter
13476 packs used in the expansion expression. While we're at it,
13477 compute the number of arguments to be expanded and make sure it
13478 is consistent. */
13479 for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
13480 pack = TREE_CHAIN (pack))
13482 tree parm_pack = TREE_VALUE (pack);
13483 tree arg_pack = NULL_TREE;
13484 tree orig_arg = NULL_TREE;
13485 int level = 0;
13487 if (TREE_CODE (parm_pack) == BASES)
13489 gcc_assert (parm_pack == pattern);
13490 tree type = tsubst (BASES_TYPE (parm_pack), args, complain, in_decl);
13491 if (BASES_DIRECT (parm_pack))
13492 return calculate_direct_bases (type, complain);
13493 else
13494 return calculate_bases (type, complain);
13496 else if (builtin_pack_call_p (parm_pack))
13498 if (parm_pack != pattern)
13500 if (complain & tf_error)
13501 sorry ("%qE is not the entire pattern of the pack expansion",
13502 parm_pack);
13503 return error_mark_node;
13505 return expand_builtin_pack_call (parm_pack, args,
13506 complain, in_decl);
13508 else if (TREE_CODE (parm_pack) == PARM_DECL)
13510 /* We know we have correct local_specializations if this
13511 expansion is at function scope, or if we're dealing with a
13512 local parameter in a requires expression; for the latter,
13513 tsubst_requires_expr set it up appropriately. */
13514 if (PACK_EXPANSION_LOCAL_P (t) || CONSTRAINT_VAR_P (parm_pack))
13515 arg_pack = retrieve_local_specialization (parm_pack);
13516 else
13517 /* We can't rely on local_specializations for a parameter
13518 name used later in a function declaration (such as in a
13519 late-specified return type). Even if it exists, it might
13520 have the wrong value for a recursive call. */
13521 need_local_specializations = true;
13523 if (!arg_pack)
13525 /* This parameter pack was used in an unevaluated context. Just
13526 make a dummy decl, since it's only used for its type. */
13527 ++cp_unevaluated_operand;
13528 arg_pack = tsubst_decl (parm_pack, args, complain);
13529 --cp_unevaluated_operand;
13530 if (arg_pack && DECL_PACK_P (arg_pack))
13531 /* Partial instantiation of the parm_pack, we can't build
13532 up an argument pack yet. */
13533 arg_pack = NULL_TREE;
13534 else
13535 arg_pack = make_fnparm_pack (arg_pack);
13537 else if (DECL_PACK_P (arg_pack))
13538 /* This argument pack isn't fully instantiated yet. */
13539 arg_pack = NULL_TREE;
13541 else if (is_capture_proxy (parm_pack))
13543 arg_pack = retrieve_local_specialization (parm_pack);
13544 if (DECL_PACK_P (arg_pack))
13545 arg_pack = NULL_TREE;
13547 else
13549 int idx;
13550 template_parm_level_and_index (parm_pack, &level, &idx);
13551 if (level <= levels)
13552 arg_pack = TMPL_ARG (args, level, idx);
13554 if (arg_pack && TREE_CODE (arg_pack) == TEMPLATE_TYPE_PARM
13555 && TEMPLATE_TYPE_PARAMETER_PACK (arg_pack))
13556 arg_pack = NULL_TREE;
13559 orig_arg = arg_pack;
13560 if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
13561 arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
13563 if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
13564 /* This can only happen if we forget to expand an argument
13565 pack somewhere else. Just return an error, silently. */
13567 result = make_tree_vec (1);
13568 TREE_VEC_ELT (result, 0) = error_mark_node;
13569 return result;
13572 if (arg_pack)
13574 int my_len =
13575 TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
13577 /* Don't bother trying to do a partial substitution with
13578 incomplete packs; we'll try again after deduction. */
13579 if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
13580 return t;
13582 if (len < 0)
13583 len = my_len;
13584 else if (len != my_len)
13586 if (!(complain & tf_error))
13587 /* Fail quietly. */;
13588 else if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
13589 error ("mismatched argument pack lengths while expanding %qT",
13590 pattern);
13591 else
13592 error ("mismatched argument pack lengths while expanding %qE",
13593 pattern);
13594 return error_mark_node;
13597 /* Keep track of the parameter packs and their corresponding
13598 argument packs. */
13599 packs = tree_cons (parm_pack, arg_pack, packs);
13600 TREE_TYPE (packs) = orig_arg;
13602 else
13604 /* We can't substitute for this parameter pack. We use a flag as
13605 well as the missing_level counter because function parameter
13606 packs don't have a level. */
13607 gcc_assert (processing_template_decl || is_auto (parm_pack));
13608 unsubstituted_packs = true;
13612 /* If the expansion is just T..., return the matching argument pack, unless
13613 we need to call convert_from_reference on all the elements. This is an
13614 important optimization; see c++/68422. */
13615 if (!unsubstituted_packs
13616 && TREE_PURPOSE (packs) == pattern)
13618 tree args = ARGUMENT_PACK_ARGS (TREE_VALUE (packs));
13620 /* If the argument pack is a single pack expansion, pull it out. */
13621 if (TREE_VEC_LENGTH (args) == 1
13622 && pack_expansion_args_count (args))
13624 tree arg = TREE_VEC_ELT (args, 0);
13625 if (PACK_EXPANSION_SIZEOF_P (t)
13626 && !TEMPLATE_PARM_P (PACK_EXPANSION_PATTERN (arg)))
13627 /* Except if this isn't a simple sizeof...(T) which gets sZ
13628 mangling, keep the TREE_VEC to get sP mangling. */;
13629 else
13630 return TREE_VEC_ELT (args, 0);
13633 /* Types need no adjustment, nor does sizeof..., and if we still have
13634 some pack expansion args we won't do anything yet. */
13635 if (TREE_CODE (t) == TYPE_PACK_EXPANSION
13636 || PACK_EXPANSION_SIZEOF_P (t)
13637 || pack_expansion_args_count (args))
13638 return args;
13639 /* Also optimize expression pack expansions if we can tell that the
13640 elements won't have reference type. */
13641 tree type = TREE_TYPE (pattern);
13642 if (type && !TYPE_REF_P (type)
13643 && !PACK_EXPANSION_P (type)
13644 && !WILDCARD_TYPE_P (type))
13645 return args;
13646 /* Otherwise use the normal path so we get convert_from_reference. */
13649 /* We cannot expand this expansion expression, because we don't have
13650 all of the argument packs we need. */
13651 if (use_pack_expansion_extra_args_p (t, packs, len, unsubstituted_packs))
13653 /* We got some full packs, but we can't substitute them in until we
13654 have values for all the packs. So remember these until then. */
13656 t = make_pack_expansion (pattern, complain);
13657 PACK_EXPANSION_EXTRA_ARGS (t)
13658 = build_extra_args (pattern, args, complain);
13659 return t;
13662 /* If NEED_LOCAL_SPECIALIZATIONS then we're in a late-specified return
13663 type, so create our own local specializations map; the current map is
13664 either NULL or (in the case of recursive unification) might have
13665 bindings that we don't want to use or alter. */
13666 local_specialization_stack lss (need_local_specializations
13667 ? lss_blank : lss_nop);
13669 if (unsubstituted_packs)
13671 /* There were no real arguments, we're just replacing a parameter
13672 pack with another version of itself. Substitute into the
13673 pattern and return a PACK_EXPANSION_*. The caller will need to
13674 deal with that. */
13675 if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
13676 result = tsubst_expr (pattern, args, complain, in_decl);
13677 else
13678 result = tsubst (pattern, args, complain, in_decl);
13679 result = make_pack_expansion (result, complain);
13680 PACK_EXPANSION_LOCAL_P (result) = PACK_EXPANSION_LOCAL_P (t);
13681 PACK_EXPANSION_SIZEOF_P (result) = PACK_EXPANSION_SIZEOF_P (t);
13682 if (PACK_EXPANSION_AUTO_P (t))
13684 /* This is a fake auto... pack expansion created in add_capture with
13685 _PACKS that don't appear in the pattern. Copy one over. */
13686 packs = PACK_EXPANSION_PARAMETER_PACKS (t);
13687 pack = retrieve_local_specialization (TREE_VALUE (packs));
13688 gcc_checking_assert (DECL_PACK_P (pack));
13689 PACK_EXPANSION_PARAMETER_PACKS (result)
13690 = build_tree_list (NULL_TREE, pack);
13691 PACK_EXPANSION_AUTO_P (result) = true;
13693 return result;
13696 gcc_assert (len >= 0);
13698 /* For each argument in each argument pack, substitute into the
13699 pattern. */
13700 result = make_tree_vec (len);
13701 tree elem_args = copy_template_args (args);
13702 for (i = 0; i < len; ++i)
13704 t = gen_elem_of_pack_expansion_instantiation (pattern, packs,
13706 elem_args, complain,
13707 in_decl);
13708 TREE_VEC_ELT (result, i) = t;
13709 if (t == error_mark_node)
13711 result = error_mark_node;
13712 break;
13716 /* Update ARGS to restore the substitution from parameter packs to
13717 their argument packs. */
13718 for (pack = packs; pack; pack = TREE_CHAIN (pack))
13720 tree parm = TREE_PURPOSE (pack);
13722 if (TREE_CODE (parm) == PARM_DECL
13723 || VAR_P (parm)
13724 || TREE_CODE (parm) == FIELD_DECL)
13725 register_local_specialization (TREE_TYPE (pack), parm);
13726 else
13728 int idx, level;
13730 if (TREE_VALUE (pack) == NULL_TREE)
13731 continue;
13733 template_parm_level_and_index (parm, &level, &idx);
13735 /* Update the corresponding argument. */
13736 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
13737 TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
13738 TREE_TYPE (pack);
13739 else
13740 TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
13744 /* If the dependent pack arguments were such that we end up with only a
13745 single pack expansion again, there's no need to keep it in a TREE_VEC. */
13746 if (len == 1 && TREE_CODE (result) == TREE_VEC
13747 && PACK_EXPANSION_P (TREE_VEC_ELT (result, 0)))
13748 return TREE_VEC_ELT (result, 0);
13750 return result;
13753 /* Make an argument pack out of the TREE_VEC VEC. */
13755 static tree
13756 make_argument_pack (tree vec)
13758 tree pack;
13760 if (TYPE_P (TREE_VEC_ELT (vec, 0)))
13761 pack = cxx_make_type (TYPE_ARGUMENT_PACK);
13762 else
13764 pack = make_node (NONTYPE_ARGUMENT_PACK);
13765 TREE_CONSTANT (pack) = 1;
13767 ARGUMENT_PACK_ARGS (pack) = vec;
13768 return pack;
13771 /* Return an exact copy of template args T that can be modified
13772 independently. */
13774 static tree
13775 copy_template_args (tree t)
13777 if (t == error_mark_node)
13778 return t;
13780 int len = TREE_VEC_LENGTH (t);
13781 tree new_vec = make_tree_vec (len);
13783 for (int i = 0; i < len; ++i)
13785 tree elt = TREE_VEC_ELT (t, i);
13786 if (elt && TREE_CODE (elt) == TREE_VEC)
13787 elt = copy_template_args (elt);
13788 TREE_VEC_ELT (new_vec, i) = elt;
13791 NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_vec)
13792 = NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
13794 return new_vec;
13797 /* Substitute ARGS into the *_ARGUMENT_PACK orig_arg. */
13799 tree
13800 tsubst_argument_pack (tree orig_arg, tree args, tsubst_flags_t complain,
13801 tree in_decl)
13803 /* This flag is used only during deduction, and we don't expect to
13804 substitute such ARGUMENT_PACKs. */
13805 gcc_assert (!ARGUMENT_PACK_INCOMPLETE_P (orig_arg));
13807 /* Substitute into each of the arguments. */
13808 tree pack_args = tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
13809 args, complain, in_decl);
13810 if (pack_args == error_mark_node)
13811 return error_mark_node;
13813 if (pack_args == ARGUMENT_PACK_ARGS (orig_arg))
13814 return orig_arg;
13816 /* If we're substituting into a generic ARGUMENT_PACK for a variadic
13817 template parameter, we might be able to avoid allocating a new
13818 ARGUMENT_PACK and reuse the corresponding ARGUMENT_PACK from ARGS
13819 if the substituted result is identical to it. */
13820 if (tree parm = template_arg_to_parm (orig_arg))
13822 int level, index;
13823 template_parm_level_and_index (parm, &level, &index);
13824 if (TMPL_ARGS_DEPTH (args) >= level)
13825 if (tree arg = TMPL_ARG (args, level, index))
13826 if (TREE_CODE (arg) == TREE_CODE (orig_arg)
13827 && ARGUMENT_PACK_ARGS (arg) == pack_args)
13829 gcc_assert (!ARGUMENT_PACK_INCOMPLETE_P (arg));
13830 return arg;
13834 tree new_arg;
13835 if (TYPE_P (orig_arg))
13837 new_arg = cxx_make_type (TREE_CODE (orig_arg));
13838 SET_TYPE_STRUCTURAL_EQUALITY (new_arg);
13840 else
13842 new_arg = make_node (TREE_CODE (orig_arg));
13843 TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
13845 ARGUMENT_PACK_ARGS (new_arg) = pack_args;
13846 return new_arg;
13849 /* Substitute ARGS into the vector or list of template arguments T. */
13851 tree
13852 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
13854 if (t == error_mark_node)
13855 return error_mark_node;
13857 /* In "sizeof(X<I>)" we need to evaluate "I". */
13858 cp_evaluated ev;
13860 const int len = TREE_VEC_LENGTH (t);
13861 tree *elts = XALLOCAVEC (tree, len);
13862 int expanded_len_adjust = 0;
13864 /* True iff the substituted result is identical to T. */
13865 bool const_subst_p = true;
13867 for (int i = 0; i < len; i++)
13869 tree orig_arg = TREE_VEC_ELT (t, i);
13870 tree new_arg;
13872 if (!orig_arg)
13873 new_arg = NULL_TREE;
13874 else if (TREE_CODE (orig_arg) == TREE_VEC)
13875 new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
13876 else if (PACK_EXPANSION_P (orig_arg))
13878 /* Substitute into an expansion expression. */
13879 new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
13881 if (TREE_CODE (new_arg) == TREE_VEC)
13882 /* Add to the expanded length adjustment the number of
13883 expanded arguments. We subtract one from this
13884 measurement, because the argument pack expression
13885 itself is already counted as 1 in
13886 LEN. EXPANDED_LEN_ADJUST can actually be negative, if
13887 the argument pack is empty. */
13888 expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
13890 else if (ARGUMENT_PACK_P (orig_arg))
13891 new_arg = tsubst_argument_pack (orig_arg, args, complain, in_decl);
13892 else
13893 new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
13895 if (new_arg == error_mark_node)
13896 return error_mark_node;
13898 elts[i] = new_arg;
13899 if (new_arg != orig_arg)
13900 const_subst_p = false;
13903 if (const_subst_p)
13904 return t;
13906 tree maybe_reuse = NULL_TREE;
13908 /* If ARGS and T are both multi-level, the substituted result may be
13909 identical to ARGS. */
13910 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (t)
13911 && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args)
13912 && TMPL_ARGS_DEPTH (t) == TMPL_ARGS_DEPTH (args))
13913 maybe_reuse = args;
13914 /* If T appears to be a vector of generic template arguments, the
13915 substituted result may be identical to the corresponding level
13916 from ARGS. */
13917 else if (tree parm = template_arg_to_parm (TREE_VEC_ELT (t, 0)))
13919 int level, index;
13920 template_parm_level_and_index (parm, &level, &index);
13921 if (index == 0 && TMPL_ARGS_DEPTH (args) >= level)
13922 maybe_reuse = TMPL_ARGS_LEVEL (args, level);
13925 /* If the substituted result is identical to MAYBE_REUSE, return
13926 it and avoid allocating a new TREE_VEC, as an optimization. */
13927 if (maybe_reuse != NULL_TREE
13928 && TREE_VEC_LENGTH (maybe_reuse) == len
13929 && std::equal (elts, elts+len, TREE_VEC_BEGIN (maybe_reuse)))
13930 return maybe_reuse;
13932 /* If T consists of only a pack expansion for which substitution yielded
13933 a TREE_VEC of the expanded elements, then reuse that TREE_VEC instead
13934 of effectively making a copy. */
13935 if (len == 1
13936 && PACK_EXPANSION_P (TREE_VEC_ELT (t, 0))
13937 && TREE_CODE (elts[0]) == TREE_VEC)
13938 return elts[0];
13940 /* Make space for the expanded arguments coming from template
13941 argument packs. */
13942 tree r = make_tree_vec (len + expanded_len_adjust);
13943 /* T can contain TREE_VECs. That happens if T contains the
13944 arguments for a member template.
13945 In that case each TREE_VEC in T represents a level of template
13946 arguments, and T won't carry any non defaulted argument count.
13947 It will rather be the nested TREE_VECs that will carry one.
13948 In other words, T carries a non defaulted argument count only
13949 if it doesn't contain any nested TREE_VEC. */
13950 if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (t))
13952 int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
13953 count += expanded_len_adjust;
13954 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (r, count);
13957 int out = 0;
13958 for (int i = 0; i < len; i++)
13960 tree orig_arg = TREE_VEC_ELT (t, i);
13961 if (orig_arg
13962 && PACK_EXPANSION_P (orig_arg)
13963 && TREE_CODE (elts[i]) == TREE_VEC)
13965 /* Now expand the template argument pack "in place". */
13966 for (int idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
13967 TREE_VEC_ELT (r, out) = TREE_VEC_ELT (elts[i], idx);
13969 else
13971 TREE_VEC_ELT (r, out) = elts[i];
13972 out++;
13975 gcc_assert (out == TREE_VEC_LENGTH (r));
13977 return r;
13980 /* Substitute ARGS into one level PARMS of template parameters. */
13982 static tree
13983 tsubst_template_parms_level (tree parms, tree args, tsubst_flags_t complain)
13985 if (parms == error_mark_node)
13986 return error_mark_node;
13988 tree new_vec = make_tree_vec (TREE_VEC_LENGTH (parms));
13990 for (int i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
13992 tree tuple = TREE_VEC_ELT (parms, i);
13994 if (tuple == error_mark_node)
13995 continue;
13997 TREE_VEC_ELT (new_vec, i) =
13998 tsubst_template_parm (tuple, args, complain);
14001 return new_vec;
14004 /* Return the result of substituting ARGS into the template parameters
14005 given by PARMS. If there are m levels of ARGS and m + n levels of
14006 PARMS, then the result will contain n levels of PARMS. For
14007 example, if PARMS is `template <class T> template <class U>
14008 template <T*, U, class V>' and ARGS is {{int}, {double}} then the
14009 result will be `template <int*, double, class V>'. */
14011 static tree
14012 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
14014 tree r = NULL_TREE;
14015 tree* new_parms;
14017 /* When substituting into a template, we must set
14018 PROCESSING_TEMPLATE_DECL as the template parameters may be
14019 dependent if they are based on one-another, and the dependency
14020 predicates are short-circuit outside of templates. */
14021 ++processing_template_decl;
14023 for (new_parms = &r;
14024 parms && TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
14025 new_parms = &(TREE_CHAIN (*new_parms)),
14026 parms = TREE_CHAIN (parms))
14028 tree new_vec = tsubst_template_parms_level (TREE_VALUE (parms),
14029 args, complain);
14030 *new_parms =
14031 tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
14032 - TMPL_ARGS_DEPTH (args)),
14033 new_vec, NULL_TREE);
14034 TEMPLATE_PARMS_CONSTRAINTS (*new_parms)
14035 = TEMPLATE_PARMS_CONSTRAINTS (parms);
14038 --processing_template_decl;
14040 return r;
14043 /* Return the result of substituting ARGS into one template parameter
14044 given by T. T Must be a TREE_LIST which TREE_VALUE is the template
14045 parameter and which TREE_PURPOSE is the default argument of the
14046 template parameter. */
14048 static tree
14049 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
14051 tree default_value, parm_decl;
14053 if (args == NULL_TREE
14054 || t == NULL_TREE
14055 || t == error_mark_node)
14056 return t;
14058 gcc_assert (TREE_CODE (t) == TREE_LIST);
14060 default_value = TREE_PURPOSE (t);
14061 parm_decl = TREE_VALUE (t);
14063 parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
14064 if (TREE_CODE (parm_decl) == PARM_DECL
14065 && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
14066 parm_decl = error_mark_node;
14067 default_value = tsubst_template_arg (default_value, args,
14068 complain, NULL_TREE);
14070 tree r = build_tree_list (default_value, parm_decl);
14071 TEMPLATE_PARM_CONSTRAINTS (r) = TEMPLATE_PARM_CONSTRAINTS (t);
14072 return r;
14075 /* Substitute in-place the TEMPLATE_PARM_CONSTRAINTS of each template
14076 parameter in PARMS for sake of declaration matching. */
14078 static void
14079 tsubst_each_template_parm_constraints (tree parms, tree args,
14080 tsubst_flags_t complain)
14082 ++processing_template_decl;
14083 for (; parms; parms = TREE_CHAIN (parms))
14085 tree level = TREE_VALUE (parms);
14086 for (tree parm : tree_vec_range (level))
14087 TEMPLATE_PARM_CONSTRAINTS (parm)
14088 = tsubst_constraint (TEMPLATE_PARM_CONSTRAINTS (parm), args,
14089 complain, NULL_TREE);
14091 --processing_template_decl;
14094 /* Substitute the ARGS into the indicated aggregate (or enumeration)
14095 type T. If T is not an aggregate or enumeration type, it is
14096 handled as if by tsubst. IN_DECL is as for tsubst. If
14097 ENTERING_SCOPE is nonzero, T is the context for a template which
14098 we are presently tsubst'ing. Return the substituted value. */
14100 static tree
14101 tsubst_aggr_type (tree t,
14102 tree args,
14103 tsubst_flags_t complain,
14104 tree in_decl,
14105 int entering_scope)
14107 if (t == NULL_TREE)
14108 return NULL_TREE;
14110 /* Handle typedefs via tsubst so that they get consistently reused. */
14111 if (typedef_variant_p (t))
14113 t = tsubst (t, args, complain, in_decl);
14114 if (t == error_mark_node)
14115 return error_mark_node;
14117 /* The effect of entering_scope is that for a dependent specialization
14118 A<T>, lookup_template_class prefers to return A's primary template
14119 type instead of the implicit instantiation. So when entering_scope,
14120 we mirror this behavior by inspecting TYPE_CANONICAL appropriately,
14121 taking advantage of the fact that lookup_template_class links the two
14122 types by setting TYPE_CANONICAL of the latter to the former. */
14123 if (entering_scope
14124 && CLASS_TYPE_P (t)
14125 && dependent_type_p (t)
14126 && TYPE_TEMPLATE_INFO (t)
14127 && TYPE_CANONICAL (t) == TREE_TYPE (TYPE_TI_TEMPLATE (t)))
14128 t = TYPE_CANONICAL (t);
14130 return t;
14133 switch (TREE_CODE (t))
14135 case RECORD_TYPE:
14136 case ENUMERAL_TYPE:
14137 case UNION_TYPE:
14138 return tsubst_aggr_type_1 (t, args, complain, in_decl, entering_scope);
14140 default:
14141 return tsubst (t, args, complain, in_decl);
14145 /* The part of tsubst_aggr_type that's shared with the RECORD_, UNION_
14146 and ENUMERAL_TYPE cases of tsubst. */
14148 static tree
14149 tsubst_aggr_type_1 (tree t,
14150 tree args,
14151 tsubst_flags_t complain,
14152 tree in_decl,
14153 int entering_scope)
14155 if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
14157 complain &= ~tf_qualifying_scope;
14159 /* Figure out what arguments are appropriate for the
14160 type we are trying to find. For example, given:
14162 template <class T> struct S;
14163 template <class T, class U> void f(T, U) { S<U> su; }
14165 and supposing that we are instantiating f<int, double>,
14166 then our ARGS will be {int, double}, but, when looking up
14167 S we only want {double}. */
14168 tree argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
14169 complain, in_decl);
14170 if (argvec == error_mark_node)
14171 return error_mark_node;
14173 tree r = lookup_template_class (t, argvec, in_decl, NULL_TREE,
14174 entering_scope, complain);
14175 return cp_build_qualified_type (r, cp_type_quals (t), complain);
14177 else
14178 /* This is not a template type, so there's nothing to do. */
14179 return t;
14182 /* Map from a FUNCTION_DECL to a vec of default argument instantiations,
14183 indexed in reverse order of the parameters. */
14185 static GTY((cache)) hash_table<tree_vec_map_cache_hasher> *defarg_inst;
14187 /* Return a reference to the vec* of defarg insts for FN. */
14189 static vec<tree,va_gc> *&
14190 defarg_insts_for (tree fn)
14192 if (!defarg_inst)
14193 defarg_inst = hash_table<tree_vec_map_cache_hasher>::create_ggc (13);
14194 tree_vec_map in = { { fn }, nullptr };
14195 tree_vec_map **slot
14196 = defarg_inst->find_slot_with_hash (&in, DECL_UID (fn), INSERT);
14197 if (!*slot)
14199 *slot = ggc_alloc<tree_vec_map> ();
14200 **slot = in;
14202 return (*slot)->to;
14205 /* Substitute into the default argument ARG (a default argument for
14206 FN), which has the indicated TYPE. */
14208 tree
14209 tsubst_default_argument (tree fn, int parmnum, tree type, tree arg,
14210 tsubst_flags_t complain)
14212 int errs = errorcount + sorrycount;
14214 /* This can happen in invalid code. */
14215 if (TREE_CODE (arg) == DEFERRED_PARSE)
14216 return arg;
14218 /* Shortcut {}. */
14219 if (BRACE_ENCLOSED_INITIALIZER_P (arg)
14220 && CONSTRUCTOR_NELTS (arg) == 0)
14221 return arg;
14223 tree parm = FUNCTION_FIRST_USER_PARM (fn);
14224 parm = chain_index (parmnum, parm);
14225 tree parmtype = TREE_TYPE (parm);
14226 if (DECL_BY_REFERENCE (parm))
14227 parmtype = TREE_TYPE (parmtype);
14228 if (parmtype == error_mark_node)
14229 return error_mark_node;
14231 gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, parmtype));
14233 /* Remember the location of the pointer to the vec rather than the location
14234 of the particular element, in case the vec grows in tsubst_expr. */
14235 vec<tree,va_gc> *&defs = defarg_insts_for (fn);
14236 /* Index in reverse order to avoid allocating space for initial parameters
14237 that don't have default arguments. */
14238 unsigned ridx = list_length (parm);
14239 if (vec_safe_length (defs) < ridx)
14240 vec_safe_grow_cleared (defs, ridx);
14241 else if (tree inst = (*defs)[ridx - 1])
14242 return inst;
14244 /* This default argument came from a template. Instantiate the
14245 default argument here, not in tsubst. In the case of
14246 something like:
14248 template <class T>
14249 struct S {
14250 static T t();
14251 void f(T = t());
14254 we must be careful to do name lookup in the scope of S<T>,
14255 rather than in the current class. */
14256 push_to_top_level ();
14257 push_access_scope (fn);
14258 push_deferring_access_checks (dk_no_deferred);
14259 /* So in_immediate_context knows this is a default argument. */
14260 begin_scope (sk_function_parms, fn);
14261 start_lambda_scope (parm);
14263 /* The default argument expression may cause implicitly defined
14264 member functions to be synthesized, which will result in garbage
14265 collection. We must treat this situation as if we were within
14266 the body of function so as to avoid collecting live data on the
14267 stack. */
14268 ++function_depth;
14269 arg = tsubst_expr (arg, DECL_TI_ARGS (fn), complain, NULL_TREE);
14270 --function_depth;
14272 finish_lambda_scope ();
14274 /* Make sure the default argument is reasonable. */
14275 arg = check_default_argument (type, arg, complain);
14277 if (errorcount+sorrycount > errs
14278 && (complain & tf_warning_or_error))
14279 inform (input_location,
14280 " when instantiating default argument for call to %qD", fn);
14282 leave_scope ();
14283 pop_deferring_access_checks ();
14284 pop_access_scope (fn);
14285 pop_from_top_level ();
14287 if (arg != error_mark_node && !cp_unevaluated_operand)
14288 (*defs)[ridx - 1] = arg;
14290 return arg;
14293 /* Substitute into all the default arguments for FN. */
14295 static void
14296 tsubst_default_arguments (tree fn, tsubst_flags_t complain)
14298 tree arg;
14299 tree tmpl_args;
14301 tmpl_args = DECL_TI_ARGS (fn);
14303 /* If this function is not yet instantiated, we certainly don't need
14304 its default arguments. */
14305 if (uses_template_parms (tmpl_args))
14306 return;
14307 /* Don't do this again for clones. */
14308 if (DECL_CLONED_FUNCTION_P (fn))
14309 return;
14311 int i = 0;
14312 for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
14313 arg;
14314 arg = TREE_CHAIN (arg), ++i)
14315 if (TREE_PURPOSE (arg))
14316 TREE_PURPOSE (arg) = tsubst_default_argument (fn, i,
14317 TREE_VALUE (arg),
14318 TREE_PURPOSE (arg),
14319 complain);
14322 /* Hash table mapping a FUNCTION_DECL to its dependent explicit-specifier. */
14323 static GTY((cache)) decl_tree_cache_map *explicit_specifier_map;
14325 /* Store a pair to EXPLICIT_SPECIFIER_MAP. */
14327 void
14328 store_explicit_specifier (tree v, tree t)
14330 if (!explicit_specifier_map)
14331 explicit_specifier_map = decl_tree_cache_map::create_ggc (37);
14332 DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (v) = true;
14333 explicit_specifier_map->put (v, t);
14336 /* Lookup an element in EXPLICIT_SPECIFIER_MAP. */
14338 tree
14339 lookup_explicit_specifier (tree v)
14341 return *explicit_specifier_map->get (v);
14344 /* Given T, a FUNCTION_TYPE or METHOD_TYPE, construct and return a corresponding
14345 FUNCTION_TYPE or METHOD_TYPE whose return type is RETURN_TYPE, argument types
14346 are ARG_TYPES, and exception specification is RAISES, and otherwise is
14347 identical to T. */
14349 static tree
14350 rebuild_function_or_method_type (tree t, tree return_type, tree arg_types,
14351 tree raises, tsubst_flags_t complain)
14353 gcc_assert (FUNC_OR_METHOD_TYPE_P (t));
14355 tree new_type;
14356 if (TREE_CODE (t) == FUNCTION_TYPE)
14358 new_type = build_function_type (return_type, arg_types);
14359 new_type = apply_memfn_quals (new_type, type_memfn_quals (t));
14361 else
14363 tree r = TREE_TYPE (TREE_VALUE (arg_types));
14364 /* Don't pick up extra function qualifiers from the basetype. */
14365 r = cp_build_qualified_type (r, type_memfn_quals (t), complain);
14366 if (! MAYBE_CLASS_TYPE_P (r))
14368 /* [temp.deduct]
14370 Type deduction may fail for any of the following
14371 reasons:
14373 -- Attempting to create "pointer to member of T" when T
14374 is not a class type. */
14375 if (complain & tf_error)
14376 error ("creating pointer to member function of non-class type %qT",
14378 return error_mark_node;
14381 new_type = build_method_type_directly (r, return_type,
14382 TREE_CHAIN (arg_types));
14384 new_type = cp_build_type_attribute_variant (new_type, TYPE_ATTRIBUTES (t));
14386 cp_ref_qualifier rqual = type_memfn_rqual (t);
14387 bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
14388 return build_cp_fntype_variant (new_type, rqual, raises, late_return_type_p);
14391 /* Check if the function type of DECL, a FUNCTION_DECL, agrees with the type of
14392 each of its formal parameters. If there is a disagreement then rebuild
14393 DECL's function type according to its formal parameter types, as part of a
14394 resolution for Core issues 1001/1322. */
14396 static void
14397 maybe_rebuild_function_decl_type (tree decl)
14399 bool function_type_needs_rebuilding = false;
14400 if (tree parm_list = FUNCTION_FIRST_USER_PARM (decl))
14402 tree parm_type_list = FUNCTION_FIRST_USER_PARMTYPE (decl);
14403 while (parm_type_list && parm_type_list != void_list_node)
14405 tree parm_type = TREE_VALUE (parm_type_list);
14406 tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
14407 if (!same_type_p (parm_type, formal_parm_type_unqual))
14409 function_type_needs_rebuilding = true;
14410 break;
14413 parm_list = DECL_CHAIN (parm_list);
14414 parm_type_list = TREE_CHAIN (parm_type_list);
14418 if (!function_type_needs_rebuilding)
14419 return;
14421 const tree fntype = TREE_TYPE (decl);
14422 tree parm_list = DECL_ARGUMENTS (decl);
14423 tree old_parm_type_list = TYPE_ARG_TYPES (fntype);
14424 tree new_parm_type_list = NULL_TREE;
14425 tree *q = &new_parm_type_list;
14426 for (int skip = num_artificial_parms_for (decl); skip > 0; skip--)
14428 *q = copy_node (old_parm_type_list);
14429 parm_list = DECL_CHAIN (parm_list);
14430 old_parm_type_list = TREE_CHAIN (old_parm_type_list);
14431 q = &TREE_CHAIN (*q);
14433 while (old_parm_type_list && old_parm_type_list != void_list_node)
14435 *q = copy_node (old_parm_type_list);
14436 tree *new_parm_type = &TREE_VALUE (*q);
14437 tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
14438 if (!same_type_p (*new_parm_type, formal_parm_type_unqual))
14439 *new_parm_type = formal_parm_type_unqual;
14441 parm_list = DECL_CHAIN (parm_list);
14442 old_parm_type_list = TREE_CHAIN (old_parm_type_list);
14443 q = &TREE_CHAIN (*q);
14445 if (old_parm_type_list == void_list_node)
14446 *q = void_list_node;
14448 TREE_TYPE (decl)
14449 = rebuild_function_or_method_type (fntype,
14450 TREE_TYPE (fntype), new_parm_type_list,
14451 TYPE_RAISES_EXCEPTIONS (fntype), tf_none);
14454 /* Subroutine of tsubst_decl for the case when T is a FUNCTION_DECL. */
14456 static tree
14457 tsubst_function_decl (tree t, tree args, tsubst_flags_t complain,
14458 tree lambda_fntype, bool use_spec_table = true)
14460 tree gen_tmpl = NULL_TREE, argvec = NULL_TREE;
14461 hashval_t hash = 0;
14462 tree in_decl = t;
14464 /* Nobody should be tsubst'ing into non-template functions. */
14465 gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE
14466 || DECL_LOCAL_DECL_P (t));
14468 if (DECL_LOCAL_DECL_P (t))
14470 if (tree spec = retrieve_local_specialization (t))
14471 return spec;
14473 else if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
14475 /* If T is not dependent, just return it. */
14476 if (!uses_template_parms (DECL_TI_ARGS (t))
14477 && !LAMBDA_FUNCTION_P (t))
14478 return t;
14480 /* A non-templated friend doesn't get DECL_TEMPLATE_INFO. */
14481 if (non_templated_friend_p (t))
14482 goto friend_case;
14484 /* Calculate the most general template of which R is a
14485 specialization. */
14486 gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
14488 /* We're substituting a lambda function under tsubst_lambda_expr but not
14489 directly from it; find the matching function we're already inside.
14490 But don't do this if T is a generic lambda with a single level of
14491 template parms, as in that case we're doing a normal instantiation. */
14492 if (LAMBDA_FUNCTION_P (t) && !lambda_fntype
14493 && (!generic_lambda_fn_p (t)
14494 || TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)) > 1))
14495 return enclosing_instantiation_of (t);
14497 /* Calculate the complete set of arguments used to
14498 specialize R. */
14499 if (use_spec_table && !lambda_fntype)
14501 argvec = tsubst_template_args (DECL_TI_ARGS
14502 (DECL_TEMPLATE_RESULT
14503 (DECL_TI_TEMPLATE (t))),
14504 args, complain, in_decl);
14505 if (argvec == error_mark_node)
14506 return error_mark_node;
14508 /* Check to see if we already have this specialization. */
14509 hash = spec_hasher::hash (gen_tmpl, argvec);
14510 if (tree spec = retrieve_specialization (gen_tmpl, argvec, hash))
14511 /* The spec for these args might be a partial instantiation of the
14512 template, but here what we want is the FUNCTION_DECL. */
14513 return STRIP_TEMPLATE (spec);
14515 else
14516 argvec = args;
14518 else
14520 /* This special case arises when we have something like this:
14522 template <class T> struct S {
14523 friend void f<int>(int, double);
14526 Here, the DECL_TI_TEMPLATE for the friend declaration
14527 will be an IDENTIFIER_NODE. We are being called from
14528 tsubst_friend_function, and we want only to create a
14529 new decl (R) with appropriate types so that we can call
14530 determine_specialization. */
14531 friend_case:
14532 gen_tmpl = NULL_TREE;
14533 argvec = NULL_TREE;
14536 tree closure = (lambda_fntype ? TYPE_METHOD_BASETYPE (lambda_fntype)
14537 : NULL_TREE);
14538 tree ctx = closure ? closure : DECL_CONTEXT (t);
14539 bool member = ctx && TYPE_P (ctx);
14541 /* If this is a static or xobj lambda, remove the 'this' pointer added in
14542 tsubst_lambda_expr now that we know the closure type. */
14543 if (lambda_fntype && !DECL_IOBJ_MEMBER_FUNCTION_P (t))
14544 lambda_fntype = static_fn_type (lambda_fntype);
14546 if (member && !closure)
14547 ctx = tsubst_aggr_type (ctx, args,
14548 complain, t, /*entering_scope=*/1);
14550 tree type = (lambda_fntype ? lambda_fntype
14551 : tsubst (TREE_TYPE (t), args,
14552 complain | tf_fndecl_type, in_decl));
14553 if (type == error_mark_node)
14554 return error_mark_node;
14556 /* If we hit excessive deduction depth, the type is bogus even if
14557 it isn't error_mark_node, so don't build a decl. */
14558 if (excessive_deduction_depth)
14559 return error_mark_node;
14561 /* We do NOT check for matching decls pushed separately at this
14562 point, as they may not represent instantiations of this
14563 template, and in any case are considered separate under the
14564 discrete model. */
14565 tree r = copy_decl (t);
14566 DECL_USE_TEMPLATE (r) = 0;
14567 TREE_TYPE (r) = type;
14568 /* Clear out the mangled name and RTL for the instantiation. */
14569 SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
14570 SET_DECL_RTL (r, NULL);
14571 /* Leave DECL_INITIAL set on deleted instantiations. */
14572 if (!DECL_DELETED_FN (r))
14573 DECL_INITIAL (r) = NULL_TREE;
14574 DECL_CONTEXT (r) = ctx;
14575 set_instantiating_module (r);
14577 /* Handle explicit(dependent-expr). */
14578 if (DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (t))
14580 tree spec = lookup_explicit_specifier (t);
14581 spec = tsubst_expr (spec, args, complain, in_decl);
14582 spec = build_explicit_specifier (spec, complain);
14583 if (spec == error_mark_node)
14584 return error_mark_node;
14585 if (instantiation_dependent_expression_p (spec))
14586 store_explicit_specifier (r, spec);
14587 else
14589 DECL_NONCONVERTING_P (r) = (spec == boolean_true_node);
14590 DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (r) = false;
14594 /* OpenMP UDRs have the only argument a reference to the declared
14595 type. We want to diagnose if the declared type is a reference,
14596 which is invalid, but as references to references are usually
14597 quietly merged, diagnose it here. */
14598 if (DECL_OMP_DECLARE_REDUCTION_P (t))
14600 tree argtype
14601 = TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (t))));
14602 argtype = tsubst (argtype, args, complain, in_decl);
14603 if (TYPE_REF_P (argtype))
14604 error_at (DECL_SOURCE_LOCATION (t),
14605 "reference type %qT in "
14606 "%<#pragma omp declare reduction%>", argtype);
14607 if (strchr (IDENTIFIER_POINTER (DECL_NAME (t)), '~') == NULL)
14608 DECL_NAME (r) = omp_reduction_id (ERROR_MARK, DECL_NAME (t),
14609 argtype);
14612 if (member && DECL_CONV_FN_P (r))
14613 /* Type-conversion operator. Reconstruct the name, in
14614 case it's the name of one of the template's parameters. */
14615 DECL_NAME (r) = make_conv_op_name (TREE_TYPE (type));
14617 tree parms = DECL_ARGUMENTS (t);
14618 if (closure && DECL_IOBJ_MEMBER_FUNCTION_P (t))
14619 parms = DECL_CHAIN (parms);
14620 parms = tsubst (parms, args, complain, t);
14621 for (tree parm = parms; parm; parm = DECL_CHAIN (parm))
14622 DECL_CONTEXT (parm) = r;
14623 if (closure && DECL_IOBJ_MEMBER_FUNCTION_P (t))
14625 tree tparm = build_this_parm (r, closure, type_memfn_quals (type));
14626 DECL_NAME (tparm) = closure_identifier;
14627 DECL_CHAIN (tparm) = parms;
14628 parms = tparm;
14630 DECL_ARGUMENTS (r) = parms;
14631 DECL_RESULT (r) = NULL_TREE;
14633 maybe_rebuild_function_decl_type (r);
14635 TREE_STATIC (r) = 0;
14636 TREE_PUBLIC (r) = TREE_PUBLIC (t);
14637 DECL_EXTERNAL (r) = 1;
14638 /* If this is an instantiation of a function with internal
14639 linkage, we already know what object file linkage will be
14640 assigned to the instantiation. */
14641 DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
14642 DECL_DEFER_OUTPUT (r) = 0;
14643 DECL_CHAIN (r) = NULL_TREE;
14644 DECL_PENDING_INLINE_INFO (r) = 0;
14645 DECL_PENDING_INLINE_P (r) = 0;
14646 DECL_SAVED_TREE (r) = NULL_TREE;
14647 DECL_STRUCT_FUNCTION (r) = NULL;
14648 TREE_USED (r) = 0;
14649 /* We'll re-clone as appropriate in instantiate_template. */
14650 DECL_CLONED_FUNCTION (r) = NULL_TREE;
14652 /* If we aren't complaining now, return on error before we register
14653 the specialization so that we'll complain eventually. */
14654 if ((complain & tf_error) == 0
14655 && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
14656 && !grok_op_properties (r, /*complain=*/false))
14657 return error_mark_node;
14659 /* If we are looking at an xobj lambda, we might need to check the type of
14660 its xobj parameter. */
14661 if (LAMBDA_FUNCTION_P (r) && DECL_XOBJ_MEMBER_FUNCTION_P (r))
14663 tree closure_obj = DECL_CONTEXT (r);
14664 tree lambda_expr = CLASSTYPE_LAMBDA_EXPR (closure_obj);
14665 tree obj_param = TREE_TYPE (DECL_ARGUMENTS (r));
14667 if (!(LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (lambda_expr) != CPLD_NONE
14668 || LAMBDA_EXPR_CAPTURE_LIST (lambda_expr)))
14669 /* If a lambda has an empty capture clause, an xobj parameter of
14670 unrelated type is not an error. */;
14671 else if (dependent_type_p (obj_param))
14672 /* If we are coming from tsubst_lambda_expr we might not have
14673 substituted into our xobj parameter yet. We can't error out until
14674 we know what the type really is so do nothing...
14675 ...but if we are instantiating the call op for real and we don't
14676 have a real type then something has gone incredibly wrong. */
14677 gcc_assert (lambda_fntype);
14678 else
14680 /* We have a lambda with captures, and know the type of the xobj
14681 parameter, time to check it. */
14682 tree obj_param_type = TYPE_MAIN_VARIANT (non_reference (obj_param));
14683 if (!same_or_base_type_p (closure_obj, obj_param_type))
14685 /* This error does not emit when the lambda's call operator
14686 template is instantiated by taking its address, such as in
14687 the following case:
14689 auto f = [x = 0](this auto&&){};
14690 int (*fp)(int&) = &decltype(f)::operator();
14692 It only emits when explicitly calling the call operator with
14693 an explicit template parameter:
14695 template<typename T>
14696 struct S : T {
14697 using T::operator();
14698 operator int() const {return {};}
14701 auto s = S{[x = 0](this auto&&) {}};
14702 s.operator()<int>();
14704 This is due to resolve_address_of_overloaded_function being
14705 deficient at reporting candidates when overload resolution
14706 fails.
14708 This diagnostic will be active in the first case if/when
14709 resolve_address_of_overloaded_function is fixed to properly
14710 emit candidates upon failure to resolve to an overload. */
14711 if (complain & tf_error)
14712 error ("a lambda with captures may not have an explicit "
14713 "object parameter of an unrelated type");
14714 return error_mark_node;
14719 /* Associate the constraints directly with the instantiation. We
14720 don't substitute through the constraints; that's only done when
14721 they are checked. */
14722 if (tree ci = get_constraints (t))
14723 set_constraints (r, ci);
14725 if (DECL_FRIEND_CONTEXT (t))
14726 SET_DECL_FRIEND_CONTEXT (r,
14727 tsubst (DECL_FRIEND_CONTEXT (t),
14728 args, complain, in_decl));
14730 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14731 args, complain, in_decl))
14732 return error_mark_node;
14734 /* Set up the DECL_TEMPLATE_INFO for R. There's no need to do
14735 this in the special friend case mentioned above where
14736 GEN_TMPL is NULL. */
14737 if (gen_tmpl && !closure)
14739 DECL_TEMPLATE_INFO (r)
14740 = build_template_info (gen_tmpl, argvec);
14741 SET_DECL_IMPLICIT_INSTANTIATION (r);
14743 if (use_spec_table)
14745 tree new_r
14746 = register_specialization (r, gen_tmpl, argvec, false, hash);
14747 if (new_r != r)
14748 /* We instantiated this while substituting into
14749 the type earlier (template/friend54.C). */
14750 return new_r;
14753 /* We're not supposed to instantiate default arguments
14754 until they are called, for a template. But, for a
14755 declaration like:
14757 template <class T> void f ()
14758 { extern void g(int i = T()); }
14760 we should do the substitution when the template is
14761 instantiated. We handle the member function case in
14762 instantiate_class_template since the default arguments
14763 might refer to other members of the class. */
14764 if (!member
14765 && !PRIMARY_TEMPLATE_P (gen_tmpl)
14766 && !uses_template_parms (argvec))
14767 tsubst_default_arguments (r, complain);
14769 else if (DECL_LOCAL_DECL_P (r))
14771 if (!cp_unevaluated_operand)
14772 register_local_specialization (r, t);
14774 else
14775 DECL_TEMPLATE_INFO (r) = NULL_TREE;
14777 /* Copy the list of befriending classes. */
14778 for (tree *friends = &DECL_BEFRIENDING_CLASSES (r);
14779 *friends;
14780 friends = &TREE_CHAIN (*friends))
14782 *friends = copy_node (*friends);
14783 TREE_VALUE (*friends)
14784 = tsubst (TREE_VALUE (*friends), args, complain, in_decl);
14787 if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
14789 maybe_retrofit_in_chrg (r);
14790 if (DECL_CONSTRUCTOR_P (r) && !grok_ctor_properties (ctx, r))
14791 return error_mark_node;
14792 /* If this is an instantiation of a member template, clone it.
14793 If it isn't, that'll be handled by
14794 clone_constructors_and_destructors. */
14795 if (gen_tmpl && PRIMARY_TEMPLATE_P (gen_tmpl))
14796 clone_cdtor (r, /*update_methods=*/false);
14798 else if ((complain & tf_error) != 0
14799 && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
14800 && !grok_op_properties (r, /*complain=*/true))
14801 return error_mark_node;
14803 /* Possibly limit visibility based on template args. */
14804 DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
14805 if (DECL_VISIBILITY_SPECIFIED (t))
14807 DECL_VISIBILITY_SPECIFIED (r) = 0;
14808 DECL_ATTRIBUTES (r)
14809 = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
14811 determine_visibility (r);
14812 if (DECL_SECTION_NAME (t))
14813 set_decl_section_name (r, t);
14814 if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
14815 && COMPLETE_TYPE_P (DECL_CONTEXT (r))
14816 && !processing_template_decl)
14817 defaulted_late_check (r);
14819 if (flag_openmp)
14820 if (tree attr = lookup_attribute ("omp declare variant base",
14821 DECL_ATTRIBUTES (r)))
14822 omp_declare_variant_finalize (r, attr);
14824 return r;
14827 /* Subroutine of tsubst_decl for the case when T is a TEMPLATE_DECL. */
14829 static tree
14830 tsubst_template_decl (tree t, tree args, tsubst_flags_t complain,
14831 tree lambda_fntype, tree lambda_tparms)
14833 /* We can get here when processing a member function template,
14834 member class template, or template template parameter. */
14835 tree decl = DECL_TEMPLATE_RESULT (t);
14836 tree in_decl = t;
14837 tree spec;
14838 tree tmpl_args;
14839 tree full_args = NULL_TREE;
14840 tree r;
14841 hashval_t hash = 0;
14843 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
14845 /* Template template parameter is treated here. */
14846 tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14847 if (new_type == error_mark_node)
14848 r = error_mark_node;
14849 /* If we get a real template back, return it. This can happen in
14850 the context of most_specialized_partial_spec. */
14851 else if (TREE_CODE (new_type) == TEMPLATE_DECL)
14852 r = new_type;
14853 else
14854 /* The new TEMPLATE_DECL was built in
14855 reduce_template_parm_level. */
14856 r = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (new_type);
14857 return r;
14860 if (!lambda_fntype)
14862 /* We might already have an instance of this template.
14863 The ARGS are for the surrounding class type, so the
14864 full args contain the tsubst'd args for the context,
14865 plus the innermost args from the template decl. */
14866 tmpl_args = DECL_CLASS_TEMPLATE_P (t)
14867 ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
14868 : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
14869 /* Because this is a template, the arguments will still be
14870 dependent, even after substitution. If
14871 PROCESSING_TEMPLATE_DECL is not set, the dependency
14872 predicates will short-circuit. */
14873 ++processing_template_decl;
14874 full_args = tsubst_template_args (tmpl_args, args,
14875 complain, in_decl);
14876 --processing_template_decl;
14877 if (full_args == error_mark_node)
14878 return error_mark_node;
14880 /* If this is a default template template argument,
14881 tsubst might not have changed anything. */
14882 if (full_args == tmpl_args)
14883 return t;
14885 hash = spec_hasher::hash (t, full_args);
14886 spec = retrieve_specialization (t, full_args, hash);
14887 if (spec != NULL_TREE)
14889 if (TYPE_P (spec))
14890 /* Type partial instantiations are stored as the type by
14891 lookup_template_class_1, not here as the template. */
14892 spec = CLASSTYPE_TI_TEMPLATE (spec);
14893 else if (TREE_CODE (spec) != TEMPLATE_DECL)
14894 spec = DECL_TI_TEMPLATE (spec);
14895 return spec;
14899 /* Make a new template decl. It will be similar to the
14900 original, but will record the current template arguments.
14901 We also create a new function declaration, which is just
14902 like the old one, but points to this new template, rather
14903 than the old one. */
14904 r = copy_decl (t);
14905 gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
14906 DECL_CHAIN (r) = NULL_TREE;
14908 // Build new template info linking to the original template decl.
14909 if (!lambda_fntype)
14911 DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
14912 SET_DECL_IMPLICIT_INSTANTIATION (r);
14914 else
14915 DECL_TEMPLATE_INFO (r) = NULL_TREE;
14917 /* The template parameters for this new template are all the
14918 template parameters for the old template, except the
14919 outermost level of parameters. */
14920 auto tparm_guard = make_temp_override (current_template_parms);
14921 DECL_TEMPLATE_PARMS (r)
14922 = current_template_parms
14923 = (lambda_tparms
14924 ? lambda_tparms
14925 : tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
14926 complain));
14928 bool class_p = false;
14929 tree inner = decl;
14930 ++processing_template_decl;
14931 if (TREE_CODE (inner) == FUNCTION_DECL)
14932 inner = tsubst_function_decl (inner, args, complain, lambda_fntype,
14933 /*use_spec_table=*/false);
14934 else
14936 if (TREE_CODE (inner) == TYPE_DECL && !TYPE_DECL_ALIAS_P (inner))
14938 class_p = true;
14939 inner = TREE_TYPE (inner);
14941 if (class_p)
14942 inner = tsubst_aggr_type (inner, args, complain,
14943 in_decl, /*entering*/1);
14944 else
14945 inner = tsubst_decl (inner, args, complain, /*use_spec_table=*/false);
14947 --processing_template_decl;
14948 if (inner == error_mark_node)
14949 return error_mark_node;
14951 if (class_p)
14953 /* For a partial specialization, we need to keep pointing to
14954 the primary template. */
14955 if (!DECL_TEMPLATE_SPECIALIZATION (t))
14957 CLASSTYPE_TI_TEMPLATE (inner) = r;
14958 CLASSTYPE_USE_TEMPLATE (inner) = 0;
14961 DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (inner);
14962 inner = TYPE_MAIN_DECL (inner);
14964 else if (lambda_fntype)
14966 tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (r));
14967 DECL_TEMPLATE_INFO (inner) = build_template_info (r, args);
14969 else
14971 DECL_TI_TEMPLATE (inner) = r;
14972 /* Set DECL_TI_ARGS to the full set of template arguments,
14973 which tsubst_function_decl / tsubst_decl didn't do due to
14974 use_spec_table=false. */
14975 DECL_TI_ARGS (inner) = full_args;
14976 DECL_TI_ARGS (r) = DECL_TI_ARGS (inner);
14979 DECL_TEMPLATE_RESULT (r) = inner;
14980 TREE_TYPE (r) = TREE_TYPE (inner);
14981 DECL_CONTEXT (r) = DECL_CONTEXT (inner);
14983 if (modules_p ())
14985 /* Propagate module information from the decl. */
14986 DECL_MODULE_EXPORT_P (r) = DECL_MODULE_EXPORT_P (inner);
14987 if (DECL_LANG_SPECIFIC (inner))
14988 /* If this is a constrained template, the above tsubst of
14989 inner can find the unconstrained template, which may have
14990 come from an import. This is ok, because we don't
14991 register this instantiation (see below). */
14992 gcc_checking_assert (!DECL_MODULE_IMPORT_P (inner)
14993 || (TEMPLATE_PARMS_CONSTRAINTS
14994 (DECL_TEMPLATE_PARMS (t))));
14997 DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
14998 DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
15000 if (PRIMARY_TEMPLATE_P (t))
15001 DECL_PRIMARY_TEMPLATE (r) = r;
15003 DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (r) = false;
15005 if (!lambda_fntype && !class_p)
15007 /* Record this non-type partial instantiation. */
15008 /* FIXME we'd like to always register the TEMPLATE_DECL, or always
15009 the DECL_TEMPLATE_RESULT, but it seems the modules code relies
15010 on this current behavior. */
15011 if (TREE_CODE (inner) == FUNCTION_DECL)
15012 register_specialization (r, t, full_args, false, hash);
15013 else
15014 register_specialization (inner, t, full_args, false, hash);
15017 return r;
15020 /* True if FN is the op() for a lambda in an uninstantiated template. */
15022 bool
15023 lambda_fn_in_template_p (tree fn)
15025 if (!fn || !LAMBDA_FUNCTION_P (fn))
15026 return false;
15027 tree closure = DECL_CONTEXT (fn);
15028 return CLASSTYPE_TEMPLATE_INFO (closure) != NULL_TREE;
15031 /* True if FN is the substitution (via tsubst_lambda_expr) of a function for
15032 which the above is true. */
15034 bool
15035 regenerated_lambda_fn_p (tree fn)
15037 if (!fn || !LAMBDA_FUNCTION_P (fn))
15038 return false;
15039 tree closure = DECL_CONTEXT (fn);
15040 tree lam = CLASSTYPE_LAMBDA_EXPR (closure);
15041 return LAMBDA_EXPR_REGEN_INFO (lam) != NULL_TREE;
15044 /* Return the LAMBDA_EXPR from which T was ultimately regenerated.
15045 If T is not a regenerated LAMBDA_EXPR, return T. */
15047 tree
15048 most_general_lambda (tree t)
15050 while (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
15051 t = TI_TEMPLATE (ti);
15052 return t;
15055 /* Return the set of template arguments used to regenerate the lambda T
15056 from its most general lambda. */
15058 tree
15059 lambda_regenerating_args (tree t)
15061 if (LAMBDA_FUNCTION_P (t))
15062 t = CLASSTYPE_LAMBDA_EXPR (DECL_CONTEXT (t));
15063 gcc_assert (TREE_CODE (t) == LAMBDA_EXPR);
15064 if (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
15065 return TI_ARGS (ti);
15066 else
15067 return NULL_TREE;
15070 /* We're instantiating a variable from template function TCTX. Return the
15071 corresponding current enclosing scope. We can match them up using
15072 DECL_SOURCE_LOCATION because lambdas only ever have one source location, and
15073 the DECL_SOURCE_LOCATION for a function instantiation is updated to match
15074 the template definition in regenerate_decl_from_template. */
15076 static tree
15077 enclosing_instantiation_of (tree tctx)
15079 tree fn = current_function_decl;
15081 /* We shouldn't ever need to do this for other artificial functions. */
15082 gcc_assert (!DECL_ARTIFICIAL (tctx) || LAMBDA_FUNCTION_P (tctx));
15084 for (; fn; fn = decl_function_context (fn))
15085 if (DECL_SOURCE_LOCATION (fn) == DECL_SOURCE_LOCATION (tctx))
15086 return fn;
15087 gcc_unreachable ();
15090 /* Substitute the ARGS into the T, which is a _DECL. Return the
15091 result of the substitution. Issue error and warning messages under
15092 control of COMPLAIN. The flag USE_SPEC_TABLE controls if we look up
15093 and insert into the specializations table or if we can assume it's
15094 the caller's responsibility; this is used by instantiate_template
15095 to avoid doing some redundant work. */
15097 static tree
15098 tsubst_decl (tree t, tree args, tsubst_flags_t complain,
15099 bool use_spec_table /* = true */)
15101 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
15102 location_t saved_loc;
15103 tree r = NULL_TREE;
15104 tree in_decl = t;
15105 hashval_t hash = 0;
15107 if (t == error_mark_node)
15108 return error_mark_node;
15110 /* Set the filename and linenumber to improve error-reporting. */
15111 saved_loc = input_location;
15112 input_location = DECL_SOURCE_LOCATION (t);
15114 switch (TREE_CODE (t))
15116 case TEMPLATE_DECL:
15117 r = tsubst_template_decl (t, args, complain,
15118 /*lambda_fntype=*/NULL_TREE,
15119 /*lambda_tparms=*/NULL_TREE);
15120 break;
15122 case FUNCTION_DECL:
15123 r = tsubst_function_decl (t, args, complain, /*lambda*/NULL_TREE,
15124 use_spec_table);
15125 break;
15127 case PARM_DECL:
15129 tree type = NULL_TREE;
15130 int i, len = 1;
15131 tree expanded_types = NULL_TREE;
15132 tree prev_r = NULL_TREE;
15133 tree first_r = NULL_TREE;
15135 if (DECL_PACK_P (t))
15137 /* If there is a local specialization that isn't a
15138 parameter pack, it means that we're doing a "simple"
15139 substitution from inside tsubst_pack_expansion. Just
15140 return the local specialization (which will be a single
15141 parm). */
15142 tree spec = retrieve_local_specialization (t);
15143 if (spec
15144 && TREE_CODE (spec) == PARM_DECL
15145 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
15146 RETURN (spec);
15148 /* Expand the TYPE_PACK_EXPANSION that provides the types for
15149 the parameters in this function parameter pack. */
15150 expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
15151 complain, in_decl);
15152 if (TREE_CODE (expanded_types) == TREE_VEC)
15154 len = TREE_VEC_LENGTH (expanded_types);
15156 /* Zero-length parameter packs are boring. Just substitute
15157 into the chain. */
15158 if (len == 0 && !cp_unevaluated_operand)
15159 RETURN (tsubst (TREE_CHAIN (t), args, complain,
15160 TREE_CHAIN (t)));
15162 else
15164 /* All we did was update the type. Make a note of that. */
15165 type = expanded_types;
15166 expanded_types = NULL_TREE;
15170 /* Loop through all of the parameters we'll build. When T is
15171 a function parameter pack, LEN is the number of expanded
15172 types in EXPANDED_TYPES; otherwise, LEN is 1. */
15173 r = NULL_TREE;
15174 for (i = 0; i < len; ++i)
15176 prev_r = r;
15177 r = copy_node (t);
15178 if (DECL_TEMPLATE_PARM_P (t))
15179 SET_DECL_TEMPLATE_PARM_P (r);
15181 if (expanded_types)
15182 /* We're on the Ith parameter of the function parameter
15183 pack. */
15185 /* Get the Ith type. */
15186 type = TREE_VEC_ELT (expanded_types, i);
15188 /* Rename the parameter to include the index. */
15189 DECL_NAME (r)
15190 = make_ith_pack_parameter_name (DECL_NAME (r), i);
15192 else if (!type)
15193 /* We're dealing with a normal parameter. */
15194 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15196 type = type_decays_to (type);
15197 TREE_TYPE (r) = type;
15198 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
15200 if (DECL_INITIAL (r))
15202 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
15203 DECL_INITIAL (r) = TREE_TYPE (r);
15204 else
15205 DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
15206 complain, in_decl);
15209 DECL_CONTEXT (r) = NULL_TREE;
15211 if (!DECL_TEMPLATE_PARM_P (r))
15212 DECL_ARG_TYPE (r) = type_passed_as (type);
15214 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
15215 args, complain, in_decl))
15216 return error_mark_node;
15218 /* Keep track of the first new parameter we
15219 generate. That's what will be returned to the
15220 caller. */
15221 if (!first_r)
15222 first_r = r;
15224 /* Build a proper chain of parameters when substituting
15225 into a function parameter pack. */
15226 if (prev_r)
15227 DECL_CHAIN (prev_r) = r;
15230 /* If cp_unevaluated_operand is set, we're just looking for a
15231 single dummy parameter, so don't keep going. */
15232 if (DECL_CHAIN (t) && !cp_unevaluated_operand)
15233 DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
15234 complain, DECL_CHAIN (t));
15236 /* FIRST_R contains the start of the chain we've built. */
15237 r = first_r;
15239 break;
15241 case FIELD_DECL:
15243 tree type = NULL_TREE;
15244 tree vec = NULL_TREE;
15245 tree expanded_types = NULL_TREE;
15246 int len = 1;
15248 if (PACK_EXPANSION_P (TREE_TYPE (t)))
15250 /* This field is a lambda capture pack. Return a TREE_VEC of
15251 the expanded fields to instantiate_class_template_1. */
15252 expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
15253 complain, in_decl);
15254 if (TREE_CODE (expanded_types) == TREE_VEC)
15256 len = TREE_VEC_LENGTH (expanded_types);
15257 vec = make_tree_vec (len);
15259 else
15261 /* All we did was update the type. Make a note of that. */
15262 type = expanded_types;
15263 expanded_types = NULL_TREE;
15267 for (int i = 0; i < len; ++i)
15269 r = copy_decl (t);
15270 if (expanded_types)
15272 type = TREE_VEC_ELT (expanded_types, i);
15273 DECL_NAME (r)
15274 = make_ith_pack_parameter_name (DECL_NAME (r), i);
15276 else if (!type)
15277 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15279 if (type == error_mark_node)
15280 RETURN (error_mark_node);
15281 TREE_TYPE (r) = type;
15282 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
15284 if (DECL_C_BIT_FIELD (r))
15285 /* For bit-fields, DECL_BIT_FIELD_REPRESENTATIVE gives the
15286 number of bits. */
15287 DECL_BIT_FIELD_REPRESENTATIVE (r)
15288 = tsubst_expr (DECL_BIT_FIELD_REPRESENTATIVE (t), args,
15289 complain, in_decl);
15290 if (DECL_INITIAL (t))
15292 /* Set up DECL_TEMPLATE_INFO so that we can get at the
15293 NSDMI in perform_member_init. Still set DECL_INITIAL
15294 so that we know there is one. */
15295 DECL_INITIAL (r) = void_node;
15296 gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
15297 retrofit_lang_decl (r);
15298 DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
15300 /* We don't have to set DECL_CONTEXT here; it is set by
15301 finish_member_declaration. */
15302 DECL_CHAIN (r) = NULL_TREE;
15304 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
15305 args, complain, in_decl))
15306 return error_mark_node;
15308 if (vec)
15309 TREE_VEC_ELT (vec, i) = r;
15312 if (vec)
15313 r = vec;
15315 break;
15317 case USING_DECL:
15318 /* We reach here only for member using decls. We also need to check
15319 uses_template_parms because DECL_DEPENDENT_P is not set for a
15320 using-declaration that designates a member of the current
15321 instantiation (c++/53549). */
15322 if (DECL_DEPENDENT_P (t)
15323 || uses_template_parms (USING_DECL_SCOPE (t)))
15325 /* True iff this using-decl was written as a pack expansion
15326 (and a pack appeared in its scope or name). If a pack
15327 appeared in both, we expand the packs separately and
15328 manually merge them. */
15329 bool variadic_p = false;
15331 tree scope = USING_DECL_SCOPE (t);
15332 if (PACK_EXPANSION_P (scope))
15334 scope = tsubst_pack_expansion (scope, args,
15335 complain | tf_qualifying_scope,
15336 in_decl);
15337 variadic_p = true;
15339 else
15340 scope = tsubst_scope (scope, args, complain, in_decl);
15342 tree name = DECL_NAME (t);
15343 if (IDENTIFIER_CONV_OP_P (name)
15344 && PACK_EXPANSION_P (TREE_TYPE (name)))
15346 name = tsubst_pack_expansion (TREE_TYPE (name), args,
15347 complain, in_decl);
15348 if (name == error_mark_node)
15350 r = error_mark_node;
15351 break;
15353 for (tree& elt : tree_vec_range (name))
15354 elt = make_conv_op_name (elt);
15355 variadic_p = true;
15357 else
15358 name = tsubst_name (name, args, complain, in_decl);
15360 int len;
15361 if (!variadic_p)
15362 len = 1;
15363 else if (TREE_CODE (scope) == TREE_VEC
15364 && TREE_CODE (name) == TREE_VEC)
15366 if (TREE_VEC_LENGTH (scope) != TREE_VEC_LENGTH (name))
15368 error ("mismatched argument pack lengths (%d vs %d)",
15369 TREE_VEC_LENGTH (scope), TREE_VEC_LENGTH (name));
15370 r = error_mark_node;
15371 break;
15373 len = TREE_VEC_LENGTH (scope);
15375 else if (TREE_CODE (scope) == TREE_VEC)
15376 len = TREE_VEC_LENGTH (scope);
15377 else /* TREE_CODE (name) == TREE_VEC */
15378 len = TREE_VEC_LENGTH (name);
15380 r = make_tree_vec (len);
15381 for (int i = 0; i < len; ++i)
15383 tree escope = (TREE_CODE (scope) == TREE_VEC
15384 ? TREE_VEC_ELT (scope, i)
15385 : scope);
15386 tree ename = (TREE_CODE (name) == TREE_VEC
15387 ? TREE_VEC_ELT (name, i)
15388 : name);
15389 tree elt = do_class_using_decl (escope, ename);
15390 if (!elt)
15392 r = error_mark_node;
15393 break;
15395 TREE_PROTECTED (elt) = TREE_PROTECTED (t);
15396 TREE_PRIVATE (elt) = TREE_PRIVATE (t);
15397 TREE_VEC_ELT (r, i) = elt;
15400 if (!variadic_p && r != error_mark_node)
15401 r = TREE_VEC_ELT (r, 0);
15403 else
15405 r = copy_node (t);
15406 DECL_CHAIN (r) = NULL_TREE;
15408 break;
15410 case TYPE_DECL:
15411 case VAR_DECL:
15413 tree argvec = NULL_TREE;
15414 tree gen_tmpl = NULL_TREE;
15415 tree tmpl = NULL_TREE;
15416 tree type = NULL_TREE;
15418 if (TREE_TYPE (t) == error_mark_node)
15419 RETURN (error_mark_node);
15421 if (TREE_CODE (t) == TYPE_DECL
15422 && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
15424 /* If this is the canonical decl, we don't have to
15425 mess with instantiations, and often we can't (for
15426 typename, template type parms and such). Note that
15427 TYPE_NAME is not correct for the above test if
15428 we've copied the type for a typedef. */
15429 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15430 if (type == error_mark_node)
15431 RETURN (error_mark_node);
15432 r = TYPE_NAME (type);
15433 break;
15436 /* Check to see if we already have the specialization we
15437 need. */
15438 tree spec = NULL_TREE;
15439 bool local_p = false;
15440 tree ctx = DECL_CONTEXT (t);
15441 if (!(VAR_P (t) && DECL_LOCAL_DECL_P (t))
15442 && (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t)))
15444 local_p = false;
15445 if (DECL_CLASS_SCOPE_P (t))
15447 ctx = tsubst_aggr_type (ctx, args,
15448 complain,
15449 in_decl, /*entering_scope=*/1);
15450 if (DECL_SELF_REFERENCE_P (t))
15451 /* The context and type of an injected-class-name are
15452 the same, so we don't need to substitute both. */
15453 type = ctx;
15454 /* If CTX is unchanged, then T is in fact the
15455 specialization we want. That situation occurs when
15456 referencing a static data member within in its own
15457 class. We can use pointer equality, rather than
15458 same_type_p, because DECL_CONTEXT is always
15459 canonical... */
15460 if (ctx == DECL_CONTEXT (t)
15461 /* ... unless T is a member template; in which
15462 case our caller can be willing to create a
15463 specialization of that template represented
15464 by T. */
15465 && !(DECL_TI_TEMPLATE (t)
15466 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (t))))
15467 spec = t;
15470 if (!spec)
15472 tmpl = DECL_TI_TEMPLATE (t);
15473 if (use_spec_table)
15475 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
15476 if (argvec == error_mark_node)
15477 RETURN (error_mark_node);
15478 gen_tmpl = most_general_template (tmpl);
15479 hash = spec_hasher::hash (gen_tmpl, argvec);
15480 spec = retrieve_specialization (gen_tmpl, argvec, hash);
15482 else
15483 argvec = args;
15486 else
15488 if (!(VAR_P (t) && DECL_LOCAL_DECL_P (t)))
15489 /* Subsequent calls to pushdecl will fill this in. */
15490 ctx = NULL_TREE;
15491 /* A local variable. */
15492 local_p = true;
15493 /* Unless this is a reference to a static variable from an
15494 enclosing function, in which case we need to fill it in now. */
15495 if (TREE_STATIC (t))
15497 tree fn = enclosing_instantiation_of (DECL_CONTEXT (t));
15498 if (fn != current_function_decl)
15499 ctx = fn;
15501 spec = retrieve_local_specialization (t);
15503 /* If we already have the specialization we need, there is
15504 nothing more to do. */
15505 if (spec)
15507 r = spec;
15508 break;
15511 /* Create a new node for the specialization we need. */
15512 if (type == NULL_TREE)
15514 if (is_typedef_decl (t))
15515 type = DECL_ORIGINAL_TYPE (t);
15516 else
15517 type = TREE_TYPE (t);
15518 if (VAR_P (t)
15519 && VAR_HAD_UNKNOWN_BOUND (t)
15520 && type != error_mark_node)
15521 type = strip_array_domain (type);
15522 tsubst_flags_t tcomplain = complain;
15523 if (VAR_P (t))
15524 tcomplain |= tf_tst_ok;
15525 type = tsubst (type, args, tcomplain, in_decl);
15526 /* Substituting the type might have recursively instantiated this
15527 same alias (c++/86171). */
15528 if (use_spec_table && gen_tmpl && DECL_ALIAS_TEMPLATE_P (gen_tmpl)
15529 && (spec = retrieve_specialization (gen_tmpl, argvec, hash)))
15531 r = spec;
15532 break;
15535 if (type == error_mark_node && !(complain & tf_error))
15536 RETURN (error_mark_node);
15537 r = copy_decl (t);
15538 if (VAR_P (r))
15540 DECL_INITIALIZED_P (r) = 0;
15541 DECL_TEMPLATE_INSTANTIATED (r) = 0;
15542 if (TREE_CODE (type) == FUNCTION_TYPE)
15544 /* It may seem that this case cannot occur, since:
15546 typedef void f();
15547 void g() { f x; }
15549 declares a function, not a variable. However:
15551 typedef void f();
15552 template <typename T> void g() { T t; }
15553 template void g<f>();
15555 is an attempt to declare a variable with function
15556 type. */
15557 error ("variable %qD has function type",
15558 /* R is not yet sufficiently initialized, so we
15559 just use its name. */
15560 DECL_NAME (r));
15561 RETURN (error_mark_node);
15563 type = complete_type (type);
15564 /* Wait until cp_finish_decl to set this again, to handle
15565 circular dependency (template/instantiate6.C). */
15566 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
15567 type = check_var_type (DECL_NAME (r), type,
15568 DECL_SOURCE_LOCATION (r));
15569 if (DECL_HAS_VALUE_EXPR_P (t))
15571 tree ve = DECL_VALUE_EXPR (t);
15572 /* If the DECL_VALUE_EXPR is converted to the declared type,
15573 preserve the identity so that gimplify_type_sizes works. */
15574 bool nop = (TREE_CODE (ve) == NOP_EXPR);
15575 if (nop)
15576 ve = TREE_OPERAND (ve, 0);
15577 ve = tsubst_expr (ve, args, complain, in_decl);
15578 if (REFERENCE_REF_P (ve))
15580 gcc_assert (TYPE_REF_P (type));
15581 ve = TREE_OPERAND (ve, 0);
15583 if (nop)
15584 ve = build_nop (type, ve);
15585 else if (DECL_LANG_SPECIFIC (t)
15586 && DECL_OMP_PRIVATIZED_MEMBER (t)
15587 && TREE_CODE (ve) == COMPONENT_REF
15588 && TREE_CODE (TREE_OPERAND (ve, 1)) == FIELD_DECL
15589 && DECL_BIT_FIELD_TYPE (TREE_OPERAND (ve, 1)) == type)
15590 type = TREE_TYPE (ve);
15591 else
15592 gcc_checking_assert (TYPE_MAIN_VARIANT (TREE_TYPE (ve))
15593 == TYPE_MAIN_VARIANT (type));
15594 SET_DECL_VALUE_EXPR (r, ve);
15596 if (CP_DECL_THREAD_LOCAL_P (r)
15597 && !processing_template_decl)
15598 set_decl_tls_model (r, decl_default_tls_model (r));
15600 else if (DECL_SELF_REFERENCE_P (t))
15601 SET_DECL_SELF_REFERENCE_P (r);
15602 TREE_TYPE (r) = type;
15603 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
15604 DECL_CONTEXT (r) = ctx;
15605 /* Clear out the mangled name and RTL for the instantiation. */
15606 SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
15607 if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
15608 SET_DECL_RTL (r, NULL);
15609 set_instantiating_module (r);
15611 /* The initializer must not be expanded until it is required;
15612 see [temp.inst]. */
15613 DECL_INITIAL (r) = NULL_TREE;
15614 DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
15615 if (VAR_P (r))
15617 if (DECL_LANG_SPECIFIC (r))
15618 SET_DECL_DEPENDENT_INIT_P (r, false);
15620 SET_DECL_MODE (r, VOIDmode);
15622 /* Possibly limit visibility based on template args. */
15623 DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
15624 if (DECL_VISIBILITY_SPECIFIED (t))
15626 DECL_VISIBILITY_SPECIFIED (r) = 0;
15627 DECL_ATTRIBUTES (r)
15628 = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
15630 determine_visibility (r);
15631 if ((!local_p || TREE_STATIC (t)) && DECL_SECTION_NAME (t))
15632 set_decl_section_name (r, t);
15635 if (!local_p)
15637 /* A static data member declaration is always marked
15638 external when it is declared in-class, even if an
15639 initializer is present. We mimic the non-template
15640 processing here. */
15641 DECL_EXTERNAL (r) = 1;
15642 if (DECL_NAMESPACE_SCOPE_P (t))
15643 DECL_NOT_REALLY_EXTERN (r) = 1;
15645 DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
15646 SET_DECL_IMPLICIT_INSTANTIATION (r);
15647 if (use_spec_table)
15648 register_specialization (r, gen_tmpl, argvec, false, hash);
15650 else
15652 if (DECL_LANG_SPECIFIC (r))
15653 DECL_TEMPLATE_INFO (r) = NULL_TREE;
15654 if (!cp_unevaluated_operand)
15655 register_local_specialization (r, t);
15658 DECL_CHAIN (r) = NULL_TREE;
15660 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
15661 /*flags=*/0,
15662 args, complain, in_decl))
15663 return error_mark_node;
15665 /* Preserve a typedef that names a type. */
15666 if (is_typedef_decl (r) && type != error_mark_node)
15668 DECL_ORIGINAL_TYPE (r) = NULL_TREE;
15669 set_underlying_type (r);
15671 /* common_handle_aligned_attribute doesn't apply the alignment
15672 to DECL_ORIGINAL_TYPE. */
15673 if (TYPE_USER_ALIGN (TREE_TYPE (t)))
15674 TREE_TYPE (r) = build_aligned_type (TREE_TYPE (r),
15675 TYPE_ALIGN (TREE_TYPE (t)));
15678 layout_decl (r, 0);
15680 break;
15682 default:
15683 gcc_unreachable ();
15685 #undef RETURN
15687 out:
15688 /* Restore the file and line information. */
15689 input_location = saved_loc;
15691 return r;
15694 /* Substitute into the complete parameter type list PARMS. */
15696 tree
15697 tsubst_function_parms (tree parms,
15698 tree args,
15699 tsubst_flags_t complain,
15700 tree in_decl)
15702 return tsubst_arg_types (parms, args, NULL_TREE, complain, in_decl);
15705 /* Substitute into the ARG_TYPES of a function type.
15706 If END is a TREE_CHAIN, leave it and any following types
15707 un-substituted. */
15709 static tree
15710 tsubst_arg_types (tree arg_types,
15711 tree args,
15712 tree end,
15713 tsubst_flags_t complain,
15714 tree in_decl)
15716 tree type = NULL_TREE;
15717 int len = 1;
15718 tree expanded_args = NULL_TREE;
15720 if (!arg_types || arg_types == void_list_node || arg_types == end)
15721 return arg_types;
15723 if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
15725 /* For a pack expansion, perform substitution on the
15726 entire expression. Later on, we'll handle the arguments
15727 one-by-one. */
15728 expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
15729 args, complain, in_decl);
15731 if (TREE_CODE (expanded_args) == TREE_VEC)
15732 /* So that we'll spin through the parameters, one by one. */
15733 len = TREE_VEC_LENGTH (expanded_args);
15734 else
15736 /* We only partially substituted into the parameter
15737 pack. Our type is TYPE_PACK_EXPANSION. */
15738 type = expanded_args;
15739 expanded_args = NULL_TREE;
15742 else
15743 type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
15745 /* Check if a substituted type is erroneous before substituting into
15746 the rest of the chain. */
15747 for (int i = 0; i < len; i++)
15749 if (expanded_args)
15750 type = TREE_VEC_ELT (expanded_args, i);
15752 if (type == error_mark_node)
15753 return error_mark_node;
15754 if (VOID_TYPE_P (type))
15756 if (complain & tf_error)
15758 error ("invalid parameter type %qT", type);
15759 if (in_decl)
15760 error ("in declaration %q+D", in_decl);
15762 return error_mark_node;
15766 /* We do not substitute into default arguments here. The standard
15767 mandates that they be instantiated only when needed, which is
15768 done in build_over_call. */
15769 tree default_arg = TREE_PURPOSE (arg_types);
15771 /* Except that we do substitute default arguments under tsubst_lambda_expr,
15772 since the new op() won't have any associated template arguments for us
15773 to refer to later. */
15774 if (lambda_fn_in_template_p (in_decl)
15775 || (in_decl && TREE_CODE (in_decl) == FUNCTION_DECL
15776 && DECL_LOCAL_DECL_P (in_decl)))
15777 default_arg = tsubst_expr (default_arg, args, complain, in_decl);
15779 tree remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
15780 args, end, complain, in_decl);
15781 if (remaining_arg_types == error_mark_node)
15782 return error_mark_node;
15784 for (int i = len-1; i >= 0; i--)
15786 if (expanded_args)
15787 type = TREE_VEC_ELT (expanded_args, i);
15789 /* Do array-to-pointer, function-to-pointer conversion, and ignore
15790 top-level qualifiers as required. */
15791 type = cv_unqualified (type_decays_to (type));
15793 if (default_arg && TREE_CODE (default_arg) == DEFERRED_PARSE)
15795 /* We've instantiated a template before its default arguments
15796 have been parsed. This can happen for a nested template
15797 class, and is not an error unless we require the default
15798 argument in a call of this function. */
15799 remaining_arg_types
15800 = tree_cons (default_arg, type, remaining_arg_types);
15801 vec_safe_push (DEFPARSE_INSTANTIATIONS (default_arg),
15802 remaining_arg_types);
15804 else
15805 remaining_arg_types
15806 = hash_tree_cons (default_arg, type, remaining_arg_types);
15809 return remaining_arg_types;
15812 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE. This routine does
15813 *not* handle the exception-specification for FNTYPE, because the
15814 initial substitution of explicitly provided template parameters
15815 during argument deduction forbids substitution into the
15816 exception-specification:
15818 [temp.deduct]
15820 All references in the function type of the function template to the
15821 corresponding template parameters are replaced by the specified tem-
15822 plate argument values. If a substitution in a template parameter or
15823 in the function type of the function template results in an invalid
15824 type, type deduction fails. [Note: The equivalent substitution in
15825 exception specifications is done only when the function is instanti-
15826 ated, at which point a program is ill-formed if the substitution
15827 results in an invalid type.] */
15829 static tree
15830 tsubst_function_type (tree t,
15831 tree args,
15832 tsubst_flags_t complain,
15833 tree in_decl)
15835 tree return_type;
15836 tree arg_types = NULL_TREE;
15838 /* The TYPE_CONTEXT is not used for function/method types. */
15839 gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
15841 /* DR 1227: Mixing immediate and non-immediate contexts in deduction
15842 failure. */
15843 bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
15845 if (late_return_type_p)
15847 /* Substitute the argument types. */
15848 arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
15849 complain, in_decl);
15850 if (arg_types == error_mark_node)
15851 return error_mark_node;
15853 tree save_ccp = current_class_ptr;
15854 tree save_ccr = current_class_ref;
15855 tree this_type = (TREE_CODE (t) == METHOD_TYPE
15856 ? TREE_TYPE (TREE_VALUE (arg_types)) : NULL_TREE);
15857 bool do_inject = this_type && CLASS_TYPE_P (this_type);
15858 if (do_inject)
15860 /* DR 1207: 'this' is in scope in the trailing return type. */
15861 inject_this_parameter (this_type, cp_type_quals (this_type));
15864 /* Substitute the return type. */
15865 return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15867 if (do_inject)
15869 current_class_ptr = save_ccp;
15870 current_class_ref = save_ccr;
15873 else
15874 /* Substitute the return type. */
15875 return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15877 if (return_type == error_mark_node)
15878 return error_mark_node;
15879 /* DR 486 clarifies that creation of a function type with an
15880 invalid return type is a deduction failure. */
15881 if (TREE_CODE (return_type) == ARRAY_TYPE
15882 || TREE_CODE (return_type) == FUNCTION_TYPE)
15884 if (complain & tf_error)
15886 if (TREE_CODE (return_type) == ARRAY_TYPE)
15887 error ("function returning an array");
15888 else
15889 error ("function returning a function");
15891 return error_mark_node;
15894 if (!late_return_type_p)
15896 /* Substitute the argument types. */
15897 arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
15898 complain, in_decl);
15899 if (arg_types == error_mark_node)
15900 return error_mark_node;
15903 /* Construct a new type node and return it. */
15904 return rebuild_function_or_method_type (t, return_type, arg_types,
15905 /*raises=*/NULL_TREE, complain);
15908 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE. Substitute the template
15909 ARGS into that specification, and return the substituted
15910 specification. If there is no specification, return NULL_TREE. */
15912 static tree
15913 tsubst_exception_specification (tree fntype,
15914 tree args,
15915 tsubst_flags_t complain,
15916 tree in_decl,
15917 bool defer_ok)
15919 tree specs;
15920 tree new_specs;
15922 specs = TYPE_RAISES_EXCEPTIONS (fntype);
15923 new_specs = NULL_TREE;
15924 if (specs && TREE_PURPOSE (specs))
15926 /* A noexcept-specifier. */
15927 tree expr = TREE_PURPOSE (specs);
15928 if (TREE_CODE (expr) == INTEGER_CST)
15929 new_specs = expr;
15930 else if (defer_ok)
15932 /* Defer instantiation of noexcept-specifiers to avoid
15933 excessive instantiations (c++/49107). */
15934 new_specs = make_node (DEFERRED_NOEXCEPT);
15935 if (DEFERRED_NOEXCEPT_SPEC_P (specs))
15937 /* We already partially instantiated this member template,
15938 so combine the new args with the old. */
15939 DEFERRED_NOEXCEPT_PATTERN (new_specs)
15940 = DEFERRED_NOEXCEPT_PATTERN (expr);
15941 DEFERRED_NOEXCEPT_ARGS (new_specs)
15942 = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
15944 else
15946 DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
15947 DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
15950 else
15952 if (DEFERRED_NOEXCEPT_SPEC_P (specs))
15954 args = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr),
15955 args);
15956 expr = DEFERRED_NOEXCEPT_PATTERN (expr);
15958 new_specs = tsubst_expr (expr, args, complain, in_decl);
15960 new_specs = build_noexcept_spec (new_specs, complain);
15961 /* We've instantiated a template before a noexcept-specifier
15962 contained therein has been parsed. This can happen for
15963 a nested template class:
15965 struct S {
15966 template<typename> struct B { B() noexcept(...); };
15967 struct A : B<int> { ... use B() ... };
15970 where completing B<int> will trigger instantiating the
15971 noexcept, even though we only parse it at the end of S. */
15972 if (UNPARSED_NOEXCEPT_SPEC_P (specs))
15974 gcc_checking_assert (defer_ok);
15975 vec_safe_push (DEFPARSE_INSTANTIATIONS (expr), new_specs);
15978 else if (specs)
15980 if (! TREE_VALUE (specs))
15981 new_specs = specs;
15982 else
15983 while (specs)
15985 tree spec;
15986 int i, len = 1;
15987 tree expanded_specs = NULL_TREE;
15989 if (PACK_EXPANSION_P (TREE_VALUE (specs)))
15991 /* Expand the pack expansion type. */
15992 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
15993 args, complain,
15994 in_decl);
15996 if (expanded_specs == error_mark_node)
15997 return error_mark_node;
15998 else if (TREE_CODE (expanded_specs) == TREE_VEC)
15999 len = TREE_VEC_LENGTH (expanded_specs);
16000 else
16002 /* We're substituting into a member template, so
16003 we got a TYPE_PACK_EXPANSION back. Add that
16004 expansion and move on. */
16005 gcc_assert (TREE_CODE (expanded_specs)
16006 == TYPE_PACK_EXPANSION);
16007 new_specs = add_exception_specifier (new_specs,
16008 expanded_specs,
16009 complain);
16010 specs = TREE_CHAIN (specs);
16011 continue;
16015 for (i = 0; i < len; ++i)
16017 if (expanded_specs)
16018 spec = TREE_VEC_ELT (expanded_specs, i);
16019 else
16020 spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
16021 if (spec == error_mark_node)
16022 return spec;
16023 new_specs = add_exception_specifier (new_specs, spec,
16024 complain);
16027 specs = TREE_CHAIN (specs);
16030 return new_specs;
16033 /* Substitute through a TREE_LIST of types or expressions, handling pack
16034 expansions. */
16036 tree
16037 tsubst_tree_list (tree t, tree args, tsubst_flags_t complain, tree in_decl)
16039 if (t == void_list_node)
16040 return t;
16042 tree purpose = TREE_PURPOSE (t);
16043 tree purposevec = NULL_TREE;
16044 if (!purpose)
16046 else if (PACK_EXPANSION_P (purpose))
16048 purpose = tsubst_pack_expansion (purpose, args, complain, in_decl);
16049 if (TREE_CODE (purpose) == TREE_VEC)
16050 purposevec = purpose;
16052 else if (TYPE_P (purpose))
16053 purpose = tsubst (purpose, args, complain, in_decl);
16054 else
16055 purpose = tsubst_expr (purpose, args, complain, in_decl);
16056 if (purpose == error_mark_node || purposevec == error_mark_node)
16057 return error_mark_node;
16059 tree value = TREE_VALUE (t);
16060 tree valuevec = NULL_TREE;
16061 if (!value)
16063 else if (PACK_EXPANSION_P (value))
16065 value = tsubst_pack_expansion (value, args, complain, in_decl);
16066 if (TREE_CODE (value) == TREE_VEC)
16067 valuevec = value;
16069 else if (TYPE_P (value))
16070 value = tsubst (value, args, complain, in_decl);
16071 else
16072 value = tsubst_expr (value, args, complain, in_decl);
16073 if (value == error_mark_node || valuevec == error_mark_node)
16074 return error_mark_node;
16076 tree chain = TREE_CHAIN (t);
16077 if (!chain)
16079 else if (TREE_CODE (chain) == TREE_LIST)
16080 chain = tsubst_tree_list (chain, args, complain, in_decl);
16081 else if (TYPE_P (chain))
16082 chain = tsubst (chain, args, complain, in_decl);
16083 else
16084 chain = tsubst_expr (chain, args, complain, in_decl);
16085 if (chain == error_mark_node)
16086 return error_mark_node;
16088 if (purpose == TREE_PURPOSE (t)
16089 && value == TREE_VALUE (t)
16090 && chain == TREE_CHAIN (t))
16091 return t;
16093 int len;
16094 /* Determine the number of arguments. */
16095 if (purposevec)
16097 len = TREE_VEC_LENGTH (purposevec);
16098 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
16100 else if (valuevec)
16101 len = TREE_VEC_LENGTH (valuevec);
16102 else
16103 len = 1;
16105 for (int i = len; i-- > 0; )
16107 if (purposevec)
16108 purpose = TREE_VEC_ELT (purposevec, i);
16109 if (valuevec)
16110 value = TREE_VEC_ELT (valuevec, i);
16112 if (value && TYPE_P (value))
16113 chain = hash_tree_cons (purpose, value, chain);
16114 else
16115 chain = tree_cons (purpose, value, chain);
16118 return chain;
16121 /* Take the tree structure T and replace template parameters used
16122 therein with the argument vector ARGS. IN_DECL is an associated
16123 decl for diagnostics. If an error occurs, returns ERROR_MARK_NODE.
16124 Issue error and warning messages under control of COMPLAIN. Note
16125 that we must be relatively non-tolerant of extensions here, in
16126 order to preserve conformance; if we allow substitutions that
16127 should not be allowed, we may allow argument deductions that should
16128 not succeed, and therefore report ambiguous overload situations
16129 where there are none. In theory, we could allow the substitution,
16130 but indicate that it should have failed, and allow our caller to
16131 make sure that the right thing happens, but we don't try to do this
16132 yet.
16134 This function is used for dealing with types, decls and the like;
16135 for expressions, use tsubst_expr or tsubst_copy. */
16137 tree
16138 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
16140 enum tree_code code;
16141 tree type, r = NULL_TREE;
16143 if (t == NULL_TREE || t == error_mark_node
16144 || t == integer_type_node
16145 || t == void_type_node
16146 || t == char_type_node
16147 || t == unknown_type_node
16148 || TREE_CODE (t) == NAMESPACE_DECL
16149 || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
16150 return t;
16152 tsubst_flags_t tst_ok_flag = (complain & tf_tst_ok);
16153 complain &= ~tf_tst_ok;
16155 tsubst_flags_t qualifying_scope_flag = (complain & tf_qualifying_scope);
16156 complain &= ~tf_qualifying_scope;
16158 if (DECL_P (t))
16159 return tsubst_decl (t, args, complain);
16161 if (args == NULL_TREE)
16162 return t;
16164 code = TREE_CODE (t);
16166 gcc_assert (code != IDENTIFIER_NODE);
16167 type = TREE_TYPE (t);
16169 gcc_assert (type != unknown_type_node);
16171 if (tree d = maybe_dependent_member_ref (t, args, complain, in_decl))
16172 return d;
16174 /* Reuse typedefs. We need to do this to handle dependent attributes,
16175 such as attribute aligned. */
16176 if (TYPE_P (t)
16177 && typedef_variant_p (t))
16179 tree decl = TYPE_NAME (t);
16181 if (alias_template_specialization_p (t, nt_opaque))
16183 /* DECL represents an alias template and we want to
16184 instantiate it. */
16185 tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
16186 tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
16187 r = instantiate_alias_template (tmpl, gen_args, complain);
16189 else if (DECL_CLASS_SCOPE_P (decl)
16190 && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
16191 && uses_template_parms (DECL_CONTEXT (decl)))
16193 tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
16194 tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
16195 r = retrieve_specialization (tmpl, gen_args, 0);
16197 else if (DECL_FUNCTION_SCOPE_P (decl)
16198 && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
16199 && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
16200 r = retrieve_local_specialization (decl);
16201 else
16202 /* The typedef is from a non-template context. */
16203 return t;
16205 if (r)
16207 r = TREE_TYPE (r);
16208 r = cp_build_qualified_type
16209 (r, cp_type_quals (t) | cp_type_quals (r),
16210 complain | tf_ignore_bad_quals);
16211 return r;
16213 else
16215 /* We don't have an instantiation yet, so drop the typedef. */
16216 int quals = cp_type_quals (t);
16217 t = DECL_ORIGINAL_TYPE (decl);
16218 t = cp_build_qualified_type (t, quals,
16219 complain | tf_ignore_bad_quals);
16223 bool fndecl_type = (complain & tf_fndecl_type);
16224 complain &= ~tf_fndecl_type;
16226 if (type
16227 && code != TYPENAME_TYPE
16228 && code != TEMPLATE_TYPE_PARM
16229 && code != TEMPLATE_PARM_INDEX
16230 && code != IDENTIFIER_NODE
16231 && code != FUNCTION_TYPE
16232 && code != METHOD_TYPE)
16233 type = tsubst (type, args, complain, in_decl);
16234 if (type == error_mark_node)
16235 return error_mark_node;
16237 switch (code)
16239 case RECORD_TYPE:
16240 if (TYPE_PTRMEMFUNC_P (t))
16241 return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
16242 /* Fall through. */
16243 case UNION_TYPE:
16244 case ENUMERAL_TYPE:
16245 return tsubst_aggr_type_1 (t, args, complain, in_decl,
16246 /*entering_scope=*/0);
16248 case ERROR_MARK:
16249 case IDENTIFIER_NODE:
16250 case VOID_TYPE:
16251 case OPAQUE_TYPE:
16252 case REAL_TYPE:
16253 case COMPLEX_TYPE:
16254 case VECTOR_TYPE:
16255 case BOOLEAN_TYPE:
16256 case NULLPTR_TYPE:
16257 case LANG_TYPE:
16258 return t;
16260 case INTEGER_TYPE:
16261 if (t == integer_type_node)
16262 return t;
16264 if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
16265 && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
16266 return t;
16269 tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
16271 max = tsubst_expr (omax, args, complain, in_decl);
16273 /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
16274 needed. */
16275 if (TREE_CODE (max) == NOP_EXPR
16276 && TREE_SIDE_EFFECTS (omax)
16277 && !TREE_TYPE (max))
16278 TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
16280 /* If we're in a partial instantiation, preserve the magic NOP_EXPR
16281 with TREE_SIDE_EFFECTS that indicates this is not an integral
16282 constant expression. */
16283 if (processing_template_decl
16284 && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
16286 gcc_assert (TREE_CODE (max) == NOP_EXPR);
16287 TREE_SIDE_EFFECTS (max) = 1;
16290 return compute_array_index_type (NULL_TREE, max, complain);
16293 case TEMPLATE_TYPE_PARM:
16294 if (template_placeholder_p (t))
16296 tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (t);
16297 tmpl = tsubst_expr (tmpl, args, complain, in_decl);
16298 if (TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
16299 tmpl = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (tmpl);
16301 if (tmpl != CLASS_PLACEHOLDER_TEMPLATE (t))
16302 return make_template_placeholder (tmpl);
16303 else
16304 return t;
16306 /* Fall through. */
16307 case TEMPLATE_TEMPLATE_PARM:
16308 case BOUND_TEMPLATE_TEMPLATE_PARM:
16309 case TEMPLATE_PARM_INDEX:
16311 int idx;
16312 int level;
16313 int levels;
16314 tree arg = NULL_TREE;
16316 r = NULL_TREE;
16318 gcc_assert (TREE_VEC_LENGTH (args) > 0);
16319 template_parm_level_and_index (t, &level, &idx);
16321 levels = TMPL_ARGS_DEPTH (args);
16322 if (level <= levels
16323 && TREE_VEC_LENGTH (TMPL_ARGS_LEVEL (args, level)) > 0)
16325 arg = TMPL_ARG (args, level, idx);
16327 /* See through ARGUMENT_PACK_SELECT arguments. */
16328 if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
16329 arg = argument_pack_select_arg (arg);
16332 if (arg == error_mark_node)
16333 return error_mark_node;
16334 else if (arg != NULL_TREE)
16336 if (ARGUMENT_PACK_P (arg))
16337 /* If ARG is an argument pack, we don't actually want to
16338 perform a substitution here, because substitutions
16339 for argument packs are only done
16340 element-by-element. We can get to this point when
16341 substituting the type of a non-type template
16342 parameter pack, when that type actually contains
16343 template parameter packs from an outer template, e.g.,
16345 template<typename... Types> struct A {
16346 template<Types... Values> struct B { };
16347 }; */
16348 return t;
16350 if (code == TEMPLATE_TYPE_PARM)
16352 int quals;
16354 /* When building concept checks for the purpose of
16355 deducing placeholders, we can end up with wildcards
16356 where types are expected. Adjust this to the deduced
16357 value. */
16358 if (TREE_CODE (arg) == WILDCARD_DECL)
16359 arg = TREE_TYPE (TREE_TYPE (arg));
16361 gcc_assert (TYPE_P (arg));
16363 quals = cp_type_quals (arg) | cp_type_quals (t);
16365 return cp_build_qualified_type
16366 (arg, quals, complain | tf_ignore_bad_quals);
16368 else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
16370 /* We are processing a type constructed from a
16371 template template parameter. */
16372 tree argvec = tsubst (TYPE_TI_ARGS (t),
16373 args, complain, in_decl);
16374 if (argvec == error_mark_node)
16375 return error_mark_node;
16377 gcc_assert (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
16378 || TREE_CODE (arg) == TEMPLATE_DECL
16379 || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
16381 if (TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
16382 /* Consider this code:
16384 template <template <class> class Template>
16385 struct Internal {
16386 template <class Arg> using Bind = Template<Arg>;
16389 template <template <class> class Template, class Arg>
16390 using Instantiate = Template<Arg>; //#0
16392 template <template <class> class Template,
16393 class Argument>
16394 using Bind =
16395 Instantiate<Internal<Template>::template Bind,
16396 Argument>; //#1
16398 When #1 is parsed, the
16399 BOUND_TEMPLATE_TEMPLATE_PARM representing the
16400 parameter `Template' in #0 matches the
16401 UNBOUND_CLASS_TEMPLATE representing the argument
16402 `Internal<Template>::template Bind'; We then want
16403 to assemble the type `Bind<Argument>' that can't
16404 be fully created right now, because
16405 `Internal<Template>' not being complete, the Bind
16406 template cannot be looked up in that context. So
16407 we need to "store" `Bind<Argument>' for later
16408 when the context of Bind becomes complete. Let's
16409 store that in a TYPENAME_TYPE. */
16410 return make_typename_type (TYPE_CONTEXT (arg),
16411 build_nt (TEMPLATE_ID_EXPR,
16412 TYPE_IDENTIFIER (arg),
16413 argvec),
16414 typename_type,
16415 complain);
16417 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
16418 are resolving nested-types in the signature of a
16419 member function templates. Otherwise ARG is a
16420 TEMPLATE_DECL and is the real template to be
16421 instantiated. */
16422 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
16423 arg = TYPE_NAME (arg);
16425 r = lookup_template_class (arg,
16426 argvec, in_decl,
16427 DECL_CONTEXT (arg),
16428 /*entering_scope=*/0,
16429 complain);
16430 return cp_build_qualified_type
16431 (r, cp_type_quals (t) | cp_type_quals (r), complain);
16433 else if (code == TEMPLATE_TEMPLATE_PARM)
16434 return arg;
16435 else
16436 /* TEMPLATE_PARM_INDEX. */
16437 return convert_from_reference (unshare_expr (arg));
16440 if (level == 1)
16441 /* This can happen during the attempted tsubst'ing in
16442 unify. This means that we don't yet have any information
16443 about the template parameter in question. */
16444 return t;
16446 /* Early in template argument deduction substitution, we don't
16447 want to reduce the level of 'auto', or it will be confused
16448 with a normal template parm in subsequent deduction.
16449 Similarly, don't reduce the level of template parameters to
16450 avoid mismatches when deducing their types. */
16451 if (complain & tf_partial)
16452 return t;
16454 /* If we get here, we must have been looking at a parm for a
16455 more deeply nested template. Make a new version of this
16456 template parameter, but with a lower level. */
16457 int quals;
16458 switch (code)
16460 case TEMPLATE_TYPE_PARM:
16461 case TEMPLATE_TEMPLATE_PARM:
16462 quals = cp_type_quals (t);
16463 if (quals)
16465 gcc_checking_assert (code == TEMPLATE_TYPE_PARM);
16466 t = TYPE_MAIN_VARIANT (t);
16469 if (tree d = TEMPLATE_TYPE_DESCENDANTS (t))
16470 if (TEMPLATE_PARM_LEVEL (d) == TEMPLATE_TYPE_LEVEL (t) - levels
16471 && (code == TEMPLATE_TYPE_PARM
16472 || TEMPLATE_TEMPLATE_PARM_SIMPLE_P (t)))
16473 /* Cache lowering a type parameter or a simple template
16474 template parameter. */
16475 r = TREE_TYPE (d);
16477 if (!r)
16479 r = copy_type (t);
16480 TEMPLATE_TYPE_PARM_INDEX (r)
16481 = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
16482 r, levels, args, complain);
16483 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
16484 TYPE_MAIN_VARIANT (r) = r;
16485 TYPE_POINTER_TO (r) = NULL_TREE;
16486 TYPE_REFERENCE_TO (r) = NULL_TREE;
16488 if (code == TEMPLATE_TYPE_PARM)
16489 if (tree ci = PLACEHOLDER_TYPE_CONSTRAINTS_INFO (t))
16490 /* Propagate constraints on placeholders since they are
16491 only instantiated during satisfaction. */
16492 PLACEHOLDER_TYPE_CONSTRAINTS_INFO (r) = ci;
16494 if (TYPE_STRUCTURAL_EQUALITY_P (t))
16495 SET_TYPE_STRUCTURAL_EQUALITY (r);
16496 else
16497 TYPE_CANONICAL (r) = canonical_type_parameter (r);
16500 if (quals)
16501 r = cp_build_qualified_type (r, quals,
16502 complain | tf_ignore_bad_quals);
16503 break;
16505 case BOUND_TEMPLATE_TEMPLATE_PARM:
16507 tree tinfo = TYPE_TEMPLATE_INFO (t);
16508 /* We might need to substitute into the types of non-type
16509 template parameters. This also lowers the level of
16510 the ttp appropriately. */
16511 tree tmpl = tsubst (TI_TEMPLATE (tinfo), args,
16512 complain, in_decl);
16513 if (tmpl == error_mark_node)
16514 return error_mark_node;
16515 tree argvec = tsubst (TI_ARGS (tinfo), args,
16516 complain, in_decl);
16517 if (argvec == error_mark_node)
16518 return error_mark_node;
16519 r = lookup_template_class (tmpl, argvec, in_decl, NULL_TREE,
16520 /*entering_scope=*/false, complain);
16521 r = cp_build_qualified_type (r, cp_type_quals (t), complain);
16522 break;
16525 case TEMPLATE_PARM_INDEX:
16526 /* OK, now substitute the type of the non-type parameter. We
16527 couldn't do it earlier because it might be an auto parameter,
16528 and we wouldn't need to if we had an argument. */
16529 type = tsubst (type, args, complain, in_decl);
16530 if (type == error_mark_node)
16531 return error_mark_node;
16532 r = reduce_template_parm_level (t, type, levels, args, complain);
16533 break;
16535 default:
16536 gcc_unreachable ();
16539 return r;
16542 case TREE_LIST:
16543 return tsubst_tree_list (t, args, complain, in_decl);
16545 case TREE_BINFO:
16546 /* We should never be tsubsting a binfo. */
16547 gcc_unreachable ();
16549 case TREE_VEC:
16550 /* A vector of template arguments. */
16551 gcc_assert (!type);
16552 return tsubst_template_args (t, args, complain, in_decl);
16554 case POINTER_TYPE:
16555 case REFERENCE_TYPE:
16557 if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
16558 return t;
16560 /* [temp.deduct]
16562 Type deduction may fail for any of the following
16563 reasons:
16565 -- Attempting to create a pointer to reference type.
16566 -- Attempting to create a reference to a reference type or
16567 a reference to void.
16569 Core issue 106 says that creating a reference to a reference
16570 during instantiation is no longer a cause for failure. We
16571 only enforce this check in strict C++98 mode. */
16572 if ((TYPE_REF_P (type)
16573 && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
16574 || (code == REFERENCE_TYPE && VOID_TYPE_P (type)))
16576 static location_t last_loc;
16578 /* We keep track of the last time we issued this error
16579 message to avoid spewing a ton of messages during a
16580 single bad template instantiation. */
16581 if (complain & tf_error
16582 && last_loc != input_location)
16584 if (VOID_TYPE_P (type))
16585 error ("forming reference to void");
16586 else if (code == POINTER_TYPE)
16587 error ("forming pointer to reference type %qT", type);
16588 else
16589 error ("forming reference to reference type %qT", type);
16590 last_loc = input_location;
16593 return error_mark_node;
16595 else if (TREE_CODE (type) == FUNCTION_TYPE
16596 && (type_memfn_quals (type) != TYPE_UNQUALIFIED
16597 || type_memfn_rqual (type) != REF_QUAL_NONE))
16599 if (complain & tf_error)
16601 if (code == POINTER_TYPE)
16602 error ("forming pointer to qualified function type %qT",
16603 type);
16604 else
16605 error ("forming reference to qualified function type %qT",
16606 type);
16608 return error_mark_node;
16610 else if (code == POINTER_TYPE)
16612 r = build_pointer_type (type);
16613 if (TREE_CODE (type) == METHOD_TYPE)
16614 r = build_ptrmemfunc_type (r);
16616 else if (TYPE_REF_P (type))
16617 /* In C++0x, during template argument substitution, when there is an
16618 attempt to create a reference to a reference type, reference
16619 collapsing is applied as described in [14.3.1/4 temp.arg.type]:
16621 "If a template-argument for a template-parameter T names a type
16622 that is a reference to a type A, an attempt to create the type
16623 'lvalue reference to cv T' creates the type 'lvalue reference to
16624 A,' while an attempt to create the type type rvalue reference to
16625 cv T' creates the type T"
16627 r = cp_build_reference_type
16628 (TREE_TYPE (type),
16629 TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
16630 else
16631 r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
16632 r = cp_build_qualified_type (r, cp_type_quals (t), complain);
16634 if (r != error_mark_node)
16635 /* Will this ever be needed for TYPE_..._TO values? */
16636 layout_type (r);
16638 return r;
16640 case OFFSET_TYPE:
16642 r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
16643 if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
16645 /* [temp.deduct]
16647 Type deduction may fail for any of the following
16648 reasons:
16650 -- Attempting to create "pointer to member of T" when T
16651 is not a class type. */
16652 if (complain & tf_error)
16653 error ("creating pointer to member of non-class type %qT", r);
16654 return error_mark_node;
16656 if (TYPE_REF_P (type))
16658 if (complain & tf_error)
16659 error ("creating pointer to member reference type %qT", type);
16660 return error_mark_node;
16662 if (VOID_TYPE_P (type))
16664 if (complain & tf_error)
16665 error ("creating pointer to member of type void");
16666 return error_mark_node;
16668 gcc_assert (TREE_CODE (type) != METHOD_TYPE);
16669 if (TREE_CODE (type) == FUNCTION_TYPE)
16671 /* The type of the implicit object parameter gets its
16672 cv-qualifiers from the FUNCTION_TYPE. */
16673 tree memptr;
16674 tree method_type
16675 = build_memfn_type (type, r, type_memfn_quals (type),
16676 type_memfn_rqual (type));
16677 memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
16678 return cp_build_qualified_type (memptr, cp_type_quals (t),
16679 complain);
16681 else
16682 return cp_build_qualified_type (build_ptrmem_type (r, type),
16683 cp_type_quals (t),
16684 complain);
16686 case FUNCTION_TYPE:
16687 case METHOD_TYPE:
16689 tree fntype;
16690 tree specs;
16691 fntype = tsubst_function_type (t, args, complain, in_decl);
16692 if (fntype == error_mark_node)
16693 return error_mark_node;
16695 /* Substitute the exception specification. */
16696 specs = tsubst_exception_specification (t, args, complain, in_decl,
16697 /*defer_ok*/fndecl_type);
16698 if (specs == error_mark_node)
16699 return error_mark_node;
16700 if (specs)
16701 fntype = build_exception_variant (fntype, specs);
16702 return fntype;
16704 case ARRAY_TYPE:
16706 tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
16707 if (domain == error_mark_node)
16708 return error_mark_node;
16710 /* As an optimization, we avoid regenerating the array type if
16711 it will obviously be the same as T. */
16712 if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
16713 return t;
16715 /* These checks should match the ones in create_array_type_for_decl.
16717 [temp.deduct]
16719 The deduction may fail for any of the following reasons:
16721 -- Attempting to create an array with an element type that
16722 is void, a function type, or a reference type, or [DR337]
16723 an abstract class type. */
16724 if (VOID_TYPE_P (type)
16725 || TREE_CODE (type) == FUNCTION_TYPE
16726 || (TREE_CODE (type) == ARRAY_TYPE
16727 && TYPE_DOMAIN (type) == NULL_TREE)
16728 || TYPE_REF_P (type))
16730 if (complain & tf_error)
16731 error ("creating array of %qT", type);
16732 return error_mark_node;
16735 if (!verify_type_context (input_location, TCTX_ARRAY_ELEMENT, type,
16736 !(complain & tf_error)))
16737 return error_mark_node;
16739 r = build_cplus_array_type (type, domain);
16741 if (!valid_array_size_p (input_location, r, in_decl,
16742 (complain & tf_error)))
16743 return error_mark_node;
16745 if (TYPE_USER_ALIGN (t))
16747 SET_TYPE_ALIGN (r, TYPE_ALIGN (t));
16748 TYPE_USER_ALIGN (r) = 1;
16751 return r;
16754 case TYPENAME_TYPE:
16756 tree ctx = TYPE_CONTEXT (t);
16757 if (TREE_CODE (ctx) == TYPE_PACK_EXPANSION)
16759 ctx = tsubst_pack_expansion (ctx, args,
16760 complain | tf_qualifying_scope,
16761 in_decl);
16762 if (ctx == error_mark_node
16763 || TREE_VEC_LENGTH (ctx) > 1)
16764 return error_mark_node;
16765 if (TREE_VEC_LENGTH (ctx) == 0)
16767 if (complain & tf_error)
16768 error ("%qD is instantiated for an empty pack",
16769 TYPENAME_TYPE_FULLNAME (t));
16770 return error_mark_node;
16772 ctx = TREE_VEC_ELT (ctx, 0);
16774 else
16775 ctx = tsubst_aggr_type (ctx, args,
16776 complain | tf_qualifying_scope,
16777 in_decl, /*entering_scope=*/1);
16778 if (ctx == error_mark_node)
16779 return error_mark_node;
16781 tree f = tsubst_name (TYPENAME_TYPE_FULLNAME (t), args,
16782 complain, in_decl);
16783 if (f == error_mark_node)
16784 return error_mark_node;
16786 if (!MAYBE_CLASS_TYPE_P (ctx))
16788 if (complain & tf_error)
16789 error ("%qT is not a class, struct, or union type", ctx);
16790 return error_mark_node;
16792 else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
16794 /* Normally, make_typename_type does not require that the CTX
16795 have complete type in order to allow things like:
16797 template <class T> struct S { typename S<T>::X Y; };
16799 But, such constructs have already been resolved by this
16800 point, so here CTX really should have complete type, unless
16801 it's a partial instantiation. */
16802 if (!complete_type_or_maybe_complain (ctx, NULL_TREE, complain))
16803 return error_mark_node;
16806 /* FIXME: TYPENAME_IS_CLASS_P conflates 'class' vs 'struct' vs 'union'
16807 tags. TYPENAME_TYPE should probably remember the exact tag that
16808 was written. */
16809 enum tag_types tag_type
16810 = TYPENAME_IS_CLASS_P (t) ? class_type
16811 : TYPENAME_IS_ENUM_P (t) ? enum_type
16812 : typename_type;
16813 tsubst_flags_t tcomplain = complain | tf_keep_type_decl;
16814 tcomplain |= tst_ok_flag | qualifying_scope_flag;
16815 f = make_typename_type (ctx, f, tag_type, tcomplain);
16816 if (f == error_mark_node)
16817 return f;
16818 if (TREE_CODE (f) == TYPE_DECL)
16820 complain |= tf_ignore_bad_quals;
16821 f = TREE_TYPE (f);
16824 if (TREE_CODE (f) != TYPENAME_TYPE)
16826 if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
16828 if (complain & tf_error)
16829 error ("%qT resolves to %qT, which is not an enumeration type",
16830 t, f);
16831 else
16832 return error_mark_node;
16834 else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
16836 if (complain & tf_error)
16837 error ("%qT resolves to %qT, which is not a class type",
16838 t, f);
16839 else
16840 return error_mark_node;
16844 return cp_build_qualified_type
16845 (f, cp_type_quals (f) | cp_type_quals (t), complain);
16848 case UNBOUND_CLASS_TEMPLATE:
16850 tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
16851 in_decl, /*entering_scope=*/1);
16852 tree name = TYPE_IDENTIFIER (t);
16853 tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
16855 if (ctx == error_mark_node || name == error_mark_node)
16856 return error_mark_node;
16858 if (parm_list)
16859 parm_list = tsubst_template_parms (parm_list, args, complain);
16860 return make_unbound_class_template (ctx, name, parm_list, complain);
16863 case TYPEOF_TYPE:
16865 tree type;
16867 ++cp_unevaluated_operand;
16868 ++c_inhibit_evaluation_warnings;
16870 type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args, complain, in_decl);
16872 --cp_unevaluated_operand;
16873 --c_inhibit_evaluation_warnings;
16875 type = finish_typeof (type);
16876 return cp_build_qualified_type (type,
16877 cp_type_quals (t)
16878 | cp_type_quals (type),
16879 complain);
16882 case DECLTYPE_TYPE:
16884 tree type;
16886 ++cp_unevaluated_operand;
16887 ++c_inhibit_evaluation_warnings;
16889 type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
16890 complain|tf_decltype, in_decl);
16892 --cp_unevaluated_operand;
16893 --c_inhibit_evaluation_warnings;
16895 if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
16896 type = lambda_capture_field_type (type,
16897 false /*explicit_init*/,
16898 DECLTYPE_FOR_REF_CAPTURE (t));
16899 else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
16900 type = lambda_proxy_type (type);
16901 else
16903 bool id = DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t);
16904 if (id && TREE_CODE (DECLTYPE_TYPE_EXPR (t)) == BIT_NOT_EXPR
16905 && EXPR_P (type))
16906 /* In a template ~id could be either a complement expression
16907 or an unqualified-id naming a destructor; if instantiating
16908 it produces an expression, it's not an id-expression or
16909 member access. */
16910 id = false;
16911 type = finish_decltype_type (type, id, complain);
16913 return cp_build_qualified_type (type,
16914 cp_type_quals (t)
16915 | cp_type_quals (type),
16916 complain | tf_ignore_bad_quals);
16919 case TRAIT_TYPE:
16921 tree type1 = TRAIT_TYPE_TYPE1 (t);
16922 if (TYPE_P (type1))
16923 type1 = tsubst (type1, args, complain, in_decl);
16924 else
16925 type1 = tsubst_expr (type1, args, complain, in_decl);
16926 tree type2 = tsubst (TRAIT_TYPE_TYPE2 (t), args, complain, in_decl);
16927 type = finish_trait_type (TRAIT_TYPE_KIND (t), type1, type2, complain);
16928 return cp_build_qualified_type (type,
16929 cp_type_quals (t) | cp_type_quals (type),
16930 complain | tf_ignore_bad_quals);
16933 case TYPE_ARGUMENT_PACK:
16934 case NONTYPE_ARGUMENT_PACK:
16935 return tsubst_argument_pack (t, args, complain, in_decl);
16937 case VOID_CST:
16938 case INTEGER_CST:
16939 case REAL_CST:
16940 case STRING_CST:
16941 case PLUS_EXPR:
16942 case MINUS_EXPR:
16943 case NEGATE_EXPR:
16944 case NOP_EXPR:
16945 case INDIRECT_REF:
16946 case ADDR_EXPR:
16947 case CALL_EXPR:
16948 case ARRAY_REF:
16949 case SCOPE_REF:
16950 case OMP_ARRAY_SECTION:
16951 /* We should use one of the expression tsubsts for these codes. */
16952 gcc_unreachable ();
16954 default:
16955 sorry ("use of %qs in template", get_tree_code_name (code));
16956 return error_mark_node;
16960 /* Convenience wrapper over tsubst for substituting into the LHS
16961 of the :: scope resolution operator. */
16963 static tree
16964 tsubst_scope (tree t, tree args, tsubst_flags_t complain, tree in_decl)
16966 gcc_checking_assert (TYPE_P (t));
16967 return tsubst (t, args, complain | tf_qualifying_scope, in_decl);
16970 /* Convenience wrapper over tsubst for substituting into an id-expression
16971 without resolving its terminal name. */
16973 static tree
16974 tsubst_name (tree t, tree args, tsubst_flags_t complain, tree in_decl)
16976 return tsubst_expr (t, args, complain | tf_no_name_lookup, in_decl);
16979 /* OLDFNS is a lookup set of member functions from some class template, and
16980 NEWFNS is a lookup set of member functions from NEWTYPE, a specialization
16981 of that class template. Return the subset of NEWFNS which are
16982 specializations of a function from OLDFNS. */
16984 static tree
16985 filter_memfn_lookup (tree oldfns, tree newfns, tree newtype)
16987 /* Record all member functions from the old lookup set OLDFNS into
16988 VISIBLE_SET. */
16989 hash_set<tree> visible_set;
16990 bool seen_dep_using = false;
16991 for (tree fn : lkp_range (oldfns))
16993 if (TREE_CODE (fn) == USING_DECL)
16995 /* Imprecisely handle dependent using-decl by keeping all members
16996 in the new lookup set that are defined in a base class, i.e.
16997 members that could plausibly have been introduced by this
16998 dependent using-decl.
16999 FIXME: Track which members are introduced by a dependent
17000 using-decl precisely, perhaps by performing another lookup
17001 from the substituted USING_DECL_SCOPE. */
17002 gcc_checking_assert (DECL_DEPENDENT_P (fn));
17003 seen_dep_using = true;
17005 else
17006 visible_set.add (fn);
17009 /* Returns true iff (a less specialized version of) FN appeared in
17010 the old lookup set OLDFNS. */
17011 auto visible_p = [newtype, seen_dep_using, &visible_set] (tree fn) {
17012 if (DECL_CONTEXT (fn) != newtype)
17013 /* FN is a member function from a base class, introduced via a
17014 using-decl; if it might have been introduced by a dependent
17015 using-decl then just conservatively keep it, otherwise look
17016 in the old lookup set for FN exactly. */
17017 return seen_dep_using || visible_set.contains (fn);
17018 else if (TREE_CODE (fn) == TEMPLATE_DECL)
17019 /* FN is a member function template from the current class;
17020 look in the old lookup set for the TEMPLATE_DECL from which
17021 it was specialized. */
17022 return visible_set.contains (DECL_TI_TEMPLATE (fn));
17023 else
17024 /* FN is a non-template member function from the current class;
17025 look in the old lookup set for the FUNCTION_DECL from which
17026 it was specialized. */
17027 return visible_set.contains (DECL_TEMPLATE_RESULT
17028 (DECL_TI_TEMPLATE (fn)));
17031 bool lookup_changed_p = false;
17032 for (tree fn : lkp_range (newfns))
17033 if (!visible_p (fn))
17035 lookup_changed_p = true;
17036 break;
17038 if (!lookup_changed_p)
17039 return newfns;
17041 /* Filter out from NEWFNS the member functions that weren't
17042 previously visible according to OLDFNS. */
17043 tree filtered_fns = NULL_TREE;
17044 unsigned filtered_size = 0;
17045 for (tree fn : lkp_range (newfns))
17046 if (visible_p (fn))
17048 filtered_fns = lookup_add (fn, filtered_fns);
17049 filtered_size++;
17051 gcc_checking_assert (seen_dep_using
17052 ? filtered_size >= visible_set.elements ()
17053 : filtered_size == visible_set.elements ());
17055 return filtered_fns;
17058 /* tsubst a BASELINK. OBJECT_TYPE, if non-NULL, is the type of the
17059 expression on the left-hand side of the "." or "->" operator. We
17060 only do the lookup if we had a dependent BASELINK. Otherwise we
17061 adjust it onto the instantiated heirarchy. */
17063 static tree
17064 tsubst_baselink (tree baselink, tree object_type,
17065 tree args, tsubst_flags_t complain, tree in_decl)
17067 bool qualified_p = BASELINK_QUALIFIED_P (baselink);
17068 tree qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
17069 qualifying_scope = tsubst (qualifying_scope, args, complain, in_decl);
17071 tree optype = BASELINK_OPTYPE (baselink);
17072 optype = tsubst (optype, args, complain, in_decl);
17074 tree template_args = NULL_TREE;
17075 bool template_id_p = false;
17076 tree fns = BASELINK_FUNCTIONS (baselink);
17077 if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
17079 template_id_p = true;
17080 template_args = TREE_OPERAND (fns, 1);
17081 fns = TREE_OPERAND (fns, 0);
17082 if (template_args)
17083 template_args = tsubst_template_args (template_args, args,
17084 complain, in_decl);
17087 tree binfo_type = BINFO_TYPE (BASELINK_BINFO (baselink));
17088 binfo_type = tsubst (binfo_type, args, complain, in_decl);
17089 bool dependent_p = (binfo_type != BINFO_TYPE (BASELINK_BINFO (baselink))
17090 || optype != BASELINK_OPTYPE (baselink));
17092 if (dependent_p)
17094 tree name = OVL_NAME (fns);
17095 if (IDENTIFIER_CONV_OP_P (name))
17096 name = make_conv_op_name (optype);
17098 /* See maybe_dependent_member_ref. */
17099 if ((complain & tf_dguide) && dependent_scope_p (qualifying_scope))
17101 if (template_id_p)
17102 name = build2 (TEMPLATE_ID_EXPR, unknown_type_node, name,
17103 template_args);
17104 return build_qualified_name (NULL_TREE, qualifying_scope, name,
17105 /* ::template */false);
17108 if (name == complete_dtor_identifier)
17109 /* Treat as-if non-dependent below. */
17110 dependent_p = false;
17112 bool maybe_incomplete = BASELINK_FUNCTIONS_MAYBE_INCOMPLETE_P (baselink);
17113 baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1,
17114 complain);
17115 if (maybe_incomplete)
17117 /* Filter out from the new lookup set those functions which didn't
17118 appear in the original lookup set (in a less specialized form).
17119 This is needed to preserve the consistency of member lookup
17120 performed in an incomplete-class context, within which
17121 later-declared members ought to remain invisible. */
17122 BASELINK_FUNCTIONS (baselink)
17123 = filter_memfn_lookup (fns, BASELINK_FUNCTIONS (baselink),
17124 binfo_type);
17125 BASELINK_FUNCTIONS_MAYBE_INCOMPLETE_P (baselink) = true;
17128 if (!baselink)
17130 if ((complain & tf_error)
17131 && constructor_name_p (name, qualifying_scope))
17132 error ("cannot call constructor %<%T::%D%> directly",
17133 qualifying_scope, name);
17134 return error_mark_node;
17137 fns = BASELINK_FUNCTIONS (baselink);
17139 else
17141 /* We're going to overwrite pieces below, make a duplicate. */
17142 baselink = copy_node (baselink);
17144 if (qualifying_scope != BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink)))
17146 /* The decl we found was from non-dependent scope, but we still need
17147 to update the binfos for the instantiated qualifying_scope. */
17148 BASELINK_ACCESS_BINFO (baselink) = TYPE_BINFO (qualifying_scope);
17149 BASELINK_BINFO (baselink) = lookup_base (qualifying_scope, binfo_type,
17150 ba_unique, nullptr, complain);
17154 /* If lookup found a single function, mark it as used at this point.
17155 (If lookup found multiple functions the one selected later by
17156 overload resolution will be marked as used at that point.) */
17157 if (!template_id_p && !really_overloaded_fn (fns))
17159 tree fn = OVL_FIRST (fns);
17160 bool ok = mark_used (fn, complain);
17161 if (!ok && !(complain & tf_error))
17162 return error_mark_node;
17163 if (ok && BASELINK_P (baselink))
17164 /* We might have instantiated an auto function. */
17165 TREE_TYPE (baselink) = TREE_TYPE (fn);
17168 if (BASELINK_P (baselink))
17170 /* Add back the template arguments, if present. */
17171 if (template_id_p)
17172 BASELINK_FUNCTIONS (baselink)
17173 = build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, template_args);
17175 /* Update the conversion operator type. */
17176 BASELINK_OPTYPE (baselink) = optype;
17179 if (!object_type)
17180 object_type = current_class_type;
17182 if (qualified_p || !dependent_p)
17184 baselink = adjust_result_of_qualified_name_lookup (baselink,
17185 qualifying_scope,
17186 object_type);
17187 if (!qualified_p)
17188 /* We need to call adjust_result_of_qualified_name_lookup in case the
17189 destructor names a base class, but we unset BASELINK_QUALIFIED_P
17190 so that we still get virtual function binding. */
17191 BASELINK_QUALIFIED_P (baselink) = false;
17194 return baselink;
17197 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID. DONE is
17198 true if the qualified-id will be a postfix-expression in-and-of
17199 itself; false if more of the postfix-expression follows the
17200 QUALIFIED_ID. ADDRESS_P is true if the qualified-id is the operand
17201 of "&". */
17203 static tree
17204 tsubst_qualified_id (tree qualified_id, tree args,
17205 tsubst_flags_t complain, tree in_decl,
17206 bool done, bool address_p)
17208 tree expr;
17209 tree scope;
17210 tree name;
17211 bool is_template;
17212 tree template_args;
17213 location_t loc = EXPR_LOCATION (qualified_id);
17215 gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
17217 /* Figure out what name to look up. */
17218 name = TREE_OPERAND (qualified_id, 1);
17219 if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
17221 is_template = true;
17222 template_args = TREE_OPERAND (name, 1);
17223 if (template_args)
17224 template_args = tsubst_template_args (template_args, args,
17225 complain, in_decl);
17226 if (template_args == error_mark_node)
17227 return error_mark_node;
17228 name = TREE_OPERAND (name, 0);
17230 else
17232 is_template = false;
17233 template_args = NULL_TREE;
17236 /* Substitute into the qualifying scope. When there are no ARGS, we
17237 are just trying to simplify a non-dependent expression. In that
17238 case the qualifying scope may be dependent, and, in any case,
17239 substituting will not help. */
17240 scope = TREE_OPERAND (qualified_id, 0);
17241 if (args)
17243 scope = tsubst_scope (scope, args, complain, in_decl);
17244 expr = tsubst_name (name, args, complain, in_decl);
17246 else
17247 expr = name;
17249 if (dependent_scope_p (scope))
17251 if (TREE_CODE (expr) == SCOPE_REF)
17252 /* We built one in tsubst_baselink. */
17253 gcc_checking_assert (same_type_p (scope, TREE_OPERAND (expr, 0)));
17254 else
17256 if (is_template)
17257 expr = build_min_nt_loc (loc, TEMPLATE_ID_EXPR, expr,
17258 template_args);
17259 expr = build_qualified_name (NULL_TREE, scope, expr,
17260 QUALIFIED_NAME_IS_TEMPLATE
17261 (qualified_id));
17263 REF_PARENTHESIZED_P (expr) = REF_PARENTHESIZED_P (qualified_id);
17264 return expr;
17267 if (!BASELINK_P (name) && !DECL_P (expr))
17269 if (TREE_CODE (expr) == BIT_NOT_EXPR)
17271 /* A BIT_NOT_EXPR is used to represent a destructor. */
17272 if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
17274 error ("qualifying type %qT does not match destructor name ~%qT",
17275 scope, TREE_OPERAND (expr, 0));
17276 expr = error_mark_node;
17278 else
17279 expr = lookup_qualified_name (scope, complete_dtor_identifier,
17280 LOOK_want::NORMAL, false);
17282 else
17283 expr = lookup_qualified_name (scope, expr, LOOK_want::NORMAL, false);
17284 if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
17285 ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
17287 if (complain & tf_error)
17289 error ("dependent-name %qE is parsed as a non-type, but "
17290 "instantiation yields a type", qualified_id);
17291 inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
17293 return error_mark_node;
17297 if (DECL_P (expr))
17299 if (!check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
17300 scope, complain))
17301 return error_mark_node;
17302 /* Remember that there was a reference to this entity. */
17303 if (!mark_used (expr, complain) && !(complain & tf_error))
17304 return error_mark_node;
17307 if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
17309 if (complain & tf_error)
17310 qualified_name_lookup_error (scope,
17311 TREE_OPERAND (qualified_id, 1),
17312 expr, input_location);
17313 return error_mark_node;
17316 if (is_template)
17318 /* We may be repeating a check already done during parsing, but
17319 if it was well-formed and passed then, it will pass again
17320 now, and if it didn't, we wouldn't have got here. The case
17321 we want to catch is when we couldn't tell then, and can now,
17322 namely when templ prior to substitution was an
17323 identifier. */
17324 if (flag_concepts && check_auto_in_tmpl_args (expr, template_args))
17325 return error_mark_node;
17327 if (variable_template_p (expr))
17328 expr = lookup_and_finish_template_variable (expr, template_args,
17329 complain);
17330 else
17331 expr = lookup_template_function (expr, template_args);
17334 if (expr == error_mark_node && complain & tf_error)
17335 qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
17336 expr, input_location);
17337 else if (TYPE_P (scope))
17339 expr = (adjust_result_of_qualified_name_lookup
17340 (expr, scope, current_nonlambda_class_type ()));
17341 expr = (finish_qualified_id_expr
17342 (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
17343 QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
17344 /*template_arg_p=*/false, complain));
17347 /* Expressions do not generally have reference type. */
17348 if (TREE_CODE (expr) != SCOPE_REF
17349 /* However, if we're about to form a pointer-to-member, we just
17350 want the referenced member referenced. */
17351 && TREE_CODE (expr) != OFFSET_REF)
17352 expr = convert_from_reference (expr);
17354 if (REF_PARENTHESIZED_P (qualified_id))
17355 expr = force_paren_expr (expr);
17357 expr = maybe_wrap_with_location (expr, loc);
17359 return expr;
17362 /* tsubst the initializer for a VAR_DECL. INIT is the unsubstituted
17363 initializer, DECL is the substituted VAR_DECL. Other arguments are as
17364 for tsubst. */
17366 static tree
17367 tsubst_init (tree init, tree decl, tree args,
17368 tsubst_flags_t complain, tree in_decl)
17370 if (!init)
17371 return NULL_TREE;
17373 init = tsubst_expr (init, args, complain, in_decl);
17375 tree type = TREE_TYPE (decl);
17377 if (!init && type != error_mark_node)
17379 if (tree auto_node = type_uses_auto (type))
17381 if (!CLASS_PLACEHOLDER_TEMPLATE (auto_node))
17383 if (complain & tf_error)
17384 error ("initializer for %q#D expands to an empty list "
17385 "of expressions", decl);
17386 return error_mark_node;
17389 else if (!dependent_type_p (type))
17391 /* If we had an initializer but it
17392 instantiated to nothing,
17393 value-initialize the object. This will
17394 only occur when the initializer was a
17395 pack expansion where the parameter packs
17396 used in that expansion were of length
17397 zero. */
17398 init = build_value_init (type, complain);
17399 if (TREE_CODE (init) == AGGR_INIT_EXPR)
17400 init = get_target_expr (init, complain);
17401 if (TREE_CODE (init) == TARGET_EXPR)
17402 TARGET_EXPR_DIRECT_INIT_P (init) = true;
17406 return init;
17409 /* If T is a reference to a dependent member of the current instantiation C and
17410 we are trying to refer to that member in a partial instantiation of C,
17411 return a SCOPE_REF; otherwise, return NULL_TREE.
17413 This can happen when forming a C++17 deduction guide, as in PR96199. */
17415 static tree
17416 maybe_dependent_member_ref (tree t, tree args, tsubst_flags_t complain,
17417 tree in_decl)
17419 if (!(complain & tf_dguide))
17420 return NULL_TREE;
17422 tree decl = (t && TYPE_P (t)) ? TYPE_NAME (t) : t;
17423 if (!decl || !DECL_P (decl))
17424 return NULL_TREE;
17426 tree ctx = context_for_name_lookup (decl);
17427 if (!CLASS_TYPE_P (ctx))
17428 return NULL_TREE;
17430 ctx = tsubst (ctx, args, complain, in_decl);
17431 if (!dependent_scope_p (ctx))
17432 return NULL_TREE;
17434 if (TYPE_P (t))
17436 if (typedef_variant_p (t))
17437 t = strip_typedefs (t);
17438 tree decl = TYPE_NAME (t);
17439 if (decl)
17440 decl = maybe_dependent_member_ref (decl, args, complain, in_decl);
17441 if (!decl)
17442 return NULL_TREE;
17443 return cp_build_qualified_type (TREE_TYPE (decl), cp_type_quals (t),
17444 complain);
17447 tree name = DECL_NAME (t);
17448 tree fullname = name;
17449 if (instantiates_primary_template_p (t))
17451 tree tinfo = get_template_info (t);
17452 name = DECL_NAME (TI_TEMPLATE (tinfo));
17453 tree targs = INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo));
17454 targs = tsubst_template_args (targs, args, complain, in_decl);
17455 fullname = build_nt (TEMPLATE_ID_EXPR, name, targs);
17458 if (TREE_CODE (t) == TYPE_DECL)
17460 if (TREE_CODE (TREE_TYPE (t)) == TYPENAME_TYPE
17461 && TYPE_NAME (TREE_TYPE (t)) == t)
17462 /* The TYPE_DECL for a typename has DECL_CONTEXT of the typename
17463 scope, but it doesn't need to be rewritten again. */
17464 return NULL_TREE;
17465 tree type = build_typename_type (ctx, name, fullname, typename_type);
17466 return TYPE_NAME (type);
17468 else if (DECL_TYPE_TEMPLATE_P (t))
17469 return make_unbound_class_template (ctx, name,
17470 NULL_TREE, complain);
17471 else
17472 return build_qualified_name (NULL_TREE, ctx, fullname,
17473 TREE_CODE (t) == TEMPLATE_DECL);
17476 /* Helper function for tsubst_omp_clauses, used for instantiation of
17477 OMP_CLAUSE_DECL of clauses. */
17479 static tree
17480 tsubst_omp_clause_decl (tree decl, tree args, tsubst_flags_t complain,
17481 tree in_decl, tree *iterator_cache)
17483 if (decl == NULL_TREE || decl == ridpointers[RID_OMP_ALL_MEMORY])
17484 return decl;
17486 /* Handle OpenMP iterators. */
17487 if (TREE_CODE (decl) == TREE_LIST
17488 && TREE_PURPOSE (decl)
17489 && TREE_CODE (TREE_PURPOSE (decl)) == TREE_VEC)
17491 tree ret;
17492 if (iterator_cache[0] == TREE_PURPOSE (decl))
17493 ret = iterator_cache[1];
17494 else
17496 tree *tp = &ret;
17497 begin_scope (sk_omp, NULL);
17498 for (tree it = TREE_PURPOSE (decl); it; it = TREE_CHAIN (it))
17500 *tp = copy_node (it);
17501 TREE_VEC_ELT (*tp, 0)
17502 = tsubst_decl (TREE_VEC_ELT (it, 0), args, complain);
17503 DECL_CONTEXT (TREE_VEC_ELT (*tp, 0)) = current_function_decl;
17504 pushdecl (TREE_VEC_ELT (*tp, 0));
17505 TREE_VEC_ELT (*tp, 1)
17506 = tsubst_stmt (TREE_VEC_ELT (it, 1), args, complain, in_decl);
17507 TREE_VEC_ELT (*tp, 2)
17508 = tsubst_stmt (TREE_VEC_ELT (it, 2), args, complain, in_decl);
17509 TREE_VEC_ELT (*tp, 3)
17510 = tsubst_stmt (TREE_VEC_ELT (it, 3), args, complain, in_decl);
17511 TREE_CHAIN (*tp) = NULL_TREE;
17512 tp = &TREE_CHAIN (*tp);
17514 TREE_VEC_ELT (ret, 5) = poplevel (1, 1, 0);
17515 iterator_cache[0] = TREE_PURPOSE (decl);
17516 iterator_cache[1] = ret;
17518 return build_tree_list (ret, tsubst_omp_clause_decl (TREE_VALUE (decl),
17519 args, complain,
17520 in_decl, NULL));
17523 /* Handle an OpenMP array section represented as a TREE_LIST (or
17524 OMP_CLAUSE_DOACROSS_KIND). An OMP_CLAUSE_DOACROSS (with a depend
17525 kind of OMP_CLAUSE_DOACROSS_SINK) can also be represented as a
17526 TREE_LIST. We can handle it exactly the same as an array section
17527 (purpose, value, and a chain), even though the nomenclature
17528 (low_bound, length, etc) is different. */
17529 if (TREE_CODE (decl) == TREE_LIST)
17531 tree low_bound
17532 = tsubst_stmt (TREE_PURPOSE (decl), args, complain, in_decl);
17533 tree length = tsubst_stmt (TREE_VALUE (decl), args, complain, in_decl);
17534 tree chain = tsubst_omp_clause_decl (TREE_CHAIN (decl), args, complain,
17535 in_decl, NULL);
17536 if (TREE_PURPOSE (decl) == low_bound
17537 && TREE_VALUE (decl) == length
17538 && TREE_CHAIN (decl) == chain)
17539 return decl;
17540 tree ret = tree_cons (low_bound, length, chain);
17541 OMP_CLAUSE_DOACROSS_SINK_NEGATIVE (ret)
17542 = OMP_CLAUSE_DOACROSS_SINK_NEGATIVE (decl);
17543 return ret;
17545 else if (TREE_CODE (decl) == OMP_ARRAY_SECTION)
17547 tree low_bound
17548 = tsubst_stmt (TREE_OPERAND (decl, 1), args, complain, in_decl);
17549 tree length = tsubst_stmt (TREE_OPERAND (decl, 2), args, complain,
17550 in_decl);
17551 tree base = tsubst_omp_clause_decl (TREE_OPERAND (decl, 0), args,
17552 complain, in_decl, NULL);
17553 if (TREE_OPERAND (decl, 0) == base
17554 && TREE_OPERAND (decl, 1) == low_bound
17555 && TREE_OPERAND (decl, 2) == length)
17556 return decl;
17557 return build3 (OMP_ARRAY_SECTION, TREE_TYPE (base), base, low_bound,
17558 length);
17560 tree ret = tsubst_stmt (decl, args, complain, in_decl);
17561 /* Undo convert_from_reference tsubst_expr could have called. */
17562 if (decl
17563 && REFERENCE_REF_P (ret)
17564 && !REFERENCE_REF_P (decl))
17565 ret = TREE_OPERAND (ret, 0);
17566 return ret;
17569 /* Like tsubst_copy, but specifically for OpenMP clauses. */
17571 static tree
17572 tsubst_omp_clauses (tree clauses, enum c_omp_region_type ort,
17573 tree args, tsubst_flags_t complain, tree in_decl)
17575 tree new_clauses = NULL_TREE, nc, oc;
17576 tree linear_no_step = NULL_TREE;
17577 tree iterator_cache[2] = { NULL_TREE, NULL_TREE };
17579 for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
17581 nc = copy_node (oc);
17582 OMP_CLAUSE_CHAIN (nc) = new_clauses;
17583 new_clauses = nc;
17585 switch (OMP_CLAUSE_CODE (nc))
17587 case OMP_CLAUSE_LASTPRIVATE:
17588 if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
17590 OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
17591 tsubst_stmt (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args,
17592 complain, in_decl);
17593 OMP_CLAUSE_LASTPRIVATE_STMT (nc)
17594 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
17596 /* FALLTHRU */
17597 case OMP_CLAUSE_PRIVATE:
17598 case OMP_CLAUSE_SHARED:
17599 case OMP_CLAUSE_FIRSTPRIVATE:
17600 case OMP_CLAUSE_COPYIN:
17601 case OMP_CLAUSE_COPYPRIVATE:
17602 case OMP_CLAUSE_UNIFORM:
17603 case OMP_CLAUSE_DEPEND:
17604 case OMP_CLAUSE_DOACROSS:
17605 case OMP_CLAUSE_AFFINITY:
17606 case OMP_CLAUSE_FROM:
17607 case OMP_CLAUSE_TO:
17608 case OMP_CLAUSE_MAP:
17609 case OMP_CLAUSE__CACHE_:
17610 case OMP_CLAUSE_NONTEMPORAL:
17611 case OMP_CLAUSE_USE_DEVICE_PTR:
17612 case OMP_CLAUSE_USE_DEVICE_ADDR:
17613 case OMP_CLAUSE_IS_DEVICE_PTR:
17614 case OMP_CLAUSE_HAS_DEVICE_ADDR:
17615 case OMP_CLAUSE_INCLUSIVE:
17616 case OMP_CLAUSE_EXCLUSIVE:
17617 OMP_CLAUSE_DECL (nc)
17618 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17619 in_decl, iterator_cache);
17620 break;
17621 case OMP_CLAUSE_NUM_TEAMS:
17622 if (OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (oc))
17623 OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (nc)
17624 = tsubst_stmt (OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (oc), args,
17625 complain, in_decl);
17626 /* FALLTHRU */
17627 case OMP_CLAUSE_TILE:
17628 case OMP_CLAUSE_IF:
17629 case OMP_CLAUSE_SELF:
17630 case OMP_CLAUSE_NUM_THREADS:
17631 case OMP_CLAUSE_SCHEDULE:
17632 case OMP_CLAUSE_COLLAPSE:
17633 case OMP_CLAUSE_FINAL:
17634 case OMP_CLAUSE_DEVICE:
17635 case OMP_CLAUSE_DIST_SCHEDULE:
17636 case OMP_CLAUSE_THREAD_LIMIT:
17637 case OMP_CLAUSE_SAFELEN:
17638 case OMP_CLAUSE_SIMDLEN:
17639 case OMP_CLAUSE_NUM_TASKS:
17640 case OMP_CLAUSE_GRAINSIZE:
17641 case OMP_CLAUSE_PRIORITY:
17642 case OMP_CLAUSE_ORDERED:
17643 case OMP_CLAUSE_HINT:
17644 case OMP_CLAUSE_FILTER:
17645 case OMP_CLAUSE_NUM_GANGS:
17646 case OMP_CLAUSE_NUM_WORKERS:
17647 case OMP_CLAUSE_VECTOR_LENGTH:
17648 case OMP_CLAUSE_WORKER:
17649 case OMP_CLAUSE_VECTOR:
17650 case OMP_CLAUSE_ASYNC:
17651 case OMP_CLAUSE_WAIT:
17652 case OMP_CLAUSE_DETACH:
17653 OMP_CLAUSE_OPERAND (nc, 0)
17654 = tsubst_stmt (OMP_CLAUSE_OPERAND (oc, 0), args, complain, in_decl);
17655 break;
17656 case OMP_CLAUSE_REDUCTION:
17657 case OMP_CLAUSE_IN_REDUCTION:
17658 case OMP_CLAUSE_TASK_REDUCTION:
17659 if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc))
17661 tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc);
17662 if (TREE_CODE (placeholder) == SCOPE_REF)
17664 tree scope = tsubst (TREE_OPERAND (placeholder, 0), args,
17665 complain, in_decl);
17666 OMP_CLAUSE_REDUCTION_PLACEHOLDER (nc)
17667 = build_qualified_name (NULL_TREE, scope,
17668 TREE_OPERAND (placeholder, 1),
17669 false);
17671 else
17672 gcc_assert (identifier_p (placeholder));
17674 OMP_CLAUSE_DECL (nc)
17675 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17676 in_decl, NULL);
17677 break;
17678 case OMP_CLAUSE_GANG:
17679 case OMP_CLAUSE_ALIGNED:
17680 OMP_CLAUSE_DECL (nc)
17681 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17682 in_decl, NULL);
17683 OMP_CLAUSE_OPERAND (nc, 1)
17684 = tsubst_stmt (OMP_CLAUSE_OPERAND (oc, 1), args, complain, in_decl);
17685 break;
17686 case OMP_CLAUSE_ALLOCATE:
17687 OMP_CLAUSE_DECL (nc)
17688 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17689 in_decl, NULL);
17690 OMP_CLAUSE_OPERAND (nc, 1)
17691 = tsubst_stmt (OMP_CLAUSE_OPERAND (oc, 1), args, complain, in_decl);
17692 OMP_CLAUSE_OPERAND (nc, 2)
17693 = tsubst_stmt (OMP_CLAUSE_OPERAND (oc, 2), args, complain, in_decl);
17694 break;
17695 case OMP_CLAUSE_LINEAR:
17696 OMP_CLAUSE_DECL (nc)
17697 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17698 in_decl, NULL);
17699 if (OMP_CLAUSE_LINEAR_STEP (oc) == NULL_TREE)
17701 gcc_assert (!linear_no_step);
17702 linear_no_step = nc;
17704 else if (OMP_CLAUSE_LINEAR_VARIABLE_STRIDE (oc))
17705 OMP_CLAUSE_LINEAR_STEP (nc)
17706 = tsubst_omp_clause_decl (OMP_CLAUSE_LINEAR_STEP (oc), args,
17707 complain, in_decl, NULL);
17708 else
17709 OMP_CLAUSE_LINEAR_STEP (nc)
17710 = tsubst_stmt (OMP_CLAUSE_LINEAR_STEP (oc), args,
17711 complain, in_decl);
17712 break;
17713 case OMP_CLAUSE_NOWAIT:
17714 case OMP_CLAUSE_DEFAULT:
17715 case OMP_CLAUSE_UNTIED:
17716 case OMP_CLAUSE_MERGEABLE:
17717 case OMP_CLAUSE_INBRANCH:
17718 case OMP_CLAUSE_NOTINBRANCH:
17719 case OMP_CLAUSE_PROC_BIND:
17720 case OMP_CLAUSE_FOR:
17721 case OMP_CLAUSE_PARALLEL:
17722 case OMP_CLAUSE_SECTIONS:
17723 case OMP_CLAUSE_TASKGROUP:
17724 case OMP_CLAUSE_NOGROUP:
17725 case OMP_CLAUSE_THREADS:
17726 case OMP_CLAUSE_SIMD:
17727 case OMP_CLAUSE_DEFAULTMAP:
17728 case OMP_CLAUSE_ORDER:
17729 case OMP_CLAUSE_BIND:
17730 case OMP_CLAUSE_INDEPENDENT:
17731 case OMP_CLAUSE_AUTO:
17732 case OMP_CLAUSE_SEQ:
17733 case OMP_CLAUSE_IF_PRESENT:
17734 case OMP_CLAUSE_FINALIZE:
17735 case OMP_CLAUSE_NOHOST:
17736 break;
17737 default:
17738 gcc_unreachable ();
17740 if ((ort & C_ORT_OMP_DECLARE_SIMD) == C_ORT_OMP)
17741 switch (OMP_CLAUSE_CODE (nc))
17743 case OMP_CLAUSE_SHARED:
17744 case OMP_CLAUSE_PRIVATE:
17745 case OMP_CLAUSE_FIRSTPRIVATE:
17746 case OMP_CLAUSE_LASTPRIVATE:
17747 case OMP_CLAUSE_COPYPRIVATE:
17748 case OMP_CLAUSE_LINEAR:
17749 case OMP_CLAUSE_REDUCTION:
17750 case OMP_CLAUSE_IN_REDUCTION:
17751 case OMP_CLAUSE_TASK_REDUCTION:
17752 case OMP_CLAUSE_USE_DEVICE_PTR:
17753 case OMP_CLAUSE_USE_DEVICE_ADDR:
17754 case OMP_CLAUSE_IS_DEVICE_PTR:
17755 case OMP_CLAUSE_HAS_DEVICE_ADDR:
17756 case OMP_CLAUSE_INCLUSIVE:
17757 case OMP_CLAUSE_EXCLUSIVE:
17758 case OMP_CLAUSE_ALLOCATE:
17759 /* tsubst_expr on SCOPE_REF results in returning
17760 finish_non_static_data_member result. Undo that here. */
17761 if (TREE_CODE (OMP_CLAUSE_DECL (oc)) == SCOPE_REF
17762 && (TREE_CODE (TREE_OPERAND (OMP_CLAUSE_DECL (oc), 1))
17763 == IDENTIFIER_NODE))
17765 tree t = OMP_CLAUSE_DECL (nc);
17766 tree v = t;
17767 while (v)
17768 switch (TREE_CODE (v))
17770 case COMPONENT_REF:
17771 case MEM_REF:
17772 case INDIRECT_REF:
17773 CASE_CONVERT:
17774 case POINTER_PLUS_EXPR:
17775 v = TREE_OPERAND (v, 0);
17776 continue;
17777 case PARM_DECL:
17778 if (DECL_CONTEXT (v) == current_function_decl
17779 && DECL_ARTIFICIAL (v)
17780 && DECL_NAME (v) == this_identifier)
17781 OMP_CLAUSE_DECL (nc) = TREE_OPERAND (t, 1);
17782 /* FALLTHRU */
17783 default:
17784 v = NULL_TREE;
17785 break;
17788 else if (VAR_P (OMP_CLAUSE_DECL (oc))
17789 && DECL_HAS_VALUE_EXPR_P (OMP_CLAUSE_DECL (oc))
17790 && DECL_ARTIFICIAL (OMP_CLAUSE_DECL (oc))
17791 && DECL_LANG_SPECIFIC (OMP_CLAUSE_DECL (oc))
17792 && DECL_OMP_PRIVATIZED_MEMBER (OMP_CLAUSE_DECL (oc)))
17794 tree decl = OMP_CLAUSE_DECL (nc);
17795 if (VAR_P (decl))
17797 retrofit_lang_decl (decl);
17798 DECL_OMP_PRIVATIZED_MEMBER (decl) = 1;
17801 break;
17802 default:
17803 break;
17807 new_clauses = nreverse (new_clauses);
17808 if (ort != C_ORT_OMP_DECLARE_SIMD)
17810 new_clauses = finish_omp_clauses (new_clauses, ort);
17811 if (linear_no_step)
17812 for (nc = new_clauses; nc; nc = OMP_CLAUSE_CHAIN (nc))
17813 if (nc == linear_no_step)
17815 OMP_CLAUSE_LINEAR_STEP (nc) = NULL_TREE;
17816 break;
17819 return new_clauses;
17822 /* Like tsubst_expr, but unshare TREE_LIST nodes. */
17824 static tree
17825 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
17826 tree in_decl)
17828 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
17830 tree purpose, value, chain;
17832 if (t == NULL)
17833 return t;
17835 if (TREE_CODE (t) != TREE_LIST)
17836 return tsubst_expr (t, args, complain, in_decl);
17838 if (t == void_list_node)
17839 return t;
17841 purpose = TREE_PURPOSE (t);
17842 if (purpose)
17843 purpose = RECUR (purpose);
17844 value = TREE_VALUE (t);
17845 if (value)
17847 if (TREE_CODE (value) != LABEL_DECL)
17848 value = RECUR (value);
17849 else
17851 value = lookup_label (DECL_NAME (value));
17852 gcc_assert (TREE_CODE (value) == LABEL_DECL);
17853 TREE_USED (value) = 1;
17856 chain = TREE_CHAIN (t);
17857 if (chain && chain != void_type_node)
17858 chain = RECUR (chain);
17859 return tree_cons (purpose, value, chain);
17860 #undef RECUR
17863 /* Used to temporarily communicate the list of #pragma omp parallel
17864 clauses to #pragma omp for instantiation if they are combined
17865 together. */
17867 static tree *omp_parallel_combined_clauses;
17869 static tree tsubst_decomp_names (tree, tree, tree, tsubst_flags_t, tree,
17870 cp_decomp *);
17872 /* Substitute one OMP_FOR iterator. */
17874 static bool
17875 tsubst_omp_for_iterator (tree t, int i, tree declv, tree &orig_declv,
17876 tree initv, tree condv, tree incrv, tree *clauses,
17877 tree args, tsubst_flags_t complain, tree in_decl)
17879 #define RECUR(NODE) \
17880 tsubst_stmt ((NODE), args, complain, in_decl)
17881 tree decl, init, cond = NULL_TREE, incr = NULL_TREE;
17882 bool ret = false;
17884 init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
17885 gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
17887 decl = TREE_OPERAND (init, 0);
17888 init = TREE_OPERAND (init, 1);
17889 tree decl_expr = NULL_TREE;
17890 bool range_for = TREE_VEC_ELT (OMP_FOR_COND (t), i) == global_namespace;
17891 if (range_for)
17893 bool decomp = false;
17894 if (decl != error_mark_node && DECL_HAS_VALUE_EXPR_P (decl))
17896 tree v = DECL_VALUE_EXPR (decl);
17897 if (TREE_CODE (v) == ARRAY_REF
17898 && VAR_P (TREE_OPERAND (v, 0))
17899 && DECL_DECOMPOSITION_P (TREE_OPERAND (v, 0)))
17901 cp_decomp decomp_d = { NULL_TREE, 0 };
17902 tree d = tsubst_decl (TREE_OPERAND (v, 0), args, complain);
17903 maybe_push_decl (d);
17904 d = tsubst_decomp_names (d, TREE_OPERAND (v, 0), args, complain,
17905 in_decl, &decomp_d);
17906 decomp = true;
17907 if (d == error_mark_node)
17908 decl = error_mark_node;
17909 else
17910 for (unsigned int i = 0; i < decomp_d.count; i++)
17912 if (!DECL_HAS_VALUE_EXPR_P (decomp_d.decl))
17914 tree v = build_nt (ARRAY_REF, d,
17915 size_int (decomp_d.count - i - 1),
17916 NULL_TREE, NULL_TREE);
17917 SET_DECL_VALUE_EXPR (decomp_d.decl, v);
17918 DECL_HAS_VALUE_EXPR_P (decomp_d.decl) = 1;
17920 fit_decomposition_lang_decl (decomp_d.decl, d);
17921 decomp_d.decl = DECL_CHAIN (decomp_d.decl);
17925 decl = tsubst_decl (decl, args, complain);
17926 if (!decomp)
17927 maybe_push_decl (decl);
17929 else if (init && TREE_CODE (init) == DECL_EXPR)
17931 /* We need to jump through some hoops to handle declarations in the
17932 init-statement, since we might need to handle auto deduction,
17933 but we need to keep control of initialization. */
17934 decl_expr = init;
17935 init = DECL_INITIAL (DECL_EXPR_DECL (init));
17936 decl = tsubst_decl (decl, args, complain);
17938 else
17940 if (TREE_CODE (decl) == SCOPE_REF)
17942 decl = RECUR (decl);
17943 if (TREE_CODE (decl) == COMPONENT_REF)
17945 tree v = decl;
17946 while (v)
17947 switch (TREE_CODE (v))
17949 case COMPONENT_REF:
17950 case MEM_REF:
17951 case INDIRECT_REF:
17952 CASE_CONVERT:
17953 case POINTER_PLUS_EXPR:
17954 v = TREE_OPERAND (v, 0);
17955 continue;
17956 case PARM_DECL:
17957 if (DECL_CONTEXT (v) == current_function_decl
17958 && DECL_ARTIFICIAL (v)
17959 && DECL_NAME (v) == this_identifier)
17961 decl = TREE_OPERAND (decl, 1);
17962 decl = omp_privatize_field (decl, false);
17964 /* FALLTHRU */
17965 default:
17966 v = NULL_TREE;
17967 break;
17971 else
17972 decl = RECUR (decl);
17974 if (init && TREE_CODE (init) == TREE_VEC)
17976 init = copy_node (init);
17977 TREE_VEC_ELT (init, 0)
17978 = tsubst_decl (TREE_VEC_ELT (init, 0), args, complain);
17979 TREE_VEC_ELT (init, 1) = RECUR (TREE_VEC_ELT (init, 1));
17980 TREE_VEC_ELT (init, 2) = RECUR (TREE_VEC_ELT (init, 2));
17982 else
17983 init = RECUR (init);
17985 if (orig_declv && OMP_FOR_ORIG_DECLS (t))
17987 tree o = TREE_VEC_ELT (OMP_FOR_ORIG_DECLS (t), i);
17988 if (TREE_CODE (o) == TREE_LIST)
17989 TREE_VEC_ELT (orig_declv, i)
17990 = tree_cons (RECUR (TREE_PURPOSE (o)),
17991 RECUR (TREE_VALUE (o)),
17992 NULL_TREE);
17993 else
17994 TREE_VEC_ELT (orig_declv, i) = RECUR (o);
17997 if (range_for)
17999 tree this_pre_body = NULL_TREE;
18000 tree orig_init = NULL_TREE;
18001 tree orig_decl = NULL_TREE;
18002 tree init_sl = NULL_TREE;
18003 cp_convert_omp_range_for (this_pre_body, init_sl, decl, orig_decl, init,
18004 orig_init, cond, incr);
18005 if (orig_decl)
18007 if (orig_declv == NULL_TREE)
18008 orig_declv = copy_node (declv);
18009 TREE_VEC_ELT (orig_declv, i) = orig_decl;
18010 ret = true;
18012 else if (orig_declv)
18013 TREE_VEC_ELT (orig_declv, i) = decl;
18016 tree auto_node = type_uses_auto (TREE_TYPE (decl));
18017 if (!range_for && auto_node && init)
18018 TREE_TYPE (decl)
18019 = do_auto_deduction (TREE_TYPE (decl), init, auto_node, complain);
18021 gcc_assert (!type_dependent_expression_p (decl));
18023 if (!CLASS_TYPE_P (TREE_TYPE (decl)) || range_for)
18025 if (decl_expr)
18027 /* Declare the variable, but don't let that initialize it. */
18028 tree init_sav = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
18029 DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL_TREE;
18030 RECUR (decl_expr);
18031 DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init_sav;
18034 if (!range_for)
18036 cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
18037 if (COMPARISON_CLASS_P (cond)
18038 && TREE_CODE (TREE_OPERAND (cond, 1)) == TREE_VEC)
18040 tree lhs = RECUR (TREE_OPERAND (cond, 0));
18041 tree rhs = copy_node (TREE_OPERAND (cond, 1));
18042 TREE_VEC_ELT (rhs, 0)
18043 = tsubst_decl (TREE_VEC_ELT (rhs, 0), args, complain);
18044 TREE_VEC_ELT (rhs, 1) = RECUR (TREE_VEC_ELT (rhs, 1));
18045 TREE_VEC_ELT (rhs, 2) = RECUR (TREE_VEC_ELT (rhs, 2));
18046 cond = build2 (TREE_CODE (cond), TREE_TYPE (cond),
18047 lhs, rhs);
18049 else
18050 cond = RECUR (cond);
18051 incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
18052 if (TREE_CODE (incr) == MODIFY_EXPR)
18054 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18055 tree rhs = RECUR (TREE_OPERAND (incr, 1));
18056 incr = build_x_modify_expr (EXPR_LOCATION (incr), lhs,
18057 NOP_EXPR, rhs, NULL_TREE, complain);
18059 else
18060 incr = RECUR (incr);
18061 if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
18062 TREE_VEC_ELT (orig_declv, i) = decl;
18064 TREE_VEC_ELT (declv, i) = decl;
18065 TREE_VEC_ELT (initv, i) = init;
18066 TREE_VEC_ELT (condv, i) = cond;
18067 TREE_VEC_ELT (incrv, i) = incr;
18068 return ret;
18071 if (decl_expr)
18073 /* Declare and initialize the variable. */
18074 RECUR (decl_expr);
18075 init = NULL_TREE;
18077 else if (init)
18079 tree *pc;
18080 int j;
18081 for (j = ((omp_parallel_combined_clauses == NULL
18082 || TREE_CODE (t) == OMP_LOOP) ? 1 : 0); j < 2; j++)
18084 for (pc = j ? clauses : omp_parallel_combined_clauses; *pc; )
18086 if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_PRIVATE
18087 && OMP_CLAUSE_DECL (*pc) == decl)
18088 break;
18089 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_LASTPRIVATE
18090 && OMP_CLAUSE_DECL (*pc) == decl)
18092 if (j)
18093 break;
18094 /* Move lastprivate (decl) clause to OMP_FOR_CLAUSES. */
18095 tree c = *pc;
18096 *pc = OMP_CLAUSE_CHAIN (c);
18097 OMP_CLAUSE_CHAIN (c) = *clauses;
18098 *clauses = c;
18100 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_FIRSTPRIVATE
18101 && OMP_CLAUSE_DECL (*pc) == decl)
18103 error ("iteration variable %qD should not be firstprivate",
18104 decl);
18105 *pc = OMP_CLAUSE_CHAIN (*pc);
18107 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_REDUCTION
18108 && OMP_CLAUSE_DECL (*pc) == decl)
18110 error ("iteration variable %qD should not be reduction",
18111 decl);
18112 *pc = OMP_CLAUSE_CHAIN (*pc);
18114 else
18115 pc = &OMP_CLAUSE_CHAIN (*pc);
18117 if (*pc)
18118 break;
18120 if (*pc == NULL_TREE)
18122 tree c = build_omp_clause (input_location,
18123 TREE_CODE (t) == OMP_LOOP
18124 ? OMP_CLAUSE_LASTPRIVATE
18125 : OMP_CLAUSE_PRIVATE);
18126 OMP_CLAUSE_DECL (c) = decl;
18127 c = finish_omp_clauses (c, C_ORT_OMP);
18128 if (c)
18130 OMP_CLAUSE_CHAIN (c) = *clauses;
18131 *clauses = c;
18135 cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
18136 if (COMPARISON_CLASS_P (cond))
18138 tree op0 = RECUR (TREE_OPERAND (cond, 0));
18139 tree op1 = RECUR (TREE_OPERAND (cond, 1));
18140 cond = build2 (TREE_CODE (cond), boolean_type_node, op0, op1);
18142 else
18143 cond = RECUR (cond);
18144 incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
18145 switch (TREE_CODE (incr))
18147 case PREINCREMENT_EXPR:
18148 case PREDECREMENT_EXPR:
18149 case POSTINCREMENT_EXPR:
18150 case POSTDECREMENT_EXPR:
18151 incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
18152 RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
18153 break;
18154 case MODIFY_EXPR:
18155 if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
18156 || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
18158 tree rhs = TREE_OPERAND (incr, 1);
18159 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18160 tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
18161 tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
18162 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18163 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
18164 rhs0, rhs1));
18166 else
18167 incr = RECUR (incr);
18168 break;
18169 case MODOP_EXPR:
18170 if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
18171 || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
18173 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18174 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18175 build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
18176 TREE_TYPE (decl), lhs,
18177 RECUR (TREE_OPERAND (incr, 2))));
18179 else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
18180 && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
18181 || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
18183 tree rhs = TREE_OPERAND (incr, 2);
18184 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18185 tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
18186 tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
18187 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18188 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
18189 rhs0, rhs1));
18191 else
18192 incr = RECUR (incr);
18193 break;
18194 default:
18195 incr = RECUR (incr);
18196 break;
18199 if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
18200 TREE_VEC_ELT (orig_declv, i) = decl;
18201 TREE_VEC_ELT (declv, i) = decl;
18202 TREE_VEC_ELT (initv, i) = init;
18203 TREE_VEC_ELT (condv, i) = cond;
18204 TREE_VEC_ELT (incrv, i) = incr;
18205 return false;
18206 #undef RECUR
18209 /* Helper function of tsubst_expr, find OMP_TEAMS inside
18210 of OMP_TARGET's body. */
18212 static tree
18213 tsubst_find_omp_teams (tree *tp, int *walk_subtrees, void *)
18215 *walk_subtrees = 0;
18216 switch (TREE_CODE (*tp))
18218 case OMP_TEAMS:
18219 return *tp;
18220 case BIND_EXPR:
18221 case STATEMENT_LIST:
18222 *walk_subtrees = 1;
18223 break;
18224 default:
18225 break;
18227 return NULL_TREE;
18230 /* Helper function for tsubst_expr. For decomposition declaration
18231 artificial base DECL, which is tsubsted PATTERN_DECL, tsubst
18232 also the corresponding decls representing the identifiers
18233 of the decomposition declaration. Return DECL if successful
18234 or error_mark_node otherwise, set *FIRST to the first decl
18235 in the list chained through DECL_CHAIN and *CNT to the number
18236 of such decls. */
18238 static tree
18239 tsubst_decomp_names (tree decl, tree pattern_decl, tree args,
18240 tsubst_flags_t complain, tree in_decl, cp_decomp *decomp)
18242 tree decl2, decl3, prev = decl;
18243 decomp->count = 0;
18244 gcc_assert (DECL_NAME (decl) == NULL_TREE);
18245 for (decl2 = DECL_CHAIN (pattern_decl);
18246 decl2
18247 && VAR_P (decl2)
18248 && DECL_DECOMPOSITION_P (decl2)
18249 && DECL_NAME (decl2);
18250 decl2 = DECL_CHAIN (decl2))
18252 if (TREE_TYPE (decl2) == error_mark_node && decomp->count == 0)
18254 gcc_assert (errorcount);
18255 return error_mark_node;
18257 decomp->count++;
18258 gcc_assert (DECL_DECOMP_BASE (decl2) == pattern_decl);
18259 gcc_assert (DECL_HAS_VALUE_EXPR_P (decl2));
18260 tree v = DECL_VALUE_EXPR (decl2);
18261 DECL_HAS_VALUE_EXPR_P (decl2) = 0;
18262 SET_DECL_VALUE_EXPR (decl2, NULL_TREE);
18263 decl3 = tsubst (decl2, args, complain, in_decl);
18264 SET_DECL_VALUE_EXPR (decl2, v);
18265 DECL_HAS_VALUE_EXPR_P (decl2) = 1;
18266 if (VAR_P (decl3))
18267 DECL_TEMPLATE_INSTANTIATED (decl3) = 1;
18268 else
18270 gcc_assert (errorcount);
18271 decl = error_mark_node;
18272 continue;
18274 maybe_push_decl (decl3);
18275 if (error_operand_p (decl3))
18276 decl = error_mark_node;
18277 else if (decl != error_mark_node
18278 && DECL_CHAIN (decl3) != prev
18279 && decl != prev)
18281 gcc_assert (errorcount);
18282 decl = error_mark_node;
18284 else
18285 prev = decl3;
18287 decomp->decl = prev;
18288 return decl;
18291 /* Return the proper local_specialization for init-capture pack DECL. */
18293 static tree
18294 lookup_init_capture_pack (tree decl)
18296 /* We handle normal pack captures by forwarding to the specialization of the
18297 captured parameter. We can't do that for pack init-captures; we need them
18298 to have their own local_specialization. We created the individual
18299 VAR_DECLs (if any) under build_capture_proxy, and we need to collect them
18300 when we process the DECL_EXPR for the pack init-capture in the template.
18301 So, how do we find them? We don't know the capture proxy pack when
18302 building the individual resulting proxies, and we don't know the
18303 individual proxies when instantiating the pack. What we have in common is
18304 the FIELD_DECL.
18306 So...when we instantiate the FIELD_DECL, we stick the result in
18307 local_specializations. Then at the DECL_EXPR we look up that result, see
18308 how many elements it has, synthesize the names, and look them up. */
18310 tree cname = DECL_NAME (decl);
18311 tree val = DECL_VALUE_EXPR (decl);
18312 tree field = TREE_OPERAND (val, 1);
18313 gcc_assert (TREE_CODE (field) == FIELD_DECL);
18314 tree fpack = retrieve_local_specialization (field);
18315 if (fpack == error_mark_node)
18316 return error_mark_node;
18318 int len = 1;
18319 tree vec = NULL_TREE;
18320 tree r = NULL_TREE;
18321 if (TREE_CODE (fpack) == TREE_VEC)
18323 len = TREE_VEC_LENGTH (fpack);
18324 vec = make_tree_vec (len);
18325 r = make_node (NONTYPE_ARGUMENT_PACK);
18326 ARGUMENT_PACK_ARGS (r) = vec;
18328 for (int i = 0; i < len; ++i)
18330 tree ename = vec ? make_ith_pack_parameter_name (cname, i) : cname;
18331 tree elt = lookup_name (ename);
18332 if (vec)
18333 TREE_VEC_ELT (vec, i) = elt;
18334 else
18335 r = elt;
18337 return r;
18340 /* T is an operand of a template tree being substituted. Return whether
18341 T is dependent such that we should suppress some warnings that would
18342 make sense if the substituted expression were written directly, like
18343 template <int I> bool f() { return I == 2; }
18344 We don't want to warn when instantiating f that comparing two constants
18345 always has the same value.
18347 This is a more limited concept of dependence than instantiation-dependent;
18348 here we don't care whether substitution could fail. */
18350 static bool
18351 dependent_operand_p (tree t)
18353 while (TREE_CODE (t) == IMPLICIT_CONV_EXPR)
18354 t = TREE_OPERAND (t, 0);
18355 ++processing_template_decl;
18356 bool r = (potential_constant_expression (t)
18357 ? value_dependent_expression_p (t)
18358 : type_dependent_expression_p (t));
18359 --processing_template_decl;
18360 return r;
18363 /* A superset of tsubst_expr that also handles statement trees. */
18365 static tree
18366 tsubst_stmt (tree t, tree args, tsubst_flags_t complain, tree in_decl)
18368 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
18369 #define RECUR(NODE) \
18370 tsubst_stmt ((NODE), args, complain, in_decl)
18372 tree stmt, tmp;
18373 tree r;
18374 location_t loc;
18376 if (t == NULL_TREE || t == error_mark_node)
18377 return t;
18379 loc = input_location;
18380 if (location_t eloc = cp_expr_location (t))
18381 input_location = eloc;
18382 if (STATEMENT_CODE_P (TREE_CODE (t)))
18383 current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
18385 switch (TREE_CODE (t))
18387 case STATEMENT_LIST:
18389 for (tree stmt : tsi_range (t))
18390 RECUR (stmt);
18391 break;
18394 case CTOR_INITIALIZER:
18395 finish_mem_initializers (tsubst_initializer_list
18396 (TREE_OPERAND (t, 0), args));
18397 break;
18399 case RETURN_EXPR:
18400 finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
18401 break;
18403 case CO_RETURN_EXPR:
18404 finish_co_return_stmt (input_location, RECUR (TREE_OPERAND (t, 0)));
18405 break;
18407 case EXPR_STMT:
18408 tmp = RECUR (EXPR_STMT_EXPR (t));
18409 if (EXPR_STMT_STMT_EXPR_RESULT (t))
18410 finish_stmt_expr_expr (tmp, cur_stmt_expr);
18411 else
18412 finish_expr_stmt (tmp);
18413 break;
18415 case USING_STMT:
18416 finish_using_directive (USING_STMT_NAMESPACE (t), /*attribs=*/NULL_TREE);
18417 break;
18419 case PRECONDITION_STMT:
18420 case POSTCONDITION_STMT:
18421 gcc_unreachable ();
18423 case ASSERTION_STMT:
18425 r = tsubst_contract (NULL_TREE, t, args, complain, in_decl);
18426 if (r != error_mark_node)
18427 add_stmt (r);
18428 RETURN (r);
18430 break;
18432 case DECL_EXPR:
18434 tree decl, pattern_decl;
18435 tree init;
18437 pattern_decl = decl = DECL_EXPR_DECL (t);
18438 if (TREE_CODE (decl) == LABEL_DECL)
18439 finish_label_decl (DECL_NAME (decl));
18440 else if (TREE_CODE (decl) == USING_DECL)
18442 tree scope = USING_DECL_SCOPE (decl);
18443 if (DECL_DEPENDENT_P (decl))
18445 scope = tsubst (scope, args, complain, in_decl);
18446 if (!MAYBE_CLASS_TYPE_P (scope)
18447 && TREE_CODE (scope) != ENUMERAL_TYPE)
18449 if (complain & tf_error)
18450 error_at (DECL_SOURCE_LOCATION (decl), "%qT is not a "
18451 "class, namespace, or enumeration", scope);
18452 return error_mark_node;
18454 finish_nonmember_using_decl (scope, DECL_NAME (decl));
18456 else
18458 /* This is a non-dependent using-decl, and we'll have
18459 used the names it found during template parsing. We do
18460 not want to do the lookup again, because we might not
18461 find the things we found then. */
18462 gcc_checking_assert (scope == tsubst (scope, args,
18463 complain, in_decl));
18464 /* We still need to push the bindings so that we can look up
18465 this name later. */
18466 push_using_decl_bindings (DECL_NAME (decl),
18467 USING_DECL_DECLS (decl));
18470 else if (is_capture_proxy (decl)
18471 && !DECL_TEMPLATE_INSTANTIATION (current_function_decl))
18473 /* We're in tsubst_lambda_expr, we've already inserted a new
18474 capture proxy, so look it up and register it. */
18475 tree inst;
18476 if (!DECL_PACK_P (decl))
18478 inst = lookup_name (DECL_NAME (decl), LOOK_where::BLOCK,
18479 LOOK_want::HIDDEN_LAMBDA);
18480 gcc_assert (inst != decl && is_capture_proxy (inst));
18482 else if (is_normal_capture_proxy (decl))
18484 inst = (retrieve_local_specialization
18485 (DECL_CAPTURED_VARIABLE (decl)));
18486 gcc_assert (TREE_CODE (inst) == NONTYPE_ARGUMENT_PACK
18487 || DECL_PACK_P (inst));
18489 else
18490 inst = lookup_init_capture_pack (decl);
18492 register_local_specialization (inst, decl);
18493 break;
18495 else if (DECL_PRETTY_FUNCTION_P (decl))
18496 decl = make_fname_decl (DECL_SOURCE_LOCATION (decl),
18497 DECL_NAME (decl),
18498 true/*DECL_PRETTY_FUNCTION_P (decl)*/);
18499 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
18500 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
18501 /* Don't copy the old closure; we'll create a new one in
18502 tsubst_lambda_expr. */
18503 break;
18504 else
18506 init = DECL_INITIAL (decl);
18507 decl = tsubst (decl, args, complain, in_decl);
18508 if (decl != error_mark_node)
18510 /* By marking the declaration as instantiated, we avoid
18511 trying to instantiate it. Since instantiate_decl can't
18512 handle local variables, and since we've already done
18513 all that needs to be done, that's the right thing to
18514 do. */
18515 if (VAR_P (decl))
18516 DECL_TEMPLATE_INSTANTIATED (decl) = 1;
18517 if (VAR_P (decl) && !DECL_NAME (decl)
18518 && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
18519 /* Anonymous aggregates are a special case. */
18520 finish_anon_union (decl);
18521 else if (is_capture_proxy (DECL_EXPR_DECL (t)))
18523 DECL_CONTEXT (decl) = current_function_decl;
18524 if (DECL_NAME (decl) == this_identifier)
18526 tree lam = DECL_CONTEXT (current_function_decl);
18527 lam = CLASSTYPE_LAMBDA_EXPR (lam);
18528 LAMBDA_EXPR_THIS_CAPTURE (lam) = decl;
18530 insert_capture_proxy (decl);
18532 else if (DECL_IMPLICIT_TYPEDEF_P (t))
18533 /* We already did a pushtag. */;
18534 else if (VAR_OR_FUNCTION_DECL_P (decl)
18535 && DECL_LOCAL_DECL_P (decl))
18537 if (TREE_CODE (DECL_CONTEXT (decl)) == FUNCTION_DECL)
18538 DECL_CONTEXT (decl) = NULL_TREE;
18539 decl = pushdecl (decl);
18540 if (TREE_CODE (decl) == FUNCTION_DECL
18541 && DECL_OMP_DECLARE_REDUCTION_P (decl)
18542 && cp_check_omp_declare_reduction (decl))
18543 instantiate_body (pattern_decl, args, decl, true);
18545 else
18547 bool const_init = false;
18548 cp_decomp decomp_d, *decomp = NULL;
18549 tree ndecl = error_mark_node;
18550 tree asmspec_tree = NULL_TREE;
18551 maybe_push_decl (decl);
18553 if (VAR_P (decl)
18554 && DECL_LANG_SPECIFIC (decl)
18555 && DECL_OMP_PRIVATIZED_MEMBER (decl))
18556 break;
18558 if (VAR_P (decl)
18559 && DECL_DECOMPOSITION_P (decl)
18560 && TREE_TYPE (pattern_decl) != error_mark_node)
18562 decomp = &decomp_d;
18563 ndecl = tsubst_decomp_names (decl, pattern_decl, args,
18564 complain, in_decl, decomp);
18567 init = tsubst_init (init, decl, args, complain, in_decl);
18569 if (VAR_P (decl))
18570 const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
18571 (pattern_decl));
18573 /* In a non-template function, VLA type declarations are
18574 handled in grokdeclarator; for templates, handle them
18575 now. */
18576 predeclare_vla (decl);
18578 if (VAR_P (decl) && DECL_HARD_REGISTER (pattern_decl))
18580 tree id = DECL_ASSEMBLER_NAME (pattern_decl);
18581 const char *asmspec = IDENTIFIER_POINTER (id);
18582 gcc_assert (asmspec[0] == '*');
18583 asmspec_tree
18584 = build_string (IDENTIFIER_LENGTH (id) - 1,
18585 asmspec + 1);
18586 TREE_TYPE (asmspec_tree) = char_array_type_node;
18589 cp_finish_decl (decl, init, const_init, asmspec_tree, 0,
18590 decomp);
18592 if (ndecl != error_mark_node)
18593 cp_finish_decomp (ndecl, decomp);
18598 break;
18601 case FOR_STMT:
18602 stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
18603 RECUR (FOR_INIT_STMT (t));
18604 finish_init_stmt (stmt);
18605 tmp = RECUR (FOR_COND (t));
18606 finish_for_cond (tmp, stmt, false, 0, false);
18607 tmp = RECUR (FOR_EXPR (t));
18608 finish_for_expr (tmp, stmt);
18610 bool prev = note_iteration_stmt_body_start ();
18611 RECUR (FOR_BODY (t));
18612 note_iteration_stmt_body_end (prev);
18614 finish_for_stmt (stmt);
18615 break;
18617 case RANGE_FOR_STMT:
18619 /* Construct another range_for, if this is not a final
18620 substitution (for inside a generic lambda of a
18621 template). Otherwise convert to a regular for. */
18622 tree decl, expr;
18623 stmt = (processing_template_decl
18624 ? begin_range_for_stmt (NULL_TREE, NULL_TREE)
18625 : begin_for_stmt (NULL_TREE, NULL_TREE));
18626 RECUR (RANGE_FOR_INIT_STMT (t));
18627 decl = RANGE_FOR_DECL (t);
18628 decl = tsubst (decl, args, complain, in_decl);
18629 maybe_push_decl (decl);
18630 expr = RECUR (RANGE_FOR_EXPR (t));
18632 cp_decomp decomp_d, *decomp = NULL;
18633 if (VAR_P (decl) && DECL_DECOMPOSITION_P (decl))
18635 decomp = &decomp_d;
18636 decl = tsubst_decomp_names (decl, RANGE_FOR_DECL (t), args,
18637 complain, in_decl, decomp);
18640 tree unroll = RECUR (RANGE_FOR_UNROLL (t));
18641 if (unroll)
18642 unroll
18643 = cp_check_pragma_unroll (EXPR_LOCATION (RANGE_FOR_UNROLL (t)),
18644 unroll);
18645 if (processing_template_decl)
18647 RANGE_FOR_IVDEP (stmt) = RANGE_FOR_IVDEP (t);
18648 RANGE_FOR_UNROLL (stmt) = unroll;
18649 RANGE_FOR_NOVECTOR (stmt) = RANGE_FOR_NOVECTOR (t);
18650 finish_range_for_decl (stmt, decl, expr);
18651 if (decomp && decl != error_mark_node)
18652 cp_finish_decomp (decl, decomp);
18654 else
18655 stmt = cp_convert_range_for (stmt, decl, expr, decomp,
18656 RANGE_FOR_IVDEP (t), unroll,
18657 RANGE_FOR_NOVECTOR (t));
18659 bool prev = note_iteration_stmt_body_start ();
18660 RECUR (RANGE_FOR_BODY (t));
18661 note_iteration_stmt_body_end (prev);
18662 finish_for_stmt (stmt);
18664 break;
18666 case WHILE_STMT:
18667 stmt = begin_while_stmt ();
18668 tmp = RECUR (WHILE_COND (t));
18669 finish_while_stmt_cond (tmp, stmt, false, 0, false);
18671 bool prev = note_iteration_stmt_body_start ();
18672 RECUR (WHILE_BODY (t));
18673 note_iteration_stmt_body_end (prev);
18675 finish_while_stmt (stmt);
18676 break;
18678 case DO_STMT:
18679 stmt = begin_do_stmt ();
18681 bool prev = note_iteration_stmt_body_start ();
18682 RECUR (DO_BODY (t));
18683 note_iteration_stmt_body_end (prev);
18685 finish_do_body (stmt);
18686 tmp = RECUR (DO_COND (t));
18687 finish_do_stmt (tmp, stmt, false, 0, false);
18688 break;
18690 case IF_STMT:
18691 stmt = begin_if_stmt ();
18692 IF_STMT_CONSTEXPR_P (stmt) = IF_STMT_CONSTEXPR_P (t);
18693 IF_STMT_CONSTEVAL_P (stmt) = IF_STMT_CONSTEVAL_P (t);
18694 if (IF_STMT_CONSTEXPR_P (t))
18695 args = add_extra_args (IF_STMT_EXTRA_ARGS (t), args, complain, in_decl);
18697 tree cond = IF_COND (t);
18698 bool was_dep = dependent_operand_p (cond);
18699 cond = RECUR (cond);
18700 warning_sentinel s1(warn_address, was_dep);
18701 tmp = finish_if_stmt_cond (cond, stmt);
18703 if (IF_STMT_CONSTEXPR_P (t)
18704 && instantiation_dependent_expression_p (tmp))
18706 /* We're partially instantiating a generic lambda, but the condition
18707 of the constexpr if is still dependent. Don't substitute into the
18708 branches now, just remember the template arguments. */
18709 do_poplevel (IF_SCOPE (stmt));
18710 IF_COND (stmt) = IF_COND (t);
18711 THEN_CLAUSE (stmt) = THEN_CLAUSE (t);
18712 ELSE_CLAUSE (stmt) = ELSE_CLAUSE (t);
18713 IF_STMT_EXTRA_ARGS (stmt) = build_extra_args (t, args, complain);
18714 add_stmt (stmt);
18715 break;
18717 if (IF_STMT_CONSTEXPR_P (t) && integer_zerop (tmp))
18718 /* Don't instantiate the THEN_CLAUSE. */;
18719 else if (IF_STMT_CONSTEVAL_P (t))
18721 bool save_in_consteval_if_p = in_consteval_if_p;
18722 in_consteval_if_p = true;
18723 RECUR (THEN_CLAUSE (t));
18724 in_consteval_if_p = save_in_consteval_if_p;
18726 else
18728 tree folded = fold_non_dependent_expr (tmp, complain);
18729 bool inhibit = integer_zerop (folded);
18730 if (inhibit)
18731 ++c_inhibit_evaluation_warnings;
18732 RECUR (THEN_CLAUSE (t));
18733 if (inhibit)
18734 --c_inhibit_evaluation_warnings;
18736 finish_then_clause (stmt);
18738 if (IF_STMT_CONSTEXPR_P (t) && integer_nonzerop (tmp))
18739 /* Don't instantiate the ELSE_CLAUSE. */;
18740 else if (ELSE_CLAUSE (t))
18742 tree folded = fold_non_dependent_expr (tmp, complain);
18743 bool inhibit = integer_nonzerop (folded);
18744 begin_else_clause (stmt);
18745 if (inhibit)
18746 ++c_inhibit_evaluation_warnings;
18747 RECUR (ELSE_CLAUSE (t));
18748 if (inhibit)
18749 --c_inhibit_evaluation_warnings;
18750 finish_else_clause (stmt);
18753 finish_if_stmt (stmt);
18754 break;
18756 case BIND_EXPR:
18757 if (BIND_EXPR_BODY_BLOCK (t))
18758 stmt = begin_function_body ();
18759 else
18760 stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
18761 ? BCS_TRY_BLOCK : 0);
18763 RECUR (BIND_EXPR_BODY (t));
18765 if (BIND_EXPR_BODY_BLOCK (t))
18766 finish_function_body (stmt);
18767 else
18768 finish_compound_stmt (stmt);
18769 break;
18771 case BREAK_STMT:
18772 finish_break_stmt ();
18773 break;
18775 case CONTINUE_STMT:
18776 finish_continue_stmt ();
18777 break;
18779 case SWITCH_STMT:
18780 stmt = begin_switch_stmt ();
18781 tmp = RECUR (SWITCH_STMT_COND (t));
18782 finish_switch_cond (tmp, stmt);
18783 RECUR (SWITCH_STMT_BODY (t));
18784 finish_switch_stmt (stmt);
18785 break;
18787 case CASE_LABEL_EXPR:
18789 tree decl = CASE_LABEL (t);
18790 tree low = RECUR (CASE_LOW (t));
18791 tree high = RECUR (CASE_HIGH (t));
18792 tree l = finish_case_label (EXPR_LOCATION (t), low, high);
18793 if (l && TREE_CODE (l) == CASE_LABEL_EXPR)
18795 tree label = CASE_LABEL (l);
18796 FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
18797 if (DECL_ATTRIBUTES (decl) != NULL_TREE)
18798 cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
18801 break;
18803 case LABEL_EXPR:
18805 tree decl = LABEL_EXPR_LABEL (t);
18806 tree label;
18808 label = finish_label_stmt (DECL_NAME (decl));
18809 if (TREE_CODE (label) == LABEL_DECL)
18810 FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
18811 if (DECL_ATTRIBUTES (decl) != NULL_TREE)
18812 cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
18814 break;
18816 case GOTO_EXPR:
18817 tmp = GOTO_DESTINATION (t);
18818 if (TREE_CODE (tmp) != LABEL_DECL)
18819 /* Computed goto's must be tsubst'd into. On the other hand,
18820 non-computed gotos must not be; the identifier in question
18821 will have no binding. */
18822 tmp = RECUR (tmp);
18823 else
18824 tmp = DECL_NAME (tmp);
18825 finish_goto_stmt (tmp);
18826 break;
18828 case ASM_EXPR:
18830 tree string = RECUR (ASM_STRING (t));
18831 tree outputs = tsubst_copy_asm_operands (ASM_OUTPUTS (t), args,
18832 complain, in_decl);
18833 tree inputs = tsubst_copy_asm_operands (ASM_INPUTS (t), args,
18834 complain, in_decl);
18835 tree clobbers = tsubst_copy_asm_operands (ASM_CLOBBERS (t), args,
18836 complain, in_decl);
18837 tree labels = tsubst_copy_asm_operands (ASM_LABELS (t), args,
18838 complain, in_decl);
18839 tmp = finish_asm_stmt (EXPR_LOCATION (t), ASM_VOLATILE_P (t), string,
18840 outputs, inputs, clobbers, labels,
18841 ASM_INLINE_P (t));
18842 tree asm_expr = tmp;
18843 if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
18844 asm_expr = TREE_OPERAND (asm_expr, 0);
18845 ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
18847 break;
18849 case TRY_BLOCK:
18850 if (CLEANUP_P (t))
18852 stmt = begin_try_block ();
18853 RECUR (TRY_STMTS (t));
18854 finish_cleanup_try_block (stmt);
18855 finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
18857 else
18859 tree compound_stmt = NULL_TREE;
18861 if (FN_TRY_BLOCK_P (t))
18862 stmt = begin_function_try_block (&compound_stmt);
18863 else
18864 stmt = begin_try_block ();
18866 RECUR (TRY_STMTS (t));
18868 if (FN_TRY_BLOCK_P (t))
18869 finish_function_try_block (stmt);
18870 else
18871 finish_try_block (stmt);
18873 RECUR (TRY_HANDLERS (t));
18874 if (FN_TRY_BLOCK_P (t))
18875 finish_function_handler_sequence (stmt, compound_stmt);
18876 else
18877 finish_handler_sequence (stmt);
18879 break;
18881 case HANDLER:
18883 tree decl = HANDLER_PARMS (t);
18885 if (decl)
18887 decl = tsubst (decl, args, complain, in_decl);
18888 /* Prevent instantiate_decl from trying to instantiate
18889 this variable. We've already done all that needs to be
18890 done. */
18891 if (decl != error_mark_node)
18892 DECL_TEMPLATE_INSTANTIATED (decl) = 1;
18894 stmt = begin_handler ();
18895 finish_handler_parms (decl, stmt);
18896 RECUR (HANDLER_BODY (t));
18897 finish_handler (stmt);
18899 break;
18901 case TAG_DEFN:
18902 tmp = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
18903 if (dependent_type_p (tmp))
18904 /* This is a partial instantiation, try again when full. */
18905 add_stmt (build_min (TAG_DEFN, tmp));
18906 else if (CLASS_TYPE_P (tmp))
18908 /* Local classes are not independent templates; they are
18909 instantiated along with their containing function. And this
18910 way we don't have to deal with pushing out of one local class
18911 to instantiate a member of another local class. */
18912 /* Closures are handled by the LAMBDA_EXPR. */
18913 gcc_assert (!LAMBDA_TYPE_P (TREE_TYPE (t)));
18914 complete_type (tmp);
18915 tree save_ccp = current_class_ptr;
18916 tree save_ccr = current_class_ref;
18917 for (tree fld = TYPE_FIELDS (tmp); fld; fld = DECL_CHAIN (fld))
18918 if ((VAR_P (fld)
18919 || (TREE_CODE (fld) == FUNCTION_DECL
18920 && !DECL_ARTIFICIAL (fld)))
18921 && DECL_TEMPLATE_INSTANTIATION (fld))
18922 instantiate_decl (fld, /*defer_ok=*/false,
18923 /*expl_inst_class=*/false);
18924 else if (TREE_CODE (fld) == FIELD_DECL)
18925 maybe_instantiate_nsdmi_init (fld, tf_warning_or_error);
18926 current_class_ptr = save_ccp;
18927 current_class_ref = save_ccr;
18929 break;
18931 case STATIC_ASSERT:
18933 tree condition, message;
18935 ++c_inhibit_evaluation_warnings;
18936 condition = tsubst_expr (STATIC_ASSERT_CONDITION (t), args,
18937 complain, in_decl);
18938 message = tsubst_expr (STATIC_ASSERT_MESSAGE (t), args,
18939 complain, in_decl);
18940 if (TREE_CODE (STATIC_ASSERT_MESSAGE (t)) != STRING_CST
18941 && TREE_CODE (message) == STRING_CST)
18942 message = build1_loc (STATIC_ASSERT_SOURCE_LOCATION (t),
18943 PAREN_EXPR, TREE_TYPE (message), message);
18944 --c_inhibit_evaluation_warnings;
18946 finish_static_assert (condition, message,
18947 STATIC_ASSERT_SOURCE_LOCATION (t),
18948 /*member_p=*/false, /*show_expr_p=*/true);
18950 break;
18952 case OACC_KERNELS:
18953 case OACC_PARALLEL:
18954 case OACC_SERIAL:
18955 tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_ACC_TARGET, args,
18956 complain, in_decl);
18957 stmt = begin_omp_parallel ();
18958 RECUR (OMP_BODY (t));
18959 finish_omp_construct (TREE_CODE (t), stmt, tmp);
18960 break;
18962 case OMP_PARALLEL:
18963 r = push_omp_privatization_clauses (OMP_PARALLEL_COMBINED (t));
18964 tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t), C_ORT_OMP, args,
18965 complain, in_decl);
18966 if (OMP_PARALLEL_COMBINED (t))
18967 omp_parallel_combined_clauses = &tmp;
18968 stmt = begin_omp_parallel ();
18969 RECUR (OMP_PARALLEL_BODY (t));
18970 gcc_assert (omp_parallel_combined_clauses == NULL);
18971 OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
18972 = OMP_PARALLEL_COMBINED (t);
18973 pop_omp_privatization_clauses (r);
18974 break;
18976 case OMP_TASK:
18977 if (OMP_TASK_BODY (t) == NULL_TREE)
18979 tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
18980 complain, in_decl);
18981 t = copy_node (t);
18982 OMP_TASK_CLAUSES (t) = tmp;
18983 add_stmt (t);
18984 break;
18986 r = push_omp_privatization_clauses (false);
18987 tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
18988 complain, in_decl);
18989 stmt = begin_omp_task ();
18990 RECUR (OMP_TASK_BODY (t));
18991 finish_omp_task (tmp, stmt);
18992 pop_omp_privatization_clauses (r);
18993 break;
18995 case OMP_FOR:
18996 case OMP_LOOP:
18997 case OMP_SIMD:
18998 case OMP_DISTRIBUTE:
18999 case OMP_TASKLOOP:
19000 case OACC_LOOP:
19002 tree clauses, body, pre_body;
19003 tree declv = NULL_TREE, initv = NULL_TREE, condv = NULL_TREE;
19004 tree orig_declv = NULL_TREE;
19005 tree incrv = NULL_TREE;
19006 enum c_omp_region_type ort = C_ORT_OMP;
19007 bool any_range_for = false;
19008 int i;
19010 if (TREE_CODE (t) == OACC_LOOP)
19011 ort = C_ORT_ACC;
19013 r = push_omp_privatization_clauses (OMP_FOR_INIT (t) == NULL_TREE);
19014 clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t), ort, args, complain,
19015 in_decl);
19016 if (OMP_FOR_INIT (t) != NULL_TREE)
19018 declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19019 if (OMP_FOR_ORIG_DECLS (t))
19020 orig_declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19021 initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19022 condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19023 incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19026 keep_next_level (true);
19027 stmt = begin_omp_structured_block ();
19029 pre_body = push_stmt_list ();
19030 RECUR (OMP_FOR_PRE_BODY (t));
19031 pre_body = pop_stmt_list (pre_body);
19033 if (OMP_FOR_INIT (t) != NULL_TREE)
19034 for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
19035 any_range_for
19036 |= tsubst_omp_for_iterator (t, i, declv, orig_declv, initv,
19037 condv, incrv, &clauses, args,
19038 complain, in_decl);
19039 omp_parallel_combined_clauses = NULL;
19041 if (any_range_for)
19043 gcc_assert (orig_declv);
19044 body = begin_omp_structured_block ();
19045 for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
19046 if (TREE_VEC_ELT (orig_declv, i) != TREE_VEC_ELT (declv, i)
19047 && TREE_CODE (TREE_VEC_ELT (orig_declv, i)) == TREE_LIST
19048 && TREE_CHAIN (TREE_VEC_ELT (orig_declv, i)))
19049 cp_finish_omp_range_for (TREE_VEC_ELT (orig_declv, i),
19050 TREE_VEC_ELT (declv, i));
19052 else
19053 body = push_stmt_list ();
19054 RECUR (OMP_FOR_BODY (t));
19055 if (any_range_for)
19056 body = finish_omp_structured_block (body);
19057 else
19058 body = pop_stmt_list (body);
19060 if (OMP_FOR_INIT (t) != NULL_TREE)
19061 t = finish_omp_for (EXPR_LOCATION (t), TREE_CODE (t), declv,
19062 orig_declv, initv, condv, incrv, body, pre_body,
19063 NULL, clauses);
19064 else
19066 t = make_node (TREE_CODE (t));
19067 TREE_TYPE (t) = void_type_node;
19068 OMP_FOR_BODY (t) = body;
19069 OMP_FOR_PRE_BODY (t) = pre_body;
19070 OMP_FOR_CLAUSES (t) = clauses;
19071 SET_EXPR_LOCATION (t, EXPR_LOCATION (t));
19072 add_stmt (t);
19075 add_stmt (finish_omp_for_block (finish_omp_structured_block (stmt),
19076 t));
19077 pop_omp_privatization_clauses (r);
19079 break;
19081 case OMP_SECTIONS:
19082 case OMP_MASKED:
19083 omp_parallel_combined_clauses = NULL;
19084 /* FALLTHRU */
19085 case OMP_SINGLE:
19086 case OMP_SCOPE:
19087 case OMP_TEAMS:
19088 case OMP_CRITICAL:
19089 case OMP_TASKGROUP:
19090 case OMP_SCAN:
19091 r = push_omp_privatization_clauses (TREE_CODE (t) == OMP_TEAMS
19092 && OMP_TEAMS_COMBINED (t));
19093 tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_OMP, args, complain,
19094 in_decl);
19095 if (TREE_CODE (t) == OMP_TEAMS)
19097 keep_next_level (true);
19098 stmt = begin_omp_structured_block ();
19099 RECUR (OMP_BODY (t));
19100 stmt = finish_omp_structured_block (stmt);
19102 else
19104 stmt = push_stmt_list ();
19105 RECUR (OMP_BODY (t));
19106 stmt = pop_stmt_list (stmt);
19109 if (TREE_CODE (t) == OMP_CRITICAL
19110 && tmp != NULL_TREE
19111 && integer_nonzerop (OMP_CLAUSE_HINT_EXPR (tmp)))
19113 error_at (OMP_CLAUSE_LOCATION (tmp),
19114 "%<#pragma omp critical%> with %<hint%> clause requires "
19115 "a name, except when %<omp_sync_hint_none%> is used");
19116 RETURN (error_mark_node);
19118 t = copy_node (t);
19119 OMP_BODY (t) = stmt;
19120 OMP_CLAUSES (t) = tmp;
19121 add_stmt (t);
19122 pop_omp_privatization_clauses (r);
19123 break;
19125 case OMP_DEPOBJ:
19126 r = RECUR (OMP_DEPOBJ_DEPOBJ (t));
19127 if (OMP_DEPOBJ_CLAUSES (t) && OMP_DEPOBJ_CLAUSES (t) != error_mark_node)
19129 enum omp_clause_depend_kind kind = OMP_CLAUSE_DEPEND_INVALID;
19130 if (TREE_CODE (OMP_DEPOBJ_CLAUSES (t)) == OMP_CLAUSE)
19132 tmp = tsubst_omp_clauses (OMP_DEPOBJ_CLAUSES (t), C_ORT_OMP,
19133 args, complain, in_decl);
19134 if (tmp == NULL_TREE)
19135 tmp = error_mark_node;
19137 else
19139 kind = (enum omp_clause_depend_kind)
19140 tree_to_uhwi (OMP_DEPOBJ_CLAUSES (t));
19141 tmp = NULL_TREE;
19143 finish_omp_depobj (EXPR_LOCATION (t), r, kind, tmp);
19145 else
19146 finish_omp_depobj (EXPR_LOCATION (t), r,
19147 OMP_CLAUSE_DEPEND_INVALID,
19148 OMP_DEPOBJ_CLAUSES (t));
19149 break;
19151 case OACC_DATA:
19152 case OMP_TARGET_DATA:
19153 case OMP_TARGET:
19154 tmp = tsubst_omp_clauses (OMP_CLAUSES (t),
19155 TREE_CODE (t) == OACC_DATA
19156 ? C_ORT_ACC
19157 : TREE_CODE (t) == OMP_TARGET
19158 ? C_ORT_OMP_TARGET : C_ORT_OMP,
19159 args, complain, in_decl);
19160 keep_next_level (true);
19161 stmt = begin_omp_structured_block ();
19163 RECUR (OMP_BODY (t));
19164 stmt = finish_omp_structured_block (stmt);
19166 t = copy_node (t);
19167 OMP_BODY (t) = stmt;
19168 OMP_CLAUSES (t) = tmp;
19170 if (TREE_CODE (t) == OMP_TARGET)
19171 finish_omp_target_clauses (EXPR_LOCATION (t), OMP_BODY (t),
19172 &OMP_CLAUSES (t));
19174 if (TREE_CODE (t) == OMP_TARGET && OMP_TARGET_COMBINED (t))
19176 tree teams = cp_walk_tree (&stmt, tsubst_find_omp_teams, NULL, NULL);
19177 if (teams)
19178 /* For combined target teams, ensure the num_teams and
19179 thread_limit clause expressions are evaluated on the host,
19180 before entering the target construct. */
19181 for (tree c = OMP_TEAMS_CLAUSES (teams);
19182 c; c = OMP_CLAUSE_CHAIN (c))
19183 if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS
19184 || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_THREAD_LIMIT)
19185 for (int i = 0;
19186 i <= (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS); ++i)
19187 if (OMP_CLAUSE_OPERAND (c, i)
19188 && TREE_CODE (OMP_CLAUSE_OPERAND (c, i)) != INTEGER_CST)
19190 tree expr = OMP_CLAUSE_OPERAND (c, i);
19191 expr = force_target_expr (TREE_TYPE (expr), expr,
19192 tf_none);
19193 if (expr == error_mark_node)
19194 continue;
19195 tmp = TARGET_EXPR_SLOT (expr);
19196 add_stmt (expr);
19197 OMP_CLAUSE_OPERAND (c, i) = expr;
19198 tree tc = build_omp_clause (OMP_CLAUSE_LOCATION (c),
19199 OMP_CLAUSE_FIRSTPRIVATE);
19200 OMP_CLAUSE_DECL (tc) = tmp;
19201 OMP_CLAUSE_CHAIN (tc) = OMP_TARGET_CLAUSES (t);
19202 OMP_TARGET_CLAUSES (t) = tc;
19205 add_stmt (t);
19206 break;
19208 case OACC_DECLARE:
19209 t = copy_node (t);
19210 tmp = tsubst_omp_clauses (OACC_DECLARE_CLAUSES (t), C_ORT_ACC, args,
19211 complain, in_decl);
19212 OACC_DECLARE_CLAUSES (t) = tmp;
19213 add_stmt (t);
19214 break;
19216 case OMP_TARGET_UPDATE:
19217 case OMP_TARGET_ENTER_DATA:
19218 case OMP_TARGET_EXIT_DATA:
19219 tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_OMP, args,
19220 complain, in_decl);
19221 t = copy_node (t);
19222 OMP_STANDALONE_CLAUSES (t) = tmp;
19223 add_stmt (t);
19224 break;
19226 case OACC_CACHE:
19227 case OACC_ENTER_DATA:
19228 case OACC_EXIT_DATA:
19229 case OACC_UPDATE:
19230 tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_ACC, args,
19231 complain, in_decl);
19232 t = copy_node (t);
19233 OMP_STANDALONE_CLAUSES (t) = tmp;
19234 add_stmt (t);
19235 break;
19237 case OMP_ORDERED:
19238 tmp = tsubst_omp_clauses (OMP_ORDERED_CLAUSES (t), C_ORT_OMP, args,
19239 complain, in_decl);
19240 if (OMP_BODY (t))
19242 stmt = push_stmt_list ();
19243 RECUR (OMP_BODY (t));
19244 stmt = pop_stmt_list (stmt);
19246 else
19247 stmt = NULL_TREE;
19249 t = copy_node (t);
19250 OMP_BODY (t) = stmt;
19251 OMP_ORDERED_CLAUSES (t) = tmp;
19252 add_stmt (t);
19253 break;
19255 case OMP_MASTER:
19256 case OMP_STRUCTURED_BLOCK:
19257 omp_parallel_combined_clauses = NULL;
19258 /* FALLTHRU */
19259 case OMP_SECTION:
19260 stmt = push_stmt_list ();
19261 RECUR (OMP_BODY (t));
19262 stmt = pop_stmt_list (stmt);
19264 t = copy_node (t);
19265 OMP_BODY (t) = stmt;
19266 add_stmt (t);
19267 break;
19269 case OMP_ATOMIC:
19270 gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
19271 tmp = NULL_TREE;
19272 if (TREE_CODE (TREE_OPERAND (t, 0)) == OMP_CLAUSE)
19273 tmp = tsubst_omp_clauses (TREE_OPERAND (t, 0), C_ORT_OMP, args,
19274 complain, in_decl);
19275 if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
19277 tree op1 = TREE_OPERAND (t, 1);
19278 tree rhs1 = NULL_TREE;
19279 tree r = NULL_TREE;
19280 tree lhs, rhs;
19281 if (TREE_CODE (op1) == COMPOUND_EXPR)
19283 rhs1 = RECUR (TREE_OPERAND (op1, 0));
19284 op1 = TREE_OPERAND (op1, 1);
19286 if (TREE_CODE (op1) == COND_EXPR)
19288 gcc_assert (rhs1 == NULL_TREE);
19289 tree c = TREE_OPERAND (op1, 0);
19290 if (TREE_CODE (c) == MODIFY_EXPR)
19292 r = RECUR (TREE_OPERAND (c, 0));
19293 c = TREE_OPERAND (c, 1);
19295 gcc_assert (TREE_CODE (c) == EQ_EXPR);
19296 rhs = RECUR (TREE_OPERAND (c, 1));
19297 lhs = RECUR (TREE_OPERAND (op1, 2));
19298 rhs1 = RECUR (TREE_OPERAND (op1, 1));
19300 else
19302 lhs = RECUR (TREE_OPERAND (op1, 0));
19303 rhs = RECUR (TREE_OPERAND (op1, 1));
19305 finish_omp_atomic (EXPR_LOCATION (t), OMP_ATOMIC, TREE_CODE (op1),
19306 lhs, rhs, NULL_TREE, NULL_TREE, rhs1, r,
19307 tmp, OMP_ATOMIC_MEMORY_ORDER (t),
19308 OMP_ATOMIC_WEAK (t));
19310 else
19312 tree op1 = TREE_OPERAND (t, 1);
19313 tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
19314 tree rhs1 = NULL_TREE, r = NULL_TREE;
19315 enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
19316 enum tree_code opcode = NOP_EXPR;
19317 if (code == OMP_ATOMIC_READ)
19319 v = RECUR (TREE_OPERAND (op1, 0));
19320 lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
19322 else if (code == OMP_ATOMIC_CAPTURE_OLD
19323 || code == OMP_ATOMIC_CAPTURE_NEW)
19325 tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
19326 v = RECUR (TREE_OPERAND (op1, 0));
19327 lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
19328 if (TREE_CODE (op11) == COMPOUND_EXPR)
19330 rhs1 = RECUR (TREE_OPERAND (op11, 0));
19331 op11 = TREE_OPERAND (op11, 1);
19333 if (TREE_CODE (op11) == COND_EXPR)
19335 gcc_assert (rhs1 == NULL_TREE);
19336 tree c = TREE_OPERAND (op11, 0);
19337 if (TREE_CODE (c) == MODIFY_EXPR)
19339 r = RECUR (TREE_OPERAND (c, 0));
19340 c = TREE_OPERAND (c, 1);
19342 gcc_assert (TREE_CODE (c) == EQ_EXPR);
19343 rhs = RECUR (TREE_OPERAND (c, 1));
19344 lhs = RECUR (TREE_OPERAND (op11, 2));
19345 rhs1 = RECUR (TREE_OPERAND (op11, 1));
19347 else
19349 lhs = RECUR (TREE_OPERAND (op11, 0));
19350 rhs = RECUR (TREE_OPERAND (op11, 1));
19352 opcode = TREE_CODE (op11);
19353 if (opcode == MODIFY_EXPR)
19354 opcode = NOP_EXPR;
19356 else
19358 code = OMP_ATOMIC;
19359 lhs = RECUR (TREE_OPERAND (op1, 0));
19360 rhs = RECUR (TREE_OPERAND (op1, 1));
19362 finish_omp_atomic (EXPR_LOCATION (t), code, opcode, lhs, rhs, v,
19363 lhs1, rhs1, r, tmp,
19364 OMP_ATOMIC_MEMORY_ORDER (t), OMP_ATOMIC_WEAK (t));
19366 break;
19368 case TRANSACTION_EXPR:
19370 int flags = 0;
19371 flags |= (TRANSACTION_EXPR_OUTER (t) ? TM_STMT_ATTR_OUTER : 0);
19372 flags |= (TRANSACTION_EXPR_RELAXED (t) ? TM_STMT_ATTR_RELAXED : 0);
19374 if (TRANSACTION_EXPR_IS_STMT (t))
19376 tree body = TRANSACTION_EXPR_BODY (t);
19377 tree noex = NULL_TREE;
19378 if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
19380 noex = MUST_NOT_THROW_COND (body);
19381 if (noex == NULL_TREE)
19382 noex = boolean_true_node;
19383 body = TREE_OPERAND (body, 0);
19385 stmt = begin_transaction_stmt (input_location, NULL, flags);
19386 RECUR (body);
19387 finish_transaction_stmt (stmt, NULL, flags, RECUR (noex));
19389 else
19391 stmt = build_transaction_expr (EXPR_LOCATION (t),
19392 RECUR (TRANSACTION_EXPR_BODY (t)),
19393 flags, NULL_TREE);
19394 RETURN (stmt);
19397 break;
19399 case MUST_NOT_THROW_EXPR:
19401 tree op0 = RECUR (TREE_OPERAND (t, 0));
19402 tree cond = RECUR (MUST_NOT_THROW_COND (t));
19403 RETURN (build_must_not_throw_expr (op0, cond));
19406 case EXPR_PACK_EXPANSION:
19407 error ("invalid use of pack expansion expression");
19408 RETURN (error_mark_node);
19410 case NONTYPE_ARGUMENT_PACK:
19411 error ("use %<...%> to expand argument pack");
19412 RETURN (error_mark_node);
19414 case COMPOUND_EXPR:
19415 tmp = RECUR (TREE_OPERAND (t, 0));
19416 if (tmp == NULL_TREE)
19417 /* If the first operand was a statement, we're done with it. */
19418 RETURN (RECUR (TREE_OPERAND (t, 1)));
19419 RETURN (build_x_compound_expr (EXPR_LOCATION (t), tmp,
19420 RECUR (TREE_OPERAND (t, 1)),
19421 templated_operator_saved_lookups (t),
19422 complain));
19424 case PREDICT_EXPR:
19425 RETURN (add_stmt (copy_node (t)));
19427 default:
19428 gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
19430 RETURN (tsubst_expr (t, args, complain, in_decl));
19433 RETURN (NULL_TREE);
19434 out:
19435 input_location = loc;
19436 return r;
19437 #undef RECUR
19438 #undef RETURN
19441 /* Instantiate the special body of the artificial DECL_OMP_DECLARE_REDUCTION
19442 function. For description of the body see comment above
19443 cp_parser_omp_declare_reduction_exprs. */
19445 static void
19446 tsubst_omp_udr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
19448 if (t == NULL_TREE || t == error_mark_node)
19449 return;
19451 gcc_assert (TREE_CODE (t) == STATEMENT_LIST && current_function_decl);
19453 tree_stmt_iterator tsi;
19454 int i;
19455 tree stmts[7];
19456 memset (stmts, 0, sizeof stmts);
19457 for (i = 0, tsi = tsi_start (t);
19458 i < 7 && !tsi_end_p (tsi);
19459 i++, tsi_next (&tsi))
19460 stmts[i] = tsi_stmt (tsi);
19461 gcc_assert (tsi_end_p (tsi));
19463 if (i >= 3)
19465 gcc_assert (TREE_CODE (stmts[0]) == DECL_EXPR
19466 && TREE_CODE (stmts[1]) == DECL_EXPR);
19467 tree omp_out = tsubst (DECL_EXPR_DECL (stmts[0]),
19468 args, complain, in_decl);
19469 tree omp_in = tsubst (DECL_EXPR_DECL (stmts[1]),
19470 args, complain, in_decl);
19471 /* tsubsting a local var_decl leaves DECL_CONTEXT null, as we
19472 expect to be pushing it. */
19473 DECL_CONTEXT (omp_out) = current_function_decl;
19474 DECL_CONTEXT (omp_in) = current_function_decl;
19475 keep_next_level (true);
19476 tree block = begin_omp_structured_block ();
19477 tsubst_stmt (stmts[2], args, complain, in_decl);
19478 block = finish_omp_structured_block (block);
19479 block = maybe_cleanup_point_expr_void (block);
19480 add_decl_expr (omp_out);
19481 copy_warning (omp_out, DECL_EXPR_DECL (stmts[0]));
19482 add_decl_expr (omp_in);
19483 finish_expr_stmt (block);
19485 if (i >= 6)
19487 gcc_assert (TREE_CODE (stmts[3]) == DECL_EXPR
19488 && TREE_CODE (stmts[4]) == DECL_EXPR);
19489 tree omp_priv = tsubst (DECL_EXPR_DECL (stmts[3]),
19490 args, complain, in_decl);
19491 tree omp_orig = tsubst (DECL_EXPR_DECL (stmts[4]),
19492 args, complain, in_decl);
19493 DECL_CONTEXT (omp_priv) = current_function_decl;
19494 DECL_CONTEXT (omp_orig) = current_function_decl;
19495 keep_next_level (true);
19496 tree block = begin_omp_structured_block ();
19497 tsubst_stmt (stmts[5], args, complain, in_decl);
19498 block = finish_omp_structured_block (block);
19499 block = maybe_cleanup_point_expr_void (block);
19500 cp_walk_tree (&block, cp_remove_omp_priv_cleanup_stmt, omp_priv, NULL);
19501 add_decl_expr (omp_priv);
19502 add_decl_expr (omp_orig);
19503 finish_expr_stmt (block);
19504 if (i == 7)
19505 add_decl_expr (omp_orig);
19509 /* T is a postfix-expression that is not being used in a function
19510 call. Return the substituted version of T. */
19512 static tree
19513 tsubst_non_call_postfix_expression (tree t, tree args,
19514 tsubst_flags_t complain,
19515 tree in_decl)
19517 if (TREE_CODE (t) == SCOPE_REF)
19518 t = tsubst_qualified_id (t, args, complain, in_decl,
19519 /*done=*/false, /*address_p=*/false);
19520 else
19521 t = tsubst_expr (t, args, complain, in_decl);
19523 return t;
19526 /* Subroutine of tsubst_lambda_expr: add the FIELD/INIT capture pair to the
19527 LAMBDA_EXPR_CAPTURE_LIST passed in LIST. Do deduction for a previously
19528 dependent init-capture. EXPLICIT_P is true if the original list had
19529 explicit captures. */
19531 static void
19532 prepend_one_capture (tree field, tree init, tree &list, bool explicit_p,
19533 tsubst_flags_t complain)
19535 if (tree auto_node = type_uses_auto (TREE_TYPE (field)))
19537 tree type = NULL_TREE;
19538 if (!init)
19540 if (complain & tf_error)
19541 error ("empty initializer in lambda init-capture");
19542 init = error_mark_node;
19544 else if (TREE_CODE (init) == TREE_LIST)
19545 init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
19546 if (!type)
19547 type = do_auto_deduction (TREE_TYPE (field), init, auto_node, complain);
19548 TREE_TYPE (field) = type;
19549 cp_apply_type_quals_to_decl (cp_type_quals (type), field);
19551 list = tree_cons (field, init, list);
19552 LAMBDA_CAPTURE_EXPLICIT_P (list) = explicit_p;
19555 /* T is a LAMBDA_EXPR. Generate a new LAMBDA_EXPR for the current
19556 instantiation context. Instantiating a pack expansion containing a lambda
19557 might result in multiple lambdas all based on the same lambda in the
19558 template. */
19560 tree
19561 tsubst_lambda_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
19563 tree oldfn = lambda_function (t);
19564 in_decl = oldfn;
19566 tree r = build_lambda_expr ();
19568 LAMBDA_EXPR_LOCATION (r)
19569 = LAMBDA_EXPR_LOCATION (t);
19570 LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
19571 = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
19572 if (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
19573 LAMBDA_EXPR_REGEN_INFO (r)
19574 = build_template_info (t, add_to_template_args (TI_ARGS (ti),
19575 preserve_args (args)));
19576 else
19577 LAMBDA_EXPR_REGEN_INFO (r)
19578 = build_template_info (t, preserve_args (args));
19580 gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
19581 && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
19583 vec<tree,va_gc>* field_packs = NULL;
19584 unsigned name_independent_cnt = 0;
19585 for (tree cap = LAMBDA_EXPR_CAPTURE_LIST (t); cap;
19586 cap = TREE_CHAIN (cap))
19588 tree ofield = TREE_PURPOSE (cap);
19589 tree init = TREE_VALUE (cap);
19590 if (PACK_EXPANSION_P (init))
19591 init = tsubst_pack_expansion (init, args, complain, in_decl);
19592 else
19593 init = tsubst_expr (init, args, complain, in_decl);
19595 if (init == error_mark_node)
19596 return error_mark_node;
19598 if (init && TREE_CODE (init) == TREE_LIST)
19599 init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
19601 if (!processing_template_decl
19602 && init && TREE_CODE (init) != TREE_VEC
19603 && variably_modified_type_p (TREE_TYPE (init), NULL_TREE))
19605 /* For a VLA, simply tsubsting the field type won't work, we need to
19606 go through add_capture again. XXX do we want to do this for all
19607 captures? */
19608 tree name = (get_identifier
19609 (IDENTIFIER_POINTER (DECL_NAME (ofield)) + 2));
19610 tree ftype = TREE_TYPE (ofield);
19611 bool by_ref = (TYPE_REF_P (ftype)
19612 || (TREE_CODE (ftype) == DECLTYPE_TYPE
19613 && DECLTYPE_FOR_REF_CAPTURE (ftype)));
19614 add_capture (r, name, init, by_ref, !DECL_NORMAL_CAPTURE_P (ofield),
19615 &name_independent_cnt);
19616 continue;
19619 if (PACK_EXPANSION_P (ofield))
19620 ofield = PACK_EXPANSION_PATTERN (ofield);
19621 tree field = tsubst_decl (ofield, args, complain);
19623 if (DECL_PACK_P (ofield) && !DECL_NORMAL_CAPTURE_P (ofield))
19625 /* Remember these for when we've pushed local_specializations. */
19626 vec_safe_push (field_packs, ofield);
19627 vec_safe_push (field_packs, field);
19630 if (field == error_mark_node)
19631 return error_mark_node;
19633 if (TREE_CODE (field) == TREE_VEC)
19635 int len = TREE_VEC_LENGTH (field);
19636 gcc_assert (TREE_CODE (init) == TREE_VEC
19637 && TREE_VEC_LENGTH (init) == len);
19638 for (int i = 0; i < len; ++i)
19639 prepend_one_capture (TREE_VEC_ELT (field, i),
19640 TREE_VEC_ELT (init, i),
19641 LAMBDA_EXPR_CAPTURE_LIST (r),
19642 LAMBDA_CAPTURE_EXPLICIT_P (cap),
19643 complain);
19645 else
19647 prepend_one_capture (field, init, LAMBDA_EXPR_CAPTURE_LIST (r),
19648 LAMBDA_CAPTURE_EXPLICIT_P (cap), complain);
19650 if (id_equal (DECL_NAME (field), "__this"))
19651 LAMBDA_EXPR_THIS_CAPTURE (r) = field;
19655 tree type = begin_lambda_type (r);
19656 if (type == error_mark_node)
19657 return error_mark_node;
19659 if (LAMBDA_EXPR_EXTRA_SCOPE (t))
19660 record_lambda_scope (r);
19661 else if (TYPE_NAMESPACE_SCOPE_P (TREE_TYPE (t)))
19662 /* If we're pushed into another scope (PR105652), fix it. */
19663 TYPE_CONTEXT (type) = DECL_CONTEXT (TYPE_NAME (type))
19664 = TYPE_CONTEXT (TREE_TYPE (t));
19665 record_lambda_scope_discriminator (r);
19667 /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set. */
19668 determine_visibility (TYPE_NAME (type));
19670 register_capture_members (LAMBDA_EXPR_CAPTURE_LIST (r));
19672 tree oldtmpl = (generic_lambda_fn_p (oldfn)
19673 ? DECL_TI_TEMPLATE (oldfn)
19674 : NULL_TREE);
19676 tree tparms = NULL_TREE;
19677 if (oldtmpl)
19678 tparms = tsubst_template_parms (DECL_TEMPLATE_PARMS (oldtmpl), args, complain);
19680 tree fntype = static_fn_type (oldfn);
19682 tree saved_ctp = current_template_parms;
19683 if (oldtmpl)
19685 ++processing_template_decl;
19686 current_template_parms = tparms;
19688 fntype = tsubst (fntype, args, complain, in_decl);
19689 if (oldtmpl)
19691 current_template_parms = saved_ctp;
19692 --processing_template_decl;
19695 if (fntype == error_mark_node)
19696 r = error_mark_node;
19697 else
19699 /* The body of a lambda-expression is not a subexpression of the
19700 enclosing expression. Parms are to have DECL_CHAIN tsubsted,
19701 which would be skipped if cp_unevaluated_operand. */
19702 cp_evaluated ev;
19704 /* Fix the type of 'this'.
19705 For static and xobj member functions we use this to transport the
19706 lambda's closure type. It appears that in the regular case the
19707 object parameter is still pulled off, and then re-added again anyway.
19708 So perhaps we could do something better here? */
19709 fntype = build_memfn_type (fntype, type,
19710 type_memfn_quals (fntype),
19711 type_memfn_rqual (fntype));
19712 tree inst = (oldtmpl
19713 ? tsubst_template_decl (oldtmpl, args, complain,
19714 fntype, tparms)
19715 : tsubst_function_decl (oldfn, args, complain, fntype));
19716 if (inst == error_mark_node)
19718 r = error_mark_node;
19719 goto out;
19721 finish_member_declaration (inst);
19722 record_lambda_scope_sig_discriminator (r, inst);
19724 tree fn = oldtmpl ? DECL_TEMPLATE_RESULT (inst) : inst;
19726 /* Let finish_function set this. */
19727 DECL_DECLARED_CONSTEXPR_P (fn) = false;
19729 bool nested = cfun;
19730 if (nested)
19731 push_function_context ();
19732 else
19733 /* Still increment function_depth so that we don't GC in the
19734 middle of an expression. */
19735 ++function_depth;
19737 local_specialization_stack s (lss_copy);
19739 bool save_in_consteval_if_p = in_consteval_if_p;
19740 in_consteval_if_p = false;
19742 tree body = start_lambda_function (fn, r);
19744 /* Now record them for lookup_init_capture_pack. */
19745 int fplen = vec_safe_length (field_packs);
19746 for (int i = 0; i < fplen; )
19748 tree pack = (*field_packs)[i++];
19749 tree inst = (*field_packs)[i++];
19750 register_local_specialization (inst, pack);
19752 release_tree_vector (field_packs);
19754 register_parameter_specializations (oldfn, fn);
19756 if (oldtmpl)
19758 /* We might not partially instantiate some parts of the function, so
19759 copy these flags from the original template. */
19760 language_function *ol = DECL_STRUCT_FUNCTION (oldfn)->language;
19761 current_function_returns_value = ol->returns_value;
19762 current_function_returns_null = ol->returns_null;
19763 current_function_returns_abnormally = ol->returns_abnormally;
19764 current_function_infinite_loop = ol->infinite_loop;
19767 /* [temp.deduct] A lambda-expression appearing in a function type or a
19768 template parameter is not considered part of the immediate context for
19769 the purposes of template argument deduction. */
19770 complain = tf_warning_or_error;
19772 tree saved = DECL_SAVED_TREE (oldfn);
19773 if (TREE_CODE (saved) == BIND_EXPR && BIND_EXPR_BODY_BLOCK (saved))
19774 /* We already have a body block from start_lambda_function, we don't
19775 need another to confuse NRV (91217). */
19776 saved = BIND_EXPR_BODY (saved);
19778 tsubst_stmt (saved, args, complain, r);
19780 finish_lambda_function (body);
19782 in_consteval_if_p = save_in_consteval_if_p;
19784 if (nested)
19785 pop_function_context ();
19786 else
19787 --function_depth;
19789 /* The capture list was built up in reverse order; fix that now. */
19790 LAMBDA_EXPR_CAPTURE_LIST (r)
19791 = nreverse (LAMBDA_EXPR_CAPTURE_LIST (r));
19793 LAMBDA_EXPR_THIS_CAPTURE (r) = NULL_TREE;
19795 maybe_add_lambda_conv_op (type);
19798 out:
19799 finish_struct (type, /*attr*/NULL_TREE);
19801 insert_pending_capture_proxies ();
19803 return r;
19806 /* Subroutine of maybe_fold_fn_template_args. */
19808 static bool
19809 fold_targs_r (tree targs, tsubst_flags_t complain)
19811 int len = TREE_VEC_LENGTH (targs);
19812 for (int i = 0; i < len; ++i)
19814 tree &elt = TREE_VEC_ELT (targs, i);
19815 if (!elt || TYPE_P (elt)
19816 || TREE_CODE (elt) == TEMPLATE_DECL)
19817 continue;
19818 if (TREE_CODE (elt) == NONTYPE_ARGUMENT_PACK)
19820 if (!fold_targs_r (ARGUMENT_PACK_ARGS (elt), complain))
19821 return false;
19823 else if (/* We can only safely preevaluate scalar prvalues. */
19824 SCALAR_TYPE_P (TREE_TYPE (elt))
19825 && !glvalue_p (elt)
19826 && !TREE_CONSTANT (elt))
19828 elt = cxx_constant_value (elt, complain);
19829 if (elt == error_mark_node)
19830 return false;
19834 return true;
19837 /* Try to do constant evaluation of any explicit template arguments in FN
19838 before overload resolution, to get any errors only once. Return true iff
19839 we didn't have any problems folding. */
19841 static bool
19842 maybe_fold_fn_template_args (tree fn, tsubst_flags_t complain)
19844 if (processing_template_decl || fn == NULL_TREE)
19845 return true;
19846 if (fn == error_mark_node)
19847 return false;
19848 if (TREE_CODE (fn) == OFFSET_REF
19849 || TREE_CODE (fn) == COMPONENT_REF)
19850 fn = TREE_OPERAND (fn, 1);
19851 if (BASELINK_P (fn))
19852 fn = BASELINK_FUNCTIONS (fn);
19853 if (TREE_CODE (fn) != TEMPLATE_ID_EXPR)
19854 return true;
19855 tree targs = TREE_OPERAND (fn, 1);
19856 if (targs == NULL_TREE)
19857 return true;
19858 if (targs == error_mark_node)
19859 return false;
19860 return fold_targs_r (targs, complain);
19863 /* Helper function for tsubst_expr CALL_EXPR and ARRAY_REF handling. */
19865 static void
19866 tsubst_call_args (tree t, tree args, tsubst_flags_t complain,
19867 tree in_decl, releasing_vec &call_args)
19869 unsigned int nargs = call_expr_nargs (t);
19870 for (unsigned int i = 0; i < nargs; ++i)
19872 tree arg = CALL_EXPR_ARG (t, i);
19874 if (!PACK_EXPANSION_P (arg))
19875 vec_safe_push (call_args, tsubst_expr (arg, args, complain, in_decl));
19876 else
19878 /* Expand the pack expansion and push each entry onto CALL_ARGS. */
19879 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
19880 if (TREE_CODE (arg) == TREE_VEC)
19882 unsigned int len, j;
19884 len = TREE_VEC_LENGTH (arg);
19885 for (j = 0; j < len; ++j)
19887 tree value = TREE_VEC_ELT (arg, j);
19888 if (value != NULL_TREE)
19889 value = convert_from_reference (value);
19890 vec_safe_push (call_args, value);
19893 else
19894 /* A partial substitution. Add one entry. */
19895 vec_safe_push (call_args, arg);
19900 /* Like tsubst but deals with expressions and performs semantic
19901 analysis. */
19903 tree
19904 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
19906 #define RETURN(EXP) do { retval = (EXP); goto out; } while(0)
19907 #define RECUR(NODE) \
19908 tsubst_expr (NODE, args, complain, in_decl)
19910 tree retval, op1;
19911 location_t save_loc;
19913 if (t == NULL_TREE || t == error_mark_node)
19914 return t;
19916 save_loc = input_location;
19917 if (location_t eloc = cp_expr_location (t))
19918 input_location = eloc;
19920 /* N3276 decltype magic only applies to calls at the top level or on the
19921 right side of a comma. */
19922 tsubst_flags_t decltype_flag = (complain & tf_decltype);
19923 complain &= ~tf_decltype;
19925 /* This flag only applies to id-expressions at the top level, and
19926 controls resolution thereof. */
19927 tsubst_flags_t no_name_lookup_flag = (complain & tf_no_name_lookup);
19928 complain &= ~tf_no_name_lookup;
19930 if (!no_name_lookup_flag)
19931 if (tree d = maybe_dependent_member_ref (t, args, complain, in_decl))
19932 return d;
19934 switch (TREE_CODE (t))
19936 case USING_DECL:
19937 t = DECL_NAME (t);
19938 /* Fall through. */
19939 case IDENTIFIER_NODE:
19941 tree decl;
19942 cp_id_kind idk;
19943 const char *error_msg;
19945 if (IDENTIFIER_CONV_OP_P (t))
19947 tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19948 t = make_conv_op_name (new_type);
19951 if (no_name_lookup_flag)
19952 RETURN (t);
19954 /* Look up the name. */
19955 decl = lookup_name (t);
19957 /* By convention, expressions use ERROR_MARK_NODE to indicate
19958 failure, not NULL_TREE. */
19959 if (decl == NULL_TREE)
19960 decl = error_mark_node;
19962 decl = finish_id_expression (t, decl, NULL_TREE,
19963 &idk,
19964 /*i_c_e_p=*/false,
19965 /*allow_i_c_e_p=*/true,
19966 /*non_i_c_e_p=*/nullptr,
19967 /*template_p=*/false,
19968 /*done=*/true,
19969 /*address_p=*/false,
19970 /*template_arg_p=*/false,
19971 &error_msg,
19972 input_location);
19973 if (error_msg)
19974 error (error_msg);
19975 if (identifier_p (decl))
19977 if (complain & tf_error)
19978 unqualified_name_lookup_error (decl);
19979 decl = error_mark_node;
19981 RETURN (decl);
19984 case TEMPLATE_ID_EXPR:
19986 tree object;
19987 tree templ = TREE_OPERAND (t, 0);
19988 tree targs = TREE_OPERAND (t, 1);
19990 if (no_name_lookup_flag)
19991 templ = tsubst_name (templ, args, complain, in_decl);
19992 else
19993 templ = tsubst_expr (templ, args, complain, in_decl);
19995 if (targs)
19996 targs = tsubst_template_args (targs, args, complain, in_decl);
19997 if (targs == error_mark_node)
19998 RETURN (error_mark_node);
20000 if (TREE_CODE (templ) == SCOPE_REF)
20002 tree name = TREE_OPERAND (templ, 1);
20003 tree tid = lookup_template_function (name, targs);
20004 TREE_OPERAND (templ, 1) = tid;
20005 RETURN (templ);
20008 if (concept_definition_p (templ))
20010 tree check = build_concept_check (templ, targs, complain);
20011 if (check == error_mark_node)
20012 RETURN (error_mark_node);
20014 tree id = unpack_concept_check (check);
20016 /* If we built a function concept check, return the underlying
20017 template-id. So we can evaluate it as a function call. */
20018 if (function_concept_p (TREE_OPERAND (id, 0)))
20019 RETURN (id);
20021 RETURN (check);
20024 if (variable_template_p (templ))
20026 if (no_name_lookup_flag)
20027 RETURN (lookup_template_variable (templ, targs, complain));
20029 tree r = lookup_and_finish_template_variable (templ, targs,
20030 complain);
20031 r = convert_from_reference (r);
20032 r = maybe_wrap_with_location (r, EXPR_LOCATION (t));
20033 RETURN (r);
20036 if (TREE_CODE (templ) == COMPONENT_REF)
20038 object = TREE_OPERAND (templ, 0);
20039 templ = TREE_OPERAND (templ, 1);
20041 else
20042 object = NULL_TREE;
20044 tree tid = lookup_template_function (templ, targs);
20045 protected_set_expr_location (tid, EXPR_LOCATION (t));
20047 if (object)
20048 RETURN (build3 (COMPONENT_REF, TREE_TYPE (tid),
20049 object, tid, NULL_TREE));
20050 else if (no_name_lookup_flag)
20051 RETURN (tid);
20052 else if (identifier_p (templ))
20054 /* C++20 P0846: we can encounter an IDENTIFIER_NODE here when
20055 name lookup found nothing when parsing the template name. */
20056 gcc_assert (cxx_dialect >= cxx20 || seen_error ());
20057 RETURN (tid);
20059 else
20060 RETURN (baselink_for_fns (tid));
20063 case INDIRECT_REF:
20065 tree r = RECUR (TREE_OPERAND (t, 0));
20067 if (REFERENCE_REF_P (t))
20069 /* A type conversion to reference type will be enclosed in
20070 such an indirect ref, but the substitution of the cast
20071 will have also added such an indirect ref. */
20072 r = convert_from_reference (r);
20074 else
20075 r = build_x_indirect_ref (input_location, r, RO_UNARY_STAR,
20076 templated_operator_saved_lookups (t),
20077 complain|decltype_flag);
20079 if (REF_PARENTHESIZED_P (t))
20080 r = force_paren_expr (r);
20082 RETURN (r);
20085 case NOP_EXPR:
20087 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20088 tree op0 = RECUR (TREE_OPERAND (t, 0));
20089 RETURN (build_nop (type, op0));
20092 case IMPLICIT_CONV_EXPR:
20094 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20095 tree expr = RECUR (TREE_OPERAND (t, 0));
20096 if (dependent_type_p (type) || type_dependent_expression_p (expr))
20098 retval = copy_node (t);
20099 TREE_TYPE (retval) = type;
20100 TREE_OPERAND (retval, 0) = expr;
20101 RETURN (retval);
20103 if (IMPLICIT_CONV_EXPR_NONTYPE_ARG (t))
20105 tree r = convert_nontype_argument (type, expr, complain);
20106 if (r == NULL_TREE)
20107 r = error_mark_node;
20108 RETURN (r);
20110 int flags = LOOKUP_IMPLICIT;
20111 if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
20112 flags = LOOKUP_NORMAL;
20113 if (IMPLICIT_CONV_EXPR_BRACED_INIT (t))
20114 flags |= LOOKUP_NO_NARROWING;
20115 RETURN (perform_implicit_conversion_flags (type, expr, complain,
20116 flags));
20119 case CONVERT_EXPR:
20121 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20122 tree op0 = RECUR (TREE_OPERAND (t, 0));
20123 if (op0 == error_mark_node)
20124 RETURN (error_mark_node);
20125 RETURN (build1 (CONVERT_EXPR, type, op0));
20128 case CAST_EXPR:
20129 case REINTERPRET_CAST_EXPR:
20130 case CONST_CAST_EXPR:
20131 case DYNAMIC_CAST_EXPR:
20132 case STATIC_CAST_EXPR:
20134 tree type;
20135 tree op, r = NULL_TREE;
20137 tsubst_flags_t tcomplain = complain;
20138 if (TREE_CODE (t) == CAST_EXPR)
20139 tcomplain |= tf_tst_ok;
20140 type = tsubst (TREE_TYPE (t), args, tcomplain, in_decl);
20142 op = RECUR (TREE_OPERAND (t, 0));
20144 warning_sentinel s(warn_useless_cast);
20145 warning_sentinel s2(warn_ignored_qualifiers);
20146 warning_sentinel s3(warn_int_in_bool_context);
20147 switch (TREE_CODE (t))
20149 case CAST_EXPR:
20150 r = build_functional_cast (input_location, type, op, complain);
20151 break;
20152 case REINTERPRET_CAST_EXPR:
20153 r = build_reinterpret_cast (input_location, type, op, complain);
20154 break;
20155 case CONST_CAST_EXPR:
20156 r = build_const_cast (input_location, type, op, complain);
20157 break;
20158 case DYNAMIC_CAST_EXPR:
20159 r = build_dynamic_cast (input_location, type, op, complain);
20160 break;
20161 case STATIC_CAST_EXPR:
20162 r = build_static_cast (input_location, type, op, complain);
20163 if (IMPLICIT_RVALUE_P (t))
20164 set_implicit_rvalue_p (r);
20165 break;
20166 default:
20167 gcc_unreachable ();
20170 RETURN (r);
20173 case BIT_CAST_EXPR:
20175 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20176 tree op0 = RECUR (TREE_OPERAND (t, 0));
20177 RETURN (cp_build_bit_cast (EXPR_LOCATION (t), type, op0, complain));
20180 case POSTDECREMENT_EXPR:
20181 case POSTINCREMENT_EXPR:
20182 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20183 args, complain, in_decl);
20184 RETURN (build_x_unary_op (input_location, TREE_CODE (t), op1,
20185 templated_operator_saved_lookups (t),
20186 complain|decltype_flag));
20188 case BIT_NOT_EXPR:
20189 if (identifier_p (TREE_OPERAND (t, 0)))
20191 gcc_checking_assert (no_name_lookup_flag);
20192 RETURN (t);
20194 else if (TYPE_P (TREE_OPERAND (t, 0)))
20196 gcc_checking_assert (no_name_lookup_flag);
20197 tree op0 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
20198 RETURN (build_min_nt_loc (EXPR_LOCATION (t), BIT_NOT_EXPR, op0));
20200 /* Fall through. */
20201 case PREDECREMENT_EXPR:
20202 case PREINCREMENT_EXPR:
20203 case NEGATE_EXPR:
20204 case ABS_EXPR:
20205 case TRUTH_NOT_EXPR:
20206 case UNARY_PLUS_EXPR: /* Unary + */
20207 case REALPART_EXPR:
20208 case IMAGPART_EXPR:
20209 RETURN (build_x_unary_op (input_location, TREE_CODE (t),
20210 RECUR (TREE_OPERAND (t, 0)),
20211 templated_operator_saved_lookups (t),
20212 complain|decltype_flag));
20214 case EXCESS_PRECISION_EXPR:
20216 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20217 tree op0 = RECUR (TREE_OPERAND (t, 0));
20218 if (TREE_CODE (op0) == EXCESS_PRECISION_EXPR)
20219 RETURN (op0);
20220 RETURN (build1_loc (EXPR_LOCATION (t), EXCESS_PRECISION_EXPR,
20221 type, op0));
20224 case FIX_TRUNC_EXPR:
20225 /* convert_like should have created an IMPLICIT_CONV_EXPR. */
20226 gcc_unreachable ();
20228 case ADDR_EXPR:
20229 op1 = TREE_OPERAND (t, 0);
20230 if (TREE_CODE (op1) == LABEL_DECL)
20231 RETURN (finish_label_address_expr (DECL_NAME (op1),
20232 EXPR_LOCATION (op1)));
20233 if (TREE_CODE (op1) == SCOPE_REF)
20234 op1 = tsubst_qualified_id (op1, args, complain, in_decl,
20235 /*done=*/true, /*address_p=*/true);
20236 else
20237 op1 = tsubst_non_call_postfix_expression (op1, args, complain,
20238 in_decl);
20239 RETURN (build_x_unary_op (input_location, ADDR_EXPR, op1,
20240 templated_operator_saved_lookups (t),
20241 complain|decltype_flag));
20243 case PLUS_EXPR:
20244 case MINUS_EXPR:
20245 case MULT_EXPR:
20246 case TRUNC_DIV_EXPR:
20247 case CEIL_DIV_EXPR:
20248 case FLOOR_DIV_EXPR:
20249 case ROUND_DIV_EXPR:
20250 case EXACT_DIV_EXPR:
20251 case BIT_AND_EXPR:
20252 case BIT_IOR_EXPR:
20253 case BIT_XOR_EXPR:
20254 case TRUNC_MOD_EXPR:
20255 case FLOOR_MOD_EXPR:
20256 case TRUTH_ANDIF_EXPR:
20257 case TRUTH_ORIF_EXPR:
20258 case TRUTH_AND_EXPR:
20259 case TRUTH_OR_EXPR:
20260 case RSHIFT_EXPR:
20261 case LSHIFT_EXPR:
20262 case EQ_EXPR:
20263 case NE_EXPR:
20264 case MAX_EXPR:
20265 case MIN_EXPR:
20266 case LE_EXPR:
20267 case GE_EXPR:
20268 case LT_EXPR:
20269 case GT_EXPR:
20270 case SPACESHIP_EXPR:
20271 case MEMBER_REF:
20272 case DOTSTAR_EXPR:
20274 /* If either OP0 or OP1 was value- or type-dependent, suppress
20275 warnings that depend on the range of the types involved. */
20276 tree op0 = TREE_OPERAND (t, 0);
20277 tree op1 = TREE_OPERAND (t, 1);
20278 const bool was_dep = (dependent_operand_p (op0)
20279 || dependent_operand_p (op1));
20280 op0 = RECUR (op0);
20281 op1 = RECUR (op1);
20283 warning_sentinel s1(warn_type_limits, was_dep);
20284 warning_sentinel s2(warn_div_by_zero, was_dep);
20285 warning_sentinel s3(warn_logical_op, was_dep);
20286 warning_sentinel s4(warn_tautological_compare, was_dep);
20287 warning_sentinel s5(warn_address, was_dep);
20289 tree r = build_x_binary_op
20290 (input_location, TREE_CODE (t),
20291 op0,
20292 (warning_suppressed_p (TREE_OPERAND (t, 0))
20293 ? ERROR_MARK
20294 : TREE_CODE (TREE_OPERAND (t, 0))),
20295 op1,
20296 (warning_suppressed_p (TREE_OPERAND (t, 1))
20297 ? ERROR_MARK
20298 : TREE_CODE (TREE_OPERAND (t, 1))),
20299 templated_operator_saved_lookups (t),
20300 /*overload=*/NULL,
20301 complain|decltype_flag);
20302 if (EXPR_P (r))
20303 copy_warning (r, t);
20305 RETURN (r);
20308 case POINTER_PLUS_EXPR:
20310 tree op0 = RECUR (TREE_OPERAND (t, 0));
20311 if (op0 == error_mark_node)
20312 RETURN (error_mark_node);
20313 tree op1 = RECUR (TREE_OPERAND (t, 1));
20314 if (op1 == error_mark_node)
20315 RETURN (error_mark_node);
20316 RETURN (fold_build_pointer_plus (op0, op1));
20319 case SCOPE_REF:
20320 if (no_name_lookup_flag)
20322 tree op0 = tsubst_scope (TREE_OPERAND (t, 0), args, complain, in_decl);
20323 tree op1 = tsubst_name (TREE_OPERAND (t, 1), args, complain, in_decl);
20324 RETURN (build_qualified_name (/*type=*/NULL_TREE, op0, op1,
20325 QUALIFIED_NAME_IS_TEMPLATE (t)));
20327 else
20328 RETURN (tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
20329 /*address_p=*/false));
20331 case BASELINK:
20332 RETURN (tsubst_baselink (t, current_nonlambda_class_type (),
20333 args, complain, in_decl));
20335 case ARRAY_REF:
20336 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20337 args, complain, in_decl);
20338 if (TREE_CODE (TREE_OPERAND (t, 1)) == CALL_EXPR
20339 && (CALL_EXPR_FN (TREE_OPERAND (t, 1))
20340 == ovl_op_identifier (ARRAY_REF)))
20342 tree c = TREE_OPERAND (t, 1);
20343 releasing_vec index_exp_list;
20344 tsubst_call_args (c, args, complain, in_decl, index_exp_list);
20346 tree r;
20347 if (vec_safe_length (index_exp_list) == 1
20348 && !PACK_EXPANSION_P (index_exp_list[0]))
20349 r = grok_array_decl (EXPR_LOCATION (t), op1,
20350 index_exp_list[0], NULL,
20351 complain | decltype_flag);
20352 else
20353 r = grok_array_decl (EXPR_LOCATION (t), op1,
20354 NULL_TREE, &index_exp_list,
20355 complain | decltype_flag);
20356 RETURN (r);
20358 RETURN (build_x_array_ref (EXPR_LOCATION (t), op1,
20359 RECUR (TREE_OPERAND (t, 1)),
20360 complain|decltype_flag));
20362 case OMP_ARRAY_SECTION:
20364 tree op0 = RECUR (TREE_OPERAND (t, 0));
20365 tree op1 = NULL_TREE, op2 = NULL_TREE;
20366 if (op0 == error_mark_node)
20367 RETURN (error_mark_node);
20368 if (TREE_OPERAND (t, 1))
20370 op1 = RECUR (TREE_OPERAND (t, 1));
20371 if (op1 == error_mark_node)
20372 RETURN (error_mark_node);
20374 if (TREE_OPERAND (t, 2))
20376 op2 = RECUR (TREE_OPERAND (t, 2));
20377 if (op2 == error_mark_node)
20378 RETURN (error_mark_node);
20380 RETURN (build_omp_array_section (EXPR_LOCATION (t), op0, op1, op2));
20383 case SIZEOF_EXPR:
20384 if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
20385 || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
20387 tree expanded, op = TREE_OPERAND (t, 0);
20388 int len = 0;
20390 if (SIZEOF_EXPR_TYPE_P (t))
20391 op = TREE_TYPE (op);
20393 ++cp_unevaluated_operand;
20394 ++c_inhibit_evaluation_warnings;
20395 /* We only want to compute the number of arguments. */
20396 if (PACK_EXPANSION_P (op))
20397 expanded = tsubst_pack_expansion (op, args, complain, in_decl);
20398 else
20399 expanded = tsubst_template_args (ARGUMENT_PACK_ARGS (op),
20400 args, complain, in_decl);
20401 --cp_unevaluated_operand;
20402 --c_inhibit_evaluation_warnings;
20404 if (TREE_CODE (expanded) == TREE_VEC)
20406 len = TREE_VEC_LENGTH (expanded);
20407 /* Set TREE_USED for the benefit of -Wunused. */
20408 for (int i = 0; i < len; i++)
20409 if (DECL_P (TREE_VEC_ELT (expanded, i)))
20410 TREE_USED (TREE_VEC_ELT (expanded, i)) = true;
20413 if (expanded == error_mark_node)
20414 RETURN (error_mark_node);
20415 else if (PACK_EXPANSION_P (expanded)
20416 || (TREE_CODE (expanded) == TREE_VEC
20417 && pack_expansion_args_count (expanded)))
20420 if (PACK_EXPANSION_P (expanded))
20421 /* OK. */;
20422 else
20423 expanded = make_argument_pack (expanded);
20425 if (TYPE_P (expanded))
20426 RETURN (cxx_sizeof_or_alignof_type (input_location,
20427 expanded, SIZEOF_EXPR,
20428 false,
20429 complain & tf_error));
20430 else
20431 RETURN (cxx_sizeof_or_alignof_expr (input_location,
20432 expanded, SIZEOF_EXPR,
20433 false,
20434 complain & tf_error));
20436 else
20437 RETURN (build_int_cst (size_type_node, len));
20439 /* Fall through */
20441 case ALIGNOF_EXPR:
20443 tree r;
20445 op1 = TREE_OPERAND (t, 0);
20446 if (TREE_CODE (t) == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (t))
20447 op1 = TREE_TYPE (op1);
20448 bool std_alignof = (TREE_CODE (t) == ALIGNOF_EXPR
20449 && ALIGNOF_EXPR_STD_P (t));
20450 if (!args)
20452 /* When there are no ARGS, we are trying to evaluate a
20453 non-dependent expression from the parser. Trying to do
20454 the substitutions may not work. */
20455 if (!TYPE_P (op1))
20456 op1 = TREE_TYPE (op1);
20458 else
20460 ++cp_unevaluated_operand;
20461 ++c_inhibit_evaluation_warnings;
20462 if (TYPE_P (op1))
20463 op1 = tsubst (op1, args, complain, in_decl);
20464 else
20465 op1 = tsubst_expr (op1, args, complain, in_decl);
20466 --cp_unevaluated_operand;
20467 --c_inhibit_evaluation_warnings;
20469 if (TYPE_P (op1))
20470 r = cxx_sizeof_or_alignof_type (input_location,
20471 op1, TREE_CODE (t), std_alignof,
20472 complain & tf_error);
20473 else
20474 r = cxx_sizeof_or_alignof_expr (input_location,
20475 op1, TREE_CODE (t), std_alignof,
20476 complain & tf_error);
20477 if (TREE_CODE (t) == SIZEOF_EXPR && r != error_mark_node)
20479 if (TREE_CODE (r) != SIZEOF_EXPR || TYPE_P (op1))
20481 if (!processing_template_decl && TYPE_P (op1))
20483 r = build_min (SIZEOF_EXPR, size_type_node,
20484 build1 (NOP_EXPR, op1, error_mark_node));
20485 SIZEOF_EXPR_TYPE_P (r) = 1;
20487 else
20488 r = build_min (SIZEOF_EXPR, size_type_node, op1);
20489 TREE_SIDE_EFFECTS (r) = 0;
20490 TREE_READONLY (r) = 1;
20492 SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
20494 RETURN (r);
20497 case AT_ENCODE_EXPR:
20499 op1 = TREE_OPERAND (t, 0);
20500 ++cp_unevaluated_operand;
20501 ++c_inhibit_evaluation_warnings;
20502 op1 = tsubst (op1, args, complain, in_decl);
20503 --cp_unevaluated_operand;
20504 --c_inhibit_evaluation_warnings;
20505 RETURN (objc_build_encode_expr (op1));
20508 case NOEXCEPT_EXPR:
20509 op1 = TREE_OPERAND (t, 0);
20510 ++cp_unevaluated_operand;
20511 ++c_inhibit_evaluation_warnings;
20512 ++cp_noexcept_operand;
20513 op1 = tsubst_expr (op1, args, complain, in_decl);
20514 --cp_unevaluated_operand;
20515 --c_inhibit_evaluation_warnings;
20516 --cp_noexcept_operand;
20517 RETURN (finish_noexcept_expr (op1, complain));
20519 case MODOP_EXPR:
20521 warning_sentinel s(warn_div_by_zero);
20522 tree lhs = RECUR (TREE_OPERAND (t, 0));
20523 tree rhs = RECUR (TREE_OPERAND (t, 2));
20525 tree r = build_x_modify_expr
20526 (EXPR_LOCATION (t), lhs, TREE_CODE (TREE_OPERAND (t, 1)), rhs,
20527 templated_operator_saved_lookups (t),
20528 complain|decltype_flag);
20529 /* TREE_NO_WARNING must be set if either the expression was
20530 parenthesized or it uses an operator such as >>= rather
20531 than plain assignment. In the former case, it was already
20532 set and must be copied. In the latter case,
20533 build_x_modify_expr sets it and it must not be reset
20534 here. */
20535 if (warning_suppressed_p (t, OPT_Wparentheses))
20536 suppress_warning (STRIP_REFERENCE_REF (r), OPT_Wparentheses);
20538 RETURN (r);
20541 case ARROW_EXPR:
20542 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20543 args, complain, in_decl);
20544 /* Remember that there was a reference to this entity. */
20545 if (DECL_P (op1)
20546 && !mark_used (op1, complain) && !(complain & tf_error))
20547 RETURN (error_mark_node);
20548 RETURN (build_x_arrow (input_location, op1, complain));
20550 case NEW_EXPR:
20552 tree placement = RECUR (TREE_OPERAND (t, 0));
20553 tree init = RECUR (TREE_OPERAND (t, 3));
20554 vec<tree, va_gc> *placement_vec;
20555 vec<tree, va_gc> *init_vec;
20556 tree ret;
20557 location_t loc = EXPR_LOCATION (t);
20559 if (placement == NULL_TREE)
20560 placement_vec = NULL;
20561 else if (placement == error_mark_node)
20562 RETURN (error_mark_node);
20563 else
20565 placement_vec = make_tree_vector ();
20566 for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
20567 vec_safe_push (placement_vec, TREE_VALUE (placement));
20570 /* If there was an initializer in the original tree, but it
20571 instantiated to an empty list, then we should pass a
20572 non-NULL empty vector to tell build_new that it was an
20573 empty initializer() rather than no initializer. This can
20574 only happen when the initializer is a pack expansion whose
20575 parameter packs are of length zero. */
20576 if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
20577 init_vec = NULL;
20578 else if (init == error_mark_node)
20579 RETURN (error_mark_node);
20580 else
20582 init_vec = make_tree_vector ();
20583 if (init == void_node)
20584 gcc_assert (init_vec != NULL);
20585 else
20587 for (; init != NULL_TREE; init = TREE_CHAIN (init))
20588 vec_safe_push (init_vec, TREE_VALUE (init));
20592 /* Avoid passing an enclosing decl to valid_array_size_p. */
20593 in_decl = NULL_TREE;
20595 tree op1 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
20596 tree op2 = RECUR (TREE_OPERAND (t, 2));
20597 ret = build_new (loc, &placement_vec, op1, op2,
20598 &init_vec, NEW_EXPR_USE_GLOBAL (t),
20599 complain);
20601 if (placement_vec != NULL)
20602 release_tree_vector (placement_vec);
20603 if (init_vec != NULL)
20604 release_tree_vector (init_vec);
20606 RETURN (ret);
20609 case DELETE_EXPR:
20611 tree op0 = RECUR (TREE_OPERAND (t, 0));
20612 tree op1 = RECUR (TREE_OPERAND (t, 1));
20613 RETURN (delete_sanity (input_location, op0, op1,
20614 DELETE_EXPR_USE_VEC (t),
20615 DELETE_EXPR_USE_GLOBAL (t),
20616 complain));
20619 case COMPOUND_EXPR:
20621 tree op0 = tsubst_expr (TREE_OPERAND (t, 0), args,
20622 complain & ~tf_decltype, in_decl);
20623 RETURN (build_x_compound_expr (EXPR_LOCATION (t),
20624 op0,
20625 RECUR (TREE_OPERAND (t, 1)),
20626 templated_operator_saved_lookups (t),
20627 complain|decltype_flag));
20630 case CALL_EXPR:
20632 tree function;
20633 unsigned int nargs;
20634 bool qualified_p;
20635 bool koenig_p;
20636 tree ret;
20638 function = CALL_EXPR_FN (t);
20639 /* Internal function with no arguments. */
20640 if (function == NULL_TREE && call_expr_nargs (t) == 0)
20641 RETURN (t);
20643 /* When we parsed the expression, we determined whether or
20644 not Koenig lookup should be performed. */
20645 koenig_p = KOENIG_LOOKUP_P (t);
20646 if (function == NULL_TREE)
20648 koenig_p = false;
20649 qualified_p = false;
20651 else if (TREE_CODE (function) == SCOPE_REF)
20653 qualified_p = true;
20654 function = tsubst_qualified_id (function, args, complain, in_decl,
20655 /*done=*/false,
20656 /*address_p=*/false);
20658 else if (CALL_EXPR_STATIC_CHAIN (t)
20659 && TREE_CODE (function) == FUNCTION_DECL
20660 && fndecl_built_in_p (function, BUILT_IN_CLASSIFY_TYPE))
20662 tree type = tsubst (CALL_EXPR_STATIC_CHAIN (t), args, complain,
20663 in_decl);
20664 if (dependent_type_p (type))
20666 ret = build_vl_exp (CALL_EXPR, 4);
20667 CALL_EXPR_FN (ret) = function;
20668 CALL_EXPR_STATIC_CHAIN (ret) = type;
20669 CALL_EXPR_ARG (ret, 0)
20670 = build_min (SIZEOF_EXPR, size_type_node, type);
20671 TREE_TYPE (ret) = integer_type_node;
20673 else
20674 ret = build_int_cst (integer_type_node, type_to_class (type));
20675 RETURN (ret);
20677 else if (koenig_p
20678 && (identifier_p (function)
20679 || (TREE_CODE (function) == TEMPLATE_ID_EXPR
20680 && identifier_p (TREE_OPERAND (function, 0)))))
20682 /* Do nothing; calling tsubst_expr on an identifier
20683 would incorrectly perform unqualified lookup again.
20685 Note that we can also have an IDENTIFIER_NODE if the earlier
20686 unqualified lookup found a dependent local extern declaration
20687 (as per finish_call_expr); in that case koenig_p will be false
20688 and we do want to do the lookup again to find the substituted
20689 declaration. */
20690 qualified_p = false;
20692 if (TREE_CODE (function) == TEMPLATE_ID_EXPR)
20693 function = tsubst_name (function, args, complain, in_decl);
20695 else
20697 if (TREE_CODE (function) == COMPONENT_REF)
20699 tree op = TREE_OPERAND (function, 1);
20701 qualified_p = (TREE_CODE (op) == SCOPE_REF
20702 || (BASELINK_P (op)
20703 && BASELINK_QUALIFIED_P (op)));
20705 else
20706 qualified_p = false;
20708 if (TREE_CODE (function) == ADDR_EXPR
20709 && TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL)
20710 /* Avoid error about taking the address of a constructor. */
20711 function = TREE_OPERAND (function, 0);
20713 tsubst_flags_t subcomplain = complain;
20714 if (koenig_p && TREE_CODE (function) == FUNCTION_DECL)
20715 /* When KOENIG_P, we don't want to mark_used the callee before
20716 augmenting the overload set via ADL, so during this initial
20717 substitution we disable mark_used by setting tf_conv (68942). */
20718 subcomplain |= tf_conv;
20719 function = tsubst_expr (function, args, subcomplain, in_decl);
20721 if (BASELINK_P (function))
20722 qualified_p = true;
20725 nargs = call_expr_nargs (t);
20726 releasing_vec call_args;
20727 tsubst_call_args (t, args, complain, in_decl, call_args);
20729 /* Stripped-down processing for a call in a thunk. Specifically, in
20730 the thunk template for a generic lambda. */
20731 if (call_from_lambda_thunk_p (t))
20733 /* Now that we've expanded any packs, the number of call args
20734 might be different. */
20735 unsigned int cargs = call_args->length ();
20736 tree thisarg = NULL_TREE;
20737 if (TREE_CODE (function) == COMPONENT_REF)
20739 thisarg = TREE_OPERAND (function, 0);
20740 if (TREE_CODE (thisarg) == INDIRECT_REF)
20741 thisarg = TREE_OPERAND (thisarg, 0);
20742 function = TREE_OPERAND (function, 1);
20743 if (TREE_CODE (function) == BASELINK)
20744 function = BASELINK_FUNCTIONS (function);
20746 /* We aren't going to do normal overload resolution, so force the
20747 template-id to resolve. */
20748 function = resolve_nondeduced_context (function, complain);
20749 for (unsigned i = 0; i < cargs; ++i)
20751 /* In a thunk, pass through args directly, without any
20752 conversions. */
20753 tree arg = (*call_args)[i];
20754 while (TREE_CODE (arg) != PARM_DECL)
20755 arg = TREE_OPERAND (arg, 0);
20756 (*call_args)[i] = arg;
20758 if (thisarg)
20760 /* If there are no other args, just push 'this'. */
20761 if (cargs == 0)
20762 vec_safe_push (call_args, thisarg);
20763 else
20765 /* Otherwise, shift the other args over to make room. */
20766 tree last = (*call_args)[cargs - 1];
20767 vec_safe_push (call_args, last);
20768 for (int i = cargs - 1; i > 0; --i)
20769 (*call_args)[i] = (*call_args)[i - 1];
20770 (*call_args)[0] = thisarg;
20773 ret = build_call_a (function, call_args->length (),
20774 call_args->address ());
20775 /* The thunk location is not interesting. */
20776 SET_EXPR_LOCATION (ret, UNKNOWN_LOCATION);
20777 CALL_FROM_THUNK_P (ret) = true;
20778 if (CLASS_TYPE_P (TREE_TYPE (ret)))
20779 CALL_EXPR_RETURN_SLOT_OPT (ret) = true;
20781 RETURN (ret);
20784 /* We do not perform argument-dependent lookup if normal
20785 lookup finds a non-function, in accordance with the
20786 resolution of DR 218. */
20787 if (koenig_p
20788 && ((is_overloaded_fn (function)
20789 /* If lookup found a member function, the Koenig lookup is
20790 not appropriate, even if an unqualified-name was used
20791 to denote the function. */
20792 && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
20793 || identifier_p (function)
20794 /* C++20 P0846: Lookup found nothing. */
20795 || (TREE_CODE (function) == TEMPLATE_ID_EXPR
20796 && identifier_p (TREE_OPERAND (function, 0))))
20797 /* Only do this when substitution turns a dependent call
20798 into a non-dependent call. */
20799 && type_dependent_expression_p_push (t)
20800 && !any_type_dependent_arguments_p (call_args))
20801 function = perform_koenig_lookup (function, call_args, tf_none);
20803 if (function != NULL_TREE
20804 && (identifier_p (function)
20805 || (TREE_CODE (function) == TEMPLATE_ID_EXPR
20806 && identifier_p (TREE_OPERAND (function, 0))
20807 && !any_dependent_template_arguments_p (TREE_OPERAND
20808 (function, 1))))
20809 && !any_type_dependent_arguments_p (call_args))
20811 bool template_id_p = (TREE_CODE (function) == TEMPLATE_ID_EXPR);
20812 if (template_id_p)
20813 function = TREE_OPERAND (function, 0);
20814 if (koenig_p && (complain & tf_warning_or_error))
20816 /* For backwards compatibility and good diagnostics, try
20817 the unqualified lookup again if we aren't in SFINAE
20818 context. */
20819 tree unq = tsubst_expr (function, args, complain, in_decl);
20820 if (unq == error_mark_node)
20821 RETURN (error_mark_node);
20823 if (unq != function)
20825 char const *const msg
20826 = G_("%qD was not declared in this scope, "
20827 "and no declarations were found by "
20828 "argument-dependent lookup at the point "
20829 "of instantiation");
20831 bool in_lambda = (current_class_type
20832 && LAMBDA_TYPE_P (current_class_type));
20833 /* In a lambda fn, we have to be careful to not
20834 introduce new this captures. Legacy code can't
20835 be using lambdas anyway, so it's ok to be
20836 stricter. Be strict with C++20 template-id ADL too.
20837 And be strict if we're already failing anyway. */
20838 bool strict = in_lambda || template_id_p || seen_error();
20839 bool diag = true;
20840 if (strict)
20841 error_at (cp_expr_loc_or_input_loc (t),
20842 msg, function);
20843 else
20844 diag = permerror (cp_expr_loc_or_input_loc (t),
20845 msg, function);
20846 if (diag)
20848 tree fn = unq;
20850 if (INDIRECT_REF_P (fn))
20851 fn = TREE_OPERAND (fn, 0);
20852 if (is_overloaded_fn (fn))
20853 fn = get_first_fn (fn);
20855 if (!DECL_P (fn))
20856 /* Can't say anything more. */;
20857 else if (DECL_CLASS_SCOPE_P (fn))
20859 location_t loc = cp_expr_loc_or_input_loc (t);
20860 inform (loc,
20861 "declarations in dependent base %qT are "
20862 "not found by unqualified lookup",
20863 DECL_CLASS_CONTEXT (fn));
20864 if (current_class_ptr)
20865 inform (loc,
20866 "use %<this->%D%> instead", function);
20867 else
20868 inform (loc,
20869 "use %<%T::%D%> instead",
20870 current_class_name, function);
20872 else
20873 inform (DECL_SOURCE_LOCATION (fn),
20874 "%qD declared here, later in the "
20875 "translation unit", fn);
20876 if (strict)
20877 RETURN (error_mark_node);
20880 function = unq;
20883 if (identifier_p (function))
20885 if (complain & tf_error)
20886 unqualified_name_lookup_error (function);
20887 RETURN (error_mark_node);
20891 /* Remember that there was a reference to this entity. */
20892 if (function != NULL_TREE
20893 && DECL_P (function)
20894 && !mark_used (function, complain) && !(complain & tf_error))
20895 RETURN (error_mark_node);
20897 if (!maybe_fold_fn_template_args (function, complain))
20898 return error_mark_node;
20900 /* Put back tf_decltype for the actual call. */
20901 complain |= decltype_flag;
20903 if (function == NULL_TREE)
20904 switch (CALL_EXPR_IFN (t))
20906 case IFN_LAUNDER:
20907 gcc_assert (nargs == 1);
20908 if (vec_safe_length (call_args) != 1)
20910 error_at (cp_expr_loc_or_input_loc (t),
20911 "wrong number of arguments to "
20912 "%<__builtin_launder%>");
20913 ret = error_mark_node;
20915 else
20916 ret = finish_builtin_launder (cp_expr_loc_or_input_loc (t),
20917 (*call_args)[0], complain);
20918 break;
20920 case IFN_VEC_CONVERT:
20921 gcc_assert (nargs == 1);
20922 if (vec_safe_length (call_args) != 1)
20924 error_at (cp_expr_loc_or_input_loc (t),
20925 "wrong number of arguments to "
20926 "%<__builtin_convertvector%>");
20927 ret = error_mark_node;
20928 break;
20930 ret = cp_build_vec_convert ((*call_args)[0], input_location,
20931 tsubst (TREE_TYPE (t), args,
20932 complain, in_decl),
20933 complain);
20934 if (TREE_CODE (ret) == VIEW_CONVERT_EXPR)
20935 RETURN (ret);
20936 break;
20938 case IFN_SHUFFLEVECTOR:
20940 ret = build_x_shufflevector (input_location, call_args,
20941 complain);
20942 if (ret != error_mark_node)
20943 RETURN (ret);
20944 break;
20947 case IFN_ASSUME:
20948 gcc_assert (nargs == 1);
20949 if (vec_safe_length (call_args) != 1)
20951 error_at (cp_expr_loc_or_input_loc (t),
20952 "wrong number of arguments to "
20953 "%<assume%> attribute");
20954 ret = error_mark_node;
20956 else
20958 tree &arg = (*call_args)[0];
20959 if (!type_dependent_expression_p (arg))
20960 arg = contextual_conv_bool (arg, tf_warning_or_error);
20961 if (error_operand_p (arg))
20963 ret = error_mark_node;
20964 break;
20966 ret = build_assume_call (EXPR_LOCATION (t), arg);
20967 RETURN (ret);
20969 break;
20971 default:
20972 /* Unsupported internal function with arguments. */
20973 gcc_unreachable ();
20975 else if (TREE_CODE (function) == OFFSET_REF
20976 || TREE_CODE (function) == DOTSTAR_EXPR
20977 || TREE_CODE (function) == MEMBER_REF)
20978 ret = build_offset_ref_call_from_tree (function, &call_args,
20979 complain);
20980 else if (concept_check_p (function))
20982 /* FUNCTION is a template-id referring to a concept definition. */
20983 tree id = unpack_concept_check (function);
20984 tree tmpl = TREE_OPERAND (id, 0);
20985 tree args = TREE_OPERAND (id, 1);
20987 /* Calls to standard and variable concepts should have been
20988 previously diagnosed. */
20989 gcc_assert (function_concept_p (tmpl));
20991 /* Ensure the result is wrapped as a call expression. */
20992 ret = build_concept_check (tmpl, args, tf_warning_or_error);
20994 else
20995 ret = finish_call_expr (function, &call_args,
20996 /*disallow_virtual=*/qualified_p,
20997 koenig_p,
20998 complain);
21000 if (ret != error_mark_node)
21002 bool op = CALL_EXPR_OPERATOR_SYNTAX (t);
21003 bool ord = CALL_EXPR_ORDERED_ARGS (t);
21004 bool rev = CALL_EXPR_REVERSE_ARGS (t);
21005 if (op || ord || rev)
21006 if (tree call = extract_call_expr (ret))
21008 CALL_EXPR_OPERATOR_SYNTAX (call) = op;
21009 CALL_EXPR_ORDERED_ARGS (call) = ord;
21010 CALL_EXPR_REVERSE_ARGS (call) = rev;
21012 if (warning_suppressed_p (t, OPT_Wpessimizing_move))
21013 /* This also suppresses -Wredundant-move. */
21014 suppress_warning (ret, OPT_Wpessimizing_move);
21017 RETURN (ret);
21020 case COND_EXPR:
21022 tree cond = RECUR (TREE_OPERAND (t, 0));
21023 cond = mark_rvalue_use (cond);
21024 tree folded_cond = fold_non_dependent_expr (cond, complain);
21025 tree exp1, exp2;
21027 if (TREE_CODE (folded_cond) == INTEGER_CST)
21029 if (integer_zerop (folded_cond))
21031 ++c_inhibit_evaluation_warnings;
21032 exp1 = RECUR (TREE_OPERAND (t, 1));
21033 --c_inhibit_evaluation_warnings;
21034 exp2 = RECUR (TREE_OPERAND (t, 2));
21036 else
21038 exp1 = RECUR (TREE_OPERAND (t, 1));
21039 ++c_inhibit_evaluation_warnings;
21040 exp2 = RECUR (TREE_OPERAND (t, 2));
21041 --c_inhibit_evaluation_warnings;
21043 cond = folded_cond;
21045 else
21047 exp1 = RECUR (TREE_OPERAND (t, 1));
21048 exp2 = RECUR (TREE_OPERAND (t, 2));
21051 warning_sentinel s(warn_duplicated_branches);
21052 RETURN (build_x_conditional_expr (EXPR_LOCATION (t),
21053 cond, exp1, exp2, complain));
21056 case PSEUDO_DTOR_EXPR:
21058 tree op0 = RECUR (TREE_OPERAND (t, 0));
21059 tree op1 = RECUR (TREE_OPERAND (t, 1));
21060 tree op2 = tsubst (TREE_OPERAND (t, 2), args, complain, in_decl);
21061 RETURN (finish_pseudo_destructor_expr (op0, op1, op2,
21062 input_location));
21065 case TREE_LIST:
21066 RETURN (tsubst_tree_list (t, args, complain, in_decl));
21068 case COMPONENT_REF:
21070 tree object;
21071 tree object_type;
21072 tree member;
21073 tree r;
21075 object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
21076 args, complain, in_decl);
21077 /* Remember that there was a reference to this entity. */
21078 if (DECL_P (object)
21079 && !mark_used (object, complain) && !(complain & tf_error))
21080 RETURN (error_mark_node);
21081 object_type = TREE_TYPE (object);
21083 member = TREE_OPERAND (t, 1);
21084 if (BASELINK_P (member))
21085 member = tsubst_baselink (member,
21086 non_reference (TREE_TYPE (object)),
21087 args, complain, in_decl);
21088 else
21089 member = tsubst_name (member, args, complain, in_decl);
21090 if (member == error_mark_node)
21091 RETURN (error_mark_node);
21093 if (object_type && TYPE_PTRMEMFUNC_P (object_type)
21094 && TREE_CODE (member) == FIELD_DECL)
21096 r = build_ptrmemfunc_access_expr (object, DECL_NAME (member));
21097 RETURN (r);
21099 else if (TREE_CODE (member) == FIELD_DECL)
21101 r = finish_non_static_data_member (member, object, NULL_TREE,
21102 complain);
21103 if (TREE_CODE (r) == COMPONENT_REF)
21104 REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
21105 RETURN (r);
21107 else if (type_dependent_expression_p (object))
21108 /* We can't do much here. */;
21109 else if (!CLASS_TYPE_P (object_type))
21111 if (scalarish_type_p (object_type))
21113 tree s = NULL_TREE;
21114 tree dtor = member;
21116 if (TREE_CODE (dtor) == SCOPE_REF)
21118 s = TREE_OPERAND (dtor, 0);
21119 dtor = TREE_OPERAND (dtor, 1);
21121 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
21123 dtor = TREE_OPERAND (dtor, 0);
21124 if (TYPE_P (dtor))
21125 RETURN (finish_pseudo_destructor_expr
21126 (object, s, dtor, input_location));
21130 else if (TREE_CODE (member) == SCOPE_REF
21131 && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
21133 /* Lookup the template functions now that we know what the
21134 scope is. */
21135 tree scope = TREE_OPERAND (member, 0);
21136 tree tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
21137 tree args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
21138 member = lookup_qualified_name (scope, tmpl, LOOK_want::NORMAL,
21139 /*complain=*/false);
21140 if (BASELINK_P (member))
21142 BASELINK_FUNCTIONS (member)
21143 = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
21144 args);
21145 member = (adjust_result_of_qualified_name_lookup
21146 (member, BINFO_TYPE (BASELINK_BINFO (member)),
21147 object_type));
21149 else
21151 qualified_name_lookup_error (scope, tmpl, member,
21152 input_location);
21153 RETURN (error_mark_node);
21156 else if (TREE_CODE (member) == SCOPE_REF
21157 && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
21158 && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
21160 if (complain & tf_error)
21162 if (TYPE_P (TREE_OPERAND (member, 0)))
21163 error ("%qT is not a class or namespace",
21164 TREE_OPERAND (member, 0));
21165 else
21166 error ("%qD is not a class or namespace",
21167 TREE_OPERAND (member, 0));
21169 RETURN (error_mark_node);
21172 r = finish_class_member_access_expr (object, member,
21173 /*template_p=*/false,
21174 complain);
21175 if (REF_PARENTHESIZED_P (t))
21176 r = force_paren_expr (r);
21177 RETURN (r);
21180 case THROW_EXPR:
21181 RETURN (build_throw
21182 (input_location, RECUR (TREE_OPERAND (t, 0))));
21184 case CONSTRUCTOR:
21186 vec<constructor_elt, va_gc> *n;
21187 constructor_elt *ce;
21188 unsigned HOST_WIDE_INT idx;
21189 bool process_index_p;
21190 int newlen;
21191 bool need_copy_p = false;
21192 tree r;
21194 tsubst_flags_t tcomplain = complain;
21195 if (COMPOUND_LITERAL_P (t))
21196 tcomplain |= tf_tst_ok;
21197 tree type = tsubst (TREE_TYPE (t), args, tcomplain, in_decl);
21198 if (type == error_mark_node)
21199 RETURN (error_mark_node);
21201 /* We do not want to process the index of aggregate
21202 initializers as they are identifier nodes which will be
21203 looked up by digest_init. */
21204 process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
21206 if (null_member_pointer_value_p (t))
21208 gcc_assert (same_type_p (type, TREE_TYPE (t)));
21209 RETURN (t);
21212 n = vec_safe_copy (CONSTRUCTOR_ELTS (t));
21213 newlen = vec_safe_length (n);
21214 FOR_EACH_VEC_SAFE_ELT (n, idx, ce)
21216 if (ce->index && process_index_p
21217 /* An identifier index is looked up in the type
21218 being initialized, not the current scope. */
21219 && TREE_CODE (ce->index) != IDENTIFIER_NODE)
21220 ce->index = RECUR (ce->index);
21222 if (PACK_EXPANSION_P (ce->value))
21224 /* Substitute into the pack expansion. */
21225 ce->value = tsubst_pack_expansion (ce->value, args, complain,
21226 in_decl);
21228 if (ce->value == error_mark_node
21229 || PACK_EXPANSION_P (ce->value))
21231 else if (TREE_VEC_LENGTH (ce->value) == 1)
21232 /* Just move the argument into place. */
21233 ce->value = TREE_VEC_ELT (ce->value, 0);
21234 else
21236 /* Update the length of the final CONSTRUCTOR
21237 arguments vector, and note that we will need to
21238 copy.*/
21239 newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
21240 need_copy_p = true;
21243 else
21244 ce->value = RECUR (ce->value);
21247 if (need_copy_p)
21249 vec<constructor_elt, va_gc> *old_n = n;
21251 vec_alloc (n, newlen);
21252 FOR_EACH_VEC_ELT (*old_n, idx, ce)
21254 if (TREE_CODE (ce->value) == TREE_VEC)
21256 int i, len = TREE_VEC_LENGTH (ce->value);
21257 for (i = 0; i < len; ++i)
21258 CONSTRUCTOR_APPEND_ELT (n, 0,
21259 TREE_VEC_ELT (ce->value, i));
21261 else
21262 CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
21266 r = build_constructor (init_list_type_node, n);
21267 CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
21268 CONSTRUCTOR_IS_DESIGNATED_INIT (r)
21269 = CONSTRUCTOR_IS_DESIGNATED_INIT (t);
21271 if (TREE_HAS_CONSTRUCTOR (t))
21273 fcl_t cl = fcl_functional;
21274 if (CONSTRUCTOR_C99_COMPOUND_LITERAL (t))
21275 cl = fcl_c99;
21276 RETURN (finish_compound_literal (type, r, complain, cl));
21279 TREE_TYPE (r) = type;
21280 RETURN (r);
21283 case TYPEID_EXPR:
21285 tree operand_0 = TREE_OPERAND (t, 0);
21286 if (TYPE_P (operand_0))
21288 operand_0 = tsubst (operand_0, args, complain, in_decl);
21289 RETURN (get_typeid (operand_0, complain));
21291 else
21293 operand_0 = RECUR (operand_0);
21294 RETURN (build_typeid (operand_0, complain));
21298 case FUNCTION_DECL:
21299 case PARM_DECL:
21300 case VAR_DECL:
21301 if (!args)
21302 RETURN (t);
21303 tree r;
21304 if (VAR_OR_FUNCTION_DECL_P (t)
21305 && DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
21306 r = tsubst_decl (t, args, complain);
21307 else if (VAR_OR_FUNCTION_DECL_P (t) && DECL_LOCAL_DECL_P (t))
21309 /* Local specialization will usually have been created when
21310 we instantiated the DECL_EXPR_DECL. */
21311 r = retrieve_local_specialization (t);
21312 if (!r)
21314 /* We're in a generic lambda referencing a local extern
21315 from an outer block-scope of a non-template. */
21316 gcc_checking_assert (LAMBDA_FUNCTION_P (current_function_decl));
21317 r = t;
21320 else if (local_variable_p (t)
21321 && ((r = retrieve_local_specialization (t))
21322 || TREE_CODE (t) == PARM_DECL
21323 || uses_template_parms (DECL_CONTEXT (t))))
21325 if (r == NULL_TREE && TREE_CODE (t) == PARM_DECL)
21327 /* We get here for a use of 'this' in an NSDMI. */
21328 if (DECL_NAME (t) == this_identifier && current_class_ptr)
21329 RETURN (current_class_ptr);
21331 /* This can happen for a parameter name used later in a function
21332 declaration (such as in a late-specified return type). Just
21333 make a dummy decl, since it's only used for its type. */
21334 gcc_assert (cp_unevaluated_operand);
21335 r = tsubst_decl (t, args, complain);
21336 /* Give it the template pattern as its context; its true context
21337 hasn't been instantiated yet and this is good enough for
21338 mangling. */
21339 DECL_CONTEXT (r) = DECL_CONTEXT (t);
21341 else if (r == NULL_TREE)
21343 /* First try name lookup to find the instantiation. */
21344 r = lookup_name (DECL_NAME (t));
21345 if (r)
21347 if (!VAR_P (r))
21349 /* During error-recovery we may find a non-variable,
21350 even an OVERLOAD: just bail out and avoid ICEs and
21351 duplicate diagnostics (c++/62207). */
21352 gcc_assert (seen_error ());
21353 RETURN (error_mark_node);
21355 if (!is_capture_proxy (r))
21357 /* Make sure the one we found is the one we want. */
21358 tree ctx = enclosing_instantiation_of (DECL_CONTEXT (t));
21359 if (ctx != DECL_CONTEXT (r))
21360 r = NULL_TREE;
21364 if (r)
21365 /* OK */;
21366 else
21368 /* This can happen for a variable used in a
21369 late-specified return type of a local lambda, or for a
21370 local static or constant. Building a new VAR_DECL
21371 should be OK in all those cases. */
21372 r = tsubst_decl (t, args, complain);
21373 if (local_specializations)
21374 /* Avoid infinite recursion (79640). */
21375 register_local_specialization (r, t);
21376 if (decl_maybe_constant_var_p (r))
21378 /* We can't call cp_finish_decl, so handle the
21379 initializer by hand. */
21380 tree init = tsubst_init (DECL_INITIAL (t), r, args,
21381 complain, in_decl);
21382 if (!processing_template_decl)
21383 init = maybe_constant_init (init);
21384 if (processing_template_decl
21385 ? potential_constant_expression (init)
21386 : reduced_constant_expression_p (init))
21387 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
21388 = TREE_CONSTANT (r) = true;
21389 DECL_INITIAL (r) = init;
21390 if (tree auto_node = type_uses_auto (TREE_TYPE (r)))
21391 TREE_TYPE (r)
21392 = do_auto_deduction (TREE_TYPE (r), init, auto_node,
21393 complain, adc_variable_type);
21395 gcc_assert (cp_unevaluated_operand
21396 || processing_contract_condition
21397 || TREE_STATIC (r)
21398 || decl_constant_var_p (r)
21399 || seen_error ());
21400 if (!processing_template_decl
21401 && !TREE_STATIC (r))
21402 r = process_outer_var_ref (r, complain);
21404 /* Remember this for subsequent uses. */
21405 if (local_specializations)
21406 register_local_specialization (r, t);
21408 if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
21409 r = argument_pack_select_arg (r);
21411 else
21412 r = t;
21413 if (!mark_used (r, complain))
21414 RETURN (error_mark_node);
21416 if (!no_name_lookup_flag
21417 && (TREE_CODE (t) == PARM_DECL || TREE_CODE (t) == VAR_DECL))
21419 /* ??? We're doing a subset of finish_id_expression here. */
21420 if (tree wrap = maybe_get_tls_wrapper_call (r))
21421 /* Replace an evaluated use of the thread_local variable with
21422 a call to its wrapper. */
21423 r = wrap;
21424 else if (outer_automatic_var_p (r))
21425 r = process_outer_var_ref (r, complain);
21427 if (!TYPE_REF_P (TREE_TYPE (t)))
21428 /* If the original type was a reference, we'll be wrapped in
21429 the appropriate INDIRECT_REF. */
21430 r = convert_from_reference (r);
21432 RETURN (r);
21434 case CONST_DECL:
21436 tree enum_type;
21437 tree v;
21439 if (DECL_TEMPLATE_PARM_P (t))
21440 RETURN (RECUR (DECL_INITIAL (t)));
21441 if (!uses_template_parms (DECL_CONTEXT (t)))
21442 RETURN (t);
21444 /* Unfortunately, we cannot just call lookup_name here.
21445 Consider:
21447 template <int I> int f() {
21448 enum E { a = I };
21449 struct S { void g() { E e = a; } };
21452 When we instantiate f<7>::S::g(), say, lookup_name is not
21453 clever enough to find f<7>::a. */
21454 enum_type
21455 = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
21456 /*entering_scope=*/0);
21458 for (v = TYPE_VALUES (enum_type);
21459 v != NULL_TREE;
21460 v = TREE_CHAIN (v))
21461 if (TREE_PURPOSE (v) == DECL_NAME (t))
21462 RETURN (TREE_VALUE (v));
21464 /* We didn't find the name. That should never happen; if
21465 name-lookup found it during preliminary parsing, we
21466 should find it again here during instantiation. */
21467 gcc_unreachable ();
21468 RETURN (t);
21471 case FIELD_DECL:
21472 if (DECL_CONTEXT (t))
21474 tree ctx;
21476 ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
21477 /*entering_scope=*/1);
21478 if (ctx != DECL_CONTEXT (t))
21480 tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
21481 if (!r)
21483 if (complain & tf_error)
21484 error ("using invalid field %qD", t);
21485 RETURN (error_mark_node);
21487 RETURN (r);
21490 RETURN (t);
21492 case NAMESPACE_DECL:
21493 case OVERLOAD:
21494 RETURN (t);
21496 case TEMPLATE_DECL:
21497 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
21498 RETURN (tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
21499 args, complain, in_decl));
21500 else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
21501 RETURN (tsubst (t, args, complain, in_decl));
21502 else if (DECL_CLASS_SCOPE_P (t)
21503 && uses_template_parms (DECL_CONTEXT (t)))
21505 /* Template template argument like the following example need
21506 special treatment:
21508 template <template <class> class TT> struct C {};
21509 template <class T> struct D {
21510 template <class U> struct E {};
21511 C<E> c; // #1
21513 D<int> d; // #2
21515 We are processing the template argument `E' in #1 for
21516 the template instantiation #2. Originally, `E' is a
21517 TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT. Now we
21518 have to substitute this with one having context `D<int>'. */
21520 tree context = tsubst_aggr_type (DECL_CONTEXT (t), args, complain,
21521 in_decl, /*entering_scope=*/true);
21522 RETURN (lookup_field (context, DECL_NAME(t), 0, false));
21524 else
21525 /* Ordinary template template argument. */
21526 RETURN (t);
21528 case TEMPLATE_PARM_INDEX:
21529 case TYPE_DECL:
21530 RETURN (tsubst (t, args, complain, in_decl));
21532 case CLEANUP_POINT_EXPR:
21533 /* We shouldn't have built any of these during initial template
21534 generation. Instead, they should be built during instantiation
21535 in response to the saved STMT_IS_FULL_EXPR_P setting. */
21536 gcc_unreachable ();
21538 case OFFSET_REF:
21540 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
21541 tree op0 = RECUR (TREE_OPERAND (t, 0));
21542 tree op1 = RECUR (TREE_OPERAND (t, 1));
21543 r = build2 (OFFSET_REF, type, op0, op1);
21544 PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
21545 if (!mark_used (TREE_OPERAND (r, 1), complain)
21546 && !(complain & tf_error))
21547 RETURN (error_mark_node);
21548 RETURN (r);
21551 case EXPR_PACK_EXPANSION:
21552 error ("invalid use of pack expansion expression");
21553 RETURN (error_mark_node);
21555 case NONTYPE_ARGUMENT_PACK:
21556 error ("use %<...%> to expand argument pack");
21557 RETURN (error_mark_node);
21559 case VOID_CST:
21560 gcc_checking_assert (t == void_node && VOID_TYPE_P (TREE_TYPE (t)));
21561 RETURN (t);
21563 case INTEGER_CST:
21564 case REAL_CST:
21565 case COMPLEX_CST:
21566 case VECTOR_CST:
21568 /* Instantiate any typedefs in the type. */
21569 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
21570 r = fold_convert (type, t);
21571 gcc_assert (TREE_CODE (r) == TREE_CODE (t));
21572 RETURN (r);
21575 case STRING_CST:
21577 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
21578 r = t;
21579 if (type != TREE_TYPE (t))
21581 r = copy_node (t);
21582 TREE_TYPE (r) = type;
21584 RETURN (r);
21587 case PTRMEM_CST:
21588 /* These can sometimes show up in a partial instantiation, but never
21589 involve template parms. */
21590 gcc_assert (!uses_template_parms (t));
21591 RETURN (t);
21593 case UNARY_LEFT_FOLD_EXPR:
21594 RETURN (tsubst_unary_left_fold (t, args, complain, in_decl));
21595 case UNARY_RIGHT_FOLD_EXPR:
21596 RETURN (tsubst_unary_right_fold (t, args, complain, in_decl));
21597 case BINARY_LEFT_FOLD_EXPR:
21598 RETURN (tsubst_binary_left_fold (t, args, complain, in_decl));
21599 case BINARY_RIGHT_FOLD_EXPR:
21600 RETURN (tsubst_binary_right_fold (t, args, complain, in_decl));
21601 case PREDICT_EXPR:
21602 RETURN (t);
21604 case DEBUG_BEGIN_STMT:
21605 /* ??? There's no point in copying it for now, but maybe some
21606 day it will contain more information, such as a pointer back
21607 to the containing function, inlined copy or so. */
21608 RETURN (t);
21610 case CO_YIELD_EXPR:
21611 RETURN (finish_co_yield_expr (input_location,
21612 RECUR (TREE_OPERAND (t, 0))));
21614 case CO_AWAIT_EXPR:
21615 RETURN (finish_co_await_expr (input_location,
21616 RECUR (TREE_OPERAND (t, 0))));
21618 case VA_ARG_EXPR:
21620 tree op0 = RECUR (TREE_OPERAND (t, 0));
21621 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
21622 RETURN (build_x_va_arg (EXPR_LOCATION (t), op0, type));
21625 case OFFSETOF_EXPR:
21627 tree object_ptr
21628 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl);
21629 RETURN (finish_offsetof (object_ptr,
21630 RECUR (TREE_OPERAND (t, 0)),
21631 EXPR_LOCATION (t)));
21634 case ADDRESSOF_EXPR:
21635 RETURN (cp_build_addressof (EXPR_LOCATION (t),
21636 RECUR (TREE_OPERAND (t, 0)), complain));
21638 case TRAIT_EXPR:
21640 tree type1 = TRAIT_EXPR_TYPE1 (t);
21641 if (TYPE_P (type1))
21642 type1 = tsubst (type1, args, complain, in_decl);
21643 else
21644 type1 = tsubst_expr (type1, args, complain, in_decl);
21645 tree type2 = tsubst (TRAIT_EXPR_TYPE2 (t), args,
21646 complain, in_decl);
21647 RETURN (finish_trait_expr (TRAIT_EXPR_LOCATION (t),
21648 TRAIT_EXPR_KIND (t), type1, type2));
21651 case STMT_EXPR:
21653 tree old_stmt_expr = cur_stmt_expr;
21654 tree stmt_expr = begin_stmt_expr ();
21656 cur_stmt_expr = stmt_expr;
21657 tsubst_stmt (STMT_EXPR_STMT (t), args, complain, in_decl);
21658 stmt_expr = finish_stmt_expr (stmt_expr, false);
21659 cur_stmt_expr = old_stmt_expr;
21661 /* If the resulting list of expression statement is empty,
21662 fold it further into void_node. */
21663 if (empty_expr_stmt_p (stmt_expr))
21664 stmt_expr = void_node;
21666 RETURN (stmt_expr);
21669 case LAMBDA_EXPR:
21671 if (complain & tf_partial)
21673 /* We don't have a full set of template arguments yet; don't touch
21674 the lambda at all. */
21675 gcc_assert (processing_template_decl);
21676 return t;
21678 tree r = tsubst_lambda_expr (t, args, complain, in_decl);
21680 RETURN (build_lambda_object (r));
21683 case TRANSACTION_EXPR:
21684 gcc_checking_assert (!TRANSACTION_EXPR_IS_STMT (t));
21685 RETURN (tsubst_stmt (t, args, complain, in_decl));
21687 case PAREN_EXPR:
21688 if (REF_PARENTHESIZED_P (t))
21689 RETURN (finish_parenthesized_expr (RECUR (TREE_OPERAND (t, 0))));
21690 else
21691 /* Recreate the PAREN_EXPR from __builtin_assoc_barrier. */
21693 tree op0 = RECUR (TREE_OPERAND (t, 0));
21694 RETURN (build1_loc (input_location, PAREN_EXPR,
21695 TREE_TYPE (op0), op0));
21698 case VEC_PERM_EXPR:
21700 tree op0 = RECUR (TREE_OPERAND (t, 0));
21701 tree op1 = RECUR (TREE_OPERAND (t, 1));
21702 tree op2 = RECUR (TREE_OPERAND (t, 2));
21703 RETURN (build_x_vec_perm_expr (input_location, op0, op1, op2,
21704 complain));
21707 case REQUIRES_EXPR:
21709 complain &= ~tf_warning_or_error;
21710 tree r = tsubst_requires_expr (t, args, complain, in_decl);
21711 RETURN (r);
21714 case RANGE_EXPR:
21715 /* No need to substitute further, a RANGE_EXPR will always be built
21716 with constant operands. */
21717 RETURN (t);
21719 case NON_LVALUE_EXPR:
21720 case VIEW_CONVERT_EXPR:
21722 tree op = RECUR (TREE_OPERAND (t, 0));
21724 if (location_wrapper_p (t))
21725 /* We need to do this here as well as in tsubst_copy so we get the
21726 other tsubst_copy_and_build semantics for a PARM_DECL operand. */
21727 RETURN (maybe_wrap_with_location (op, EXPR_LOCATION (t)));
21729 gcc_checking_assert (TREE_CODE (t) == VIEW_CONVERT_EXPR);
21730 if (REF_PARENTHESIZED_P (t))
21731 /* force_paren_expr can also create a VIEW_CONVERT_EXPR. */
21732 RETURN (finish_parenthesized_expr (op));
21734 /* Otherwise, we're dealing with a wrapper to make a C++20 template
21735 parameter object const. */
21736 if (TREE_TYPE (op) == NULL_TREE
21737 || !CP_TYPE_CONST_P (TREE_TYPE (op)))
21739 /* The template argument is not const, presumably because
21740 it is still dependent, and so not the const template parm
21741 object. */
21742 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
21743 if (TREE_CODE (op) == CONSTRUCTOR
21744 || TREE_CODE (op) == IMPLICIT_CONV_EXPR)
21746 /* Don't add a wrapper to these. */
21747 op = copy_node (op);
21748 TREE_TYPE (op) = type;
21750 else
21751 /* Do add a wrapper otherwise (in particular, if op is
21752 another TEMPLATE_PARM_INDEX). */
21753 op = build1 (VIEW_CONVERT_EXPR, type, op);
21755 RETURN (op);
21758 case ANNOTATE_EXPR:
21760 op1 = RECUR (TREE_OPERAND (t, 0));
21761 tree op2 = RECUR (TREE_OPERAND (t, 1));
21762 tree op3 = RECUR (TREE_OPERAND (t, 2));
21763 if (TREE_CODE (op2) == INTEGER_CST
21764 && wi::to_widest (op2) == (int) annot_expr_unroll_kind)
21765 op3 = cp_check_pragma_unroll (EXPR_LOCATION (TREE_OPERAND (t, 2)),
21766 op3);
21767 RETURN (build3_loc (EXPR_LOCATION (t), ANNOTATE_EXPR,
21768 TREE_TYPE (op1), op1, op2, op3));
21771 default:
21772 /* Handle Objective-C++ constructs, if appropriate. */
21773 if (tree subst = objcp_tsubst_expr (t, args, complain, in_decl))
21774 RETURN (subst);
21776 /* We shouldn't get here, but keep going if !flag_checking. */
21777 if (flag_checking)
21778 gcc_unreachable ();
21779 RETURN (t);
21782 #undef RECUR
21783 #undef RETURN
21784 out:
21785 input_location = save_loc;
21786 return retval;
21789 /* Verify that the instantiated ARGS are valid. For type arguments,
21790 make sure that the type's linkage is ok. For non-type arguments,
21791 make sure they are constants if they are integral or enumerations.
21792 Emit an error under control of COMPLAIN, and return TRUE on error. */
21794 static bool
21795 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
21797 if (dependent_template_arg_p (t))
21798 return false;
21799 if (ARGUMENT_PACK_P (t))
21801 tree vec = ARGUMENT_PACK_ARGS (t);
21802 int len = TREE_VEC_LENGTH (vec);
21803 bool result = false;
21804 int i;
21806 for (i = 0; i < len; ++i)
21807 if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
21808 result = true;
21809 return result;
21811 else if (TYPE_P (t))
21813 /* [basic.link]: A name with no linkage (notably, the name
21814 of a class or enumeration declared in a local scope)
21815 shall not be used to declare an entity with linkage.
21816 This implies that names with no linkage cannot be used as
21817 template arguments
21819 DR 757 relaxes this restriction for C++0x. */
21820 tree nt = (cxx_dialect > cxx98 ? NULL_TREE
21821 : no_linkage_check (t, /*relaxed_p=*/false));
21823 if (nt)
21825 /* DR 488 makes use of a type with no linkage cause
21826 type deduction to fail. */
21827 if (complain & tf_error)
21829 if (TYPE_UNNAMED_P (nt))
21830 error ("%qT is/uses unnamed type", t);
21831 else
21832 error ("template argument for %qD uses local type %qT",
21833 tmpl, t);
21835 return true;
21837 /* In order to avoid all sorts of complications, we do not
21838 allow variably-modified types as template arguments. */
21839 else if (variably_modified_type_p (t, NULL_TREE))
21841 if (complain & tf_error)
21842 error ("%qT is a variably modified type", t);
21843 return true;
21846 /* Class template and alias template arguments should be OK. */
21847 else if (DECL_TYPE_TEMPLATE_P (t))
21849 /* A non-type argument of integral or enumerated type must be a
21850 constant. */
21851 else if (TREE_TYPE (t)
21852 && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
21853 && !REFERENCE_REF_P (t)
21854 && !TREE_CONSTANT (t))
21856 if (complain & tf_error)
21857 error ("integral expression %qE is not constant", t);
21858 return true;
21860 return false;
21863 static bool
21864 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
21866 int ix, len = DECL_NTPARMS (tmpl);
21867 bool result = false;
21869 for (ix = 0; ix != len; ix++)
21871 if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
21872 result = true;
21874 if (result && (complain & tf_error))
21875 error (" trying to instantiate %qD", tmpl);
21876 return result;
21879 /* Call mark_used on each entity within the non-type template arguments in
21880 ARGS for an instantiation of TMPL, to ensure that each such entity is
21881 considered odr-used (and therefore marked for instantiation) regardless of
21882 whether the specialization was first formed in a template context (which
21883 inhibits mark_used).
21885 This function assumes push_to_top_level has been called beforehand. */
21887 static void
21888 mark_template_arguments_used (tree tmpl, tree args)
21890 /* It suffices to do this only when instantiating a primary template. */
21891 if (TREE_CODE (tmpl) != TEMPLATE_DECL || !PRIMARY_TEMPLATE_P (tmpl))
21892 return;
21894 /* We already marked outer arguments when specializing the context. */
21895 args = INNERMOST_TEMPLATE_ARGS (args);
21897 for (tree arg : tree_vec_range (args))
21899 /* A (pointer/reference to) function or variable NTTP argument. */
21900 if (TREE_CODE (arg) == ADDR_EXPR
21901 || TREE_CODE (arg) == INDIRECT_REF)
21903 while (TREE_CODE (arg) == ADDR_EXPR
21904 || REFERENCE_REF_P (arg)
21905 || CONVERT_EXPR_P (arg))
21906 arg = TREE_OPERAND (arg, 0);
21907 if (VAR_OR_FUNCTION_DECL_P (arg))
21909 /* Pass tf_none to avoid duplicate diagnostics: if this call
21910 fails then an earlier call to mark_used for this argument
21911 must have also failed and emitted a diagnostic. */
21912 bool ok = mark_used (arg, tf_none);
21913 gcc_checking_assert (ok || seen_error ());
21916 /* A class NTTP argument. */
21917 else if (VAR_P (arg)
21918 && DECL_NTTP_OBJECT_P (arg))
21920 auto mark_used_r = [](tree *tp, int *, void *) {
21921 if (VAR_OR_FUNCTION_DECL_P (*tp))
21923 bool ok = mark_used (*tp, tf_none);
21924 gcc_checking_assert (ok || seen_error ());
21926 return NULL_TREE;
21928 cp_walk_tree_without_duplicates (&DECL_INITIAL (arg),
21929 mark_used_r, nullptr);
21934 /* We're out of SFINAE context now, so generate diagnostics for the access
21935 errors we saw earlier when instantiating D from TMPL and ARGS. */
21937 static void
21938 recheck_decl_substitution (tree d, tree tmpl, tree args)
21940 tree pattern = DECL_TEMPLATE_RESULT (tmpl);
21941 tree type = TREE_TYPE (pattern);
21942 location_t loc = input_location;
21944 push_access_scope (d);
21945 push_deferring_access_checks (dk_no_deferred);
21946 input_location = DECL_SOURCE_LOCATION (pattern);
21947 tsubst (type, args, tf_warning_or_error, d);
21948 input_location = loc;
21949 pop_deferring_access_checks ();
21950 pop_access_scope (d);
21953 /* Instantiate the indicated variable, function, or alias template TMPL with
21954 the template arguments in TARG_PTR. */
21956 tree
21957 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
21959 auto_timevar tv (TV_TEMPLATE_INST);
21961 tree targ_ptr = orig_args;
21962 tree fndecl;
21963 tree gen_tmpl;
21964 bool access_ok = true;
21966 if (tmpl == error_mark_node)
21967 return error_mark_node;
21969 /* The other flags are not relevant anymore here, especially tf_partial
21970 shouldn't be set. For instance, we may be called while doing a partial
21971 substitution of a template variable, but the type of the variable
21972 template may be auto, in which case we will call do_auto_deduction
21973 in mark_used (which clears tf_partial) and the auto must be properly
21974 reduced at that time for the deduction to work. */
21975 complain &= tf_warning_or_error;
21977 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
21979 if (modules_p ())
21980 lazy_load_pendings (tmpl);
21982 /* If this function is a clone, handle it specially. */
21983 if (DECL_CLONED_FUNCTION_P (tmpl))
21985 tree spec;
21986 tree clone;
21988 /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
21989 DECL_CLONED_FUNCTION. */
21990 spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
21991 targ_ptr, complain);
21992 if (spec == error_mark_node)
21993 return error_mark_node;
21995 /* Look for the clone. */
21996 FOR_EACH_CLONE (clone, spec)
21997 if (DECL_NAME (clone) == DECL_NAME (tmpl))
21998 return clone;
21999 /* We should always have found the clone by now. */
22000 gcc_unreachable ();
22001 return NULL_TREE;
22004 if (targ_ptr == error_mark_node)
22005 return error_mark_node;
22007 /* Check to see if we already have this specialization. */
22008 gen_tmpl = most_general_template (tmpl);
22009 if (TMPL_ARGS_DEPTH (targ_ptr)
22010 < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)))
22011 /* targ_ptr only has the innermost template args, so add the outer ones
22012 from tmpl, which could be either a partial instantiation or gen_tmpl (in
22013 the case of a non-dependent call within a template definition). */
22014 targ_ptr = (add_outermost_template_args
22015 (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (tmpl)),
22016 targ_ptr));
22018 hashval_t hash = spec_hasher::hash (gen_tmpl, targ_ptr);
22019 tree spec = retrieve_specialization (gen_tmpl, targ_ptr, hash);
22021 gcc_checking_assert (tmpl == gen_tmpl
22022 || ((fndecl
22023 = retrieve_specialization (tmpl, orig_args, 0))
22024 == spec)
22025 || fndecl == NULL_TREE);
22027 if (spec != NULL_TREE)
22029 if (FNDECL_HAS_ACCESS_ERRORS (spec))
22031 if (complain & tf_error)
22032 recheck_decl_substitution (spec, gen_tmpl, targ_ptr);
22033 return error_mark_node;
22035 return spec;
22038 if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
22039 complain))
22040 return error_mark_node;
22042 /* We are building a FUNCTION_DECL, during which the access of its
22043 parameters and return types have to be checked. However this
22044 FUNCTION_DECL which is the desired context for access checking
22045 is not built yet. We solve this chicken-and-egg problem by
22046 deferring all checks until we have the FUNCTION_DECL. */
22047 push_deferring_access_checks (dk_deferred);
22049 /* Instantiation of the function happens in the context of the function
22050 template, not the context of the overload resolution we're doing. */
22051 push_to_top_level ();
22052 /* If there are dependent arguments, e.g. because we're doing partial
22053 ordering, make sure processing_template_decl stays set. */
22054 if (uses_template_parms (targ_ptr))
22055 ++processing_template_decl;
22056 if (DECL_CLASS_SCOPE_P (gen_tmpl))
22058 tree ctx;
22059 if (!uses_template_parms (DECL_CONTEXT (tmpl)))
22060 /* If the context of the partially instantiated template is
22061 already non-dependent, then we might as well use it. */
22062 ctx = DECL_CONTEXT (tmpl);
22063 else
22064 ctx = tsubst_aggr_type (DECL_CONTEXT (gen_tmpl), targ_ptr,
22065 complain, gen_tmpl, true);
22066 push_nested_class (ctx);
22069 tree pattern = DECL_TEMPLATE_RESULT (gen_tmpl);
22071 tree partial_ti = NULL_TREE;
22072 fndecl = NULL_TREE;
22073 if (VAR_P (pattern))
22075 /* We need to determine if we're using a partial or explicit
22076 specialization now, because the type of the variable could be
22077 different. */
22078 tree tid = build2 (TEMPLATE_ID_EXPR, NULL_TREE, tmpl, targ_ptr);
22079 partial_ti = most_specialized_partial_spec (tid, complain);
22080 if (partial_ti == error_mark_node)
22081 pattern = error_mark_node;
22082 else if (partial_ti)
22084 tree partial_tmpl = TI_TEMPLATE (partial_ti);
22085 tree partial_args = TI_ARGS (partial_ti);
22086 tree partial_pat = DECL_TEMPLATE_RESULT (partial_tmpl);
22087 fndecl = tsubst_decl (partial_pat, partial_args, complain,
22088 /*use_spec_table=*/false);
22092 /* Substitute template parameters to obtain the specialization. */
22093 if (fndecl == NULL_TREE)
22094 fndecl = tsubst_decl (pattern, targ_ptr, complain, /*use_spec_table=*/false);
22095 if (DECL_CLASS_SCOPE_P (gen_tmpl))
22096 pop_nested_class ();
22097 pop_from_top_level ();
22099 if (fndecl == error_mark_node)
22101 pop_deferring_access_checks ();
22102 return error_mark_node;
22105 /* The DECL_TI_TEMPLATE should always be the immediate parent
22106 template, not the most general template. */
22107 DECL_TI_TEMPLATE (fndecl) = tmpl;
22108 DECL_TI_ARGS (fndecl) = targ_ptr;
22109 if (VAR_P (pattern))
22111 /* Now that we we've formed this variable template specialization,
22112 remember the result of most_specialized_partial_spec for it. */
22113 TI_PARTIAL_INFO (DECL_TEMPLATE_INFO (fndecl)) = partial_ti;
22115 /* And remember if the variable was declared with []. */
22116 if (TREE_CODE (TREE_TYPE (fndecl)) == ARRAY_TYPE
22117 && TYPE_DOMAIN (TREE_TYPE (fndecl)) == NULL_TREE)
22118 SET_VAR_HAD_UNKNOWN_BOUND (fndecl);
22121 fndecl = register_specialization (fndecl, gen_tmpl, targ_ptr, false, hash);
22122 if (fndecl == error_mark_node)
22123 return error_mark_node;
22125 set_instantiating_module (fndecl);
22127 /* Now we know the specialization, compute access previously
22128 deferred. Do no access control for inheriting constructors,
22129 as we already checked access for the inherited constructor. */
22130 if (!(flag_new_inheriting_ctors
22131 && DECL_INHERITED_CTOR (fndecl)))
22133 push_access_scope (fndecl);
22134 if (!perform_deferred_access_checks (complain))
22135 access_ok = false;
22136 pop_access_scope (fndecl);
22138 pop_deferring_access_checks ();
22140 /* If we've just instantiated the main entry point for a function,
22141 instantiate all the alternate entry points as well. We do this
22142 by cloning the instantiation of the main entry point, not by
22143 instantiating the template clones. */
22144 if (tree chain = DECL_CHAIN (gen_tmpl))
22145 if (DECL_P (chain) && DECL_CLONED_FUNCTION_P (chain))
22146 clone_cdtor (fndecl, /*update_methods=*/false);
22148 if (!access_ok)
22150 if (!(complain & tf_error))
22152 /* Remember to reinstantiate when we're out of SFINAE so the user
22153 can see the errors. */
22154 FNDECL_HAS_ACCESS_ERRORS (fndecl) = true;
22156 return error_mark_node;
22159 return fndecl;
22162 /* Instantiate the alias template TMPL with ARGS. Also push a template
22163 instantiation level, which instantiate_template doesn't do because
22164 functions and variables have sufficient context established by the
22165 callers. */
22167 static tree
22168 instantiate_alias_template (tree tmpl, tree args, tsubst_flags_t complain)
22170 if (tmpl == error_mark_node || args == error_mark_node)
22171 return error_mark_node;
22173 args = coerce_template_parms (DECL_TEMPLATE_PARMS (tmpl),
22174 args, tmpl, complain);
22175 if (args == error_mark_node)
22176 return error_mark_node;
22178 /* FIXME check for satisfaction in check_instantiated_args. */
22179 if (!constraints_satisfied_p (tmpl, args))
22181 if (complain & tf_error)
22183 auto_diagnostic_group d;
22184 error ("template constraint failure for %qD", tmpl);
22185 diagnose_constraints (input_location, tmpl, args);
22187 return error_mark_node;
22190 if (!push_tinst_level (tmpl, args))
22191 return error_mark_node;
22192 tree r = instantiate_template (tmpl, args, complain);
22193 pop_tinst_level ();
22195 if (tree d = dependent_alias_template_spec_p (TREE_TYPE (r), nt_opaque))
22197 /* An alias template specialization can be dependent
22198 even if its underlying type is not. */
22199 TYPE_DEPENDENT_P (d) = true;
22200 TYPE_DEPENDENT_P_VALID (d) = true;
22201 /* Sometimes a dependent alias spec is equivalent to its expansion,
22202 sometimes not. So always use structural_comptypes. */
22203 SET_TYPE_STRUCTURAL_EQUALITY (d);
22206 return r;
22209 /* PARM is a template parameter pack for FN. Returns true iff
22210 PARM is used in a deducible way in the argument list of FN. */
22212 static bool
22213 pack_deducible_p (tree parm, tree fn)
22215 tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
22216 for (; t; t = TREE_CHAIN (t))
22218 tree type = TREE_VALUE (t);
22219 tree packs;
22220 if (!PACK_EXPANSION_P (type))
22221 continue;
22222 for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
22223 packs; packs = TREE_CHAIN (packs))
22224 if (template_args_equal (TREE_VALUE (packs), parm))
22226 /* The template parameter pack is used in a function parameter
22227 pack. If this is the end of the parameter list, the
22228 template parameter pack is deducible. */
22229 if (TREE_CHAIN (t) == void_list_node)
22230 return true;
22231 else
22232 /* Otherwise, not. Well, it could be deduced from
22233 a non-pack parameter, but doing so would end up with
22234 a deduction mismatch, so don't bother. */
22235 return false;
22238 /* The template parameter pack isn't used in any function parameter
22239 packs, but it might be used deeper, e.g. tuple<Args...>. */
22240 return true;
22243 /* Subroutine of fn_type_unification: check non-dependent parms for
22244 convertibility. */
22246 static int
22247 check_non_deducible_conversions (tree parms, const tree *args, unsigned nargs,
22248 tree fn, unification_kind_t strict, int flags,
22249 struct conversion **convs, bool explain_p,
22250 bool noninst_only_p)
22252 /* Non-constructor methods need to leave a conversion for 'this', which
22253 isn't included in nargs here. */
22254 unsigned offset = (DECL_IOBJ_MEMBER_FUNCTION_P (fn)
22255 && !DECL_CONSTRUCTOR_P (fn));
22257 for (unsigned ia = 0;
22258 parms && parms != void_list_node && ia < nargs; )
22260 tree parm = TREE_VALUE (parms);
22262 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
22263 && (!TREE_CHAIN (parms)
22264 || TREE_CHAIN (parms) == void_list_node))
22265 /* For a function parameter pack that occurs at the end of the
22266 parameter-declaration-list, the type A of each remaining
22267 argument of the call is compared with the type P of the
22268 declarator-id of the function parameter pack. */
22269 break;
22271 parms = TREE_CHAIN (parms);
22273 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
22274 /* For a function parameter pack that does not occur at the
22275 end of the parameter-declaration-list, the type of the
22276 parameter pack is a non-deduced context. */
22277 continue;
22279 if (!uses_template_parms (parm))
22281 tree arg = args[ia];
22282 conversion **conv_p = convs ? &convs[ia+offset] : NULL;
22283 int lflags = conv_flags (ia, nargs, fn, arg, flags);
22285 if (check_non_deducible_conversion (parm, arg, strict, lflags,
22286 conv_p, explain_p, noninst_only_p))
22287 return 1;
22290 ++ia;
22293 return 0;
22296 /* The FN is a TEMPLATE_DECL for a function. ARGS is an array with
22297 NARGS elements of the arguments that are being used when calling
22298 it. TARGS is a vector into which the deduced template arguments
22299 are placed.
22301 Returns either a FUNCTION_DECL for the matching specialization of FN or
22302 NULL_TREE if no suitable specialization can be found. If EXPLAIN_P is
22303 true, diagnostics will be printed to explain why it failed.
22305 If FN is a conversion operator, or we are trying to produce a specific
22306 specialization, RETURN_TYPE is the return type desired.
22308 The EXPLICIT_TARGS are explicit template arguments provided via a
22309 template-id.
22311 The parameter STRICT is one of:
22313 DEDUCE_CALL:
22314 We are deducing arguments for a function call, as in
22315 [temp.deduct.call]. If RETURN_TYPE is non-null, we are
22316 deducing arguments for a call to the result of a conversion
22317 function template, as in [over.call.object].
22319 DEDUCE_CONV:
22320 We are deducing arguments for a conversion function, as in
22321 [temp.deduct.conv].
22323 DEDUCE_EXACT:
22324 We are deducing arguments when doing an explicit instantiation
22325 as in [temp.explicit], when determining an explicit specialization
22326 as in [temp.expl.spec], or when taking the address of a function
22327 template, as in [temp.deduct.funcaddr]. */
22329 tree
22330 fn_type_unification (tree fn,
22331 tree explicit_targs,
22332 tree targs,
22333 const tree *args,
22334 unsigned int nargs,
22335 tree return_type,
22336 unification_kind_t strict,
22337 int flags,
22338 struct conversion **convs,
22339 bool explain_p,
22340 bool decltype_p)
22342 tree parms;
22343 tree fntype;
22344 tree decl = NULL_TREE;
22345 tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
22346 bool ok;
22347 static int deduction_depth;
22348 /* type_unification_real will pass back any access checks from default
22349 template argument substitution. */
22350 vec<deferred_access_check, va_gc> *checks = NULL;
22351 /* We don't have all the template args yet. */
22352 bool incomplete = true;
22354 tree orig_fn = fn;
22355 if (flag_new_inheriting_ctors)
22356 fn = strip_inheriting_ctors (fn);
22358 tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
22359 tree r = error_mark_node;
22361 tree full_targs = targs;
22362 if (TMPL_ARGS_DEPTH (targs)
22363 < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (fn)))
22364 full_targs = (add_outermost_template_args
22365 (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (fn)),
22366 targs));
22368 if (decltype_p)
22369 complain |= tf_decltype;
22371 /* In C++0x, it's possible to have a function template whose type depends
22372 on itself recursively. This is most obvious with decltype, but can also
22373 occur with enumeration scope (c++/48969). So we need to catch infinite
22374 recursion and reject the substitution at deduction time; this function
22375 will return error_mark_node for any repeated substitution.
22377 This also catches excessive recursion such as when f<N> depends on
22378 f<N-1> across all integers, and returns error_mark_node for all the
22379 substitutions back up to the initial one.
22381 This is, of course, not reentrant. */
22382 if (excessive_deduction_depth)
22383 return error_mark_node;
22384 ++deduction_depth;
22386 gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
22388 fntype = TREE_TYPE (fn);
22389 if (explicit_targs)
22391 /* [temp.deduct]
22393 The specified template arguments must match the template
22394 parameters in kind (i.e., type, nontype, template), and there
22395 must not be more arguments than there are parameters;
22396 otherwise type deduction fails.
22398 Nontype arguments must match the types of the corresponding
22399 nontype template parameters, or must be convertible to the
22400 types of the corresponding nontype parameters as specified in
22401 _temp.arg.nontype_, otherwise type deduction fails.
22403 All references in the function type of the function template
22404 to the corresponding template parameters are replaced by the
22405 specified template argument values. If a substitution in a
22406 template parameter or in the function type of the function
22407 template results in an invalid type, type deduction fails. */
22408 int i, len = TREE_VEC_LENGTH (tparms);
22409 location_t loc = input_location;
22410 incomplete = false;
22412 if (explicit_targs == error_mark_node)
22413 goto fail;
22415 if (TMPL_ARGS_DEPTH (explicit_targs)
22416 < TMPL_ARGS_DEPTH (full_targs))
22417 explicit_targs = add_outermost_template_args (full_targs,
22418 explicit_targs);
22420 /* Adjust any explicit template arguments before entering the
22421 substitution context. */
22422 explicit_targs
22423 = (coerce_template_parms (tparms, explicit_targs, fn,
22424 complain|tf_partial,
22425 /*require_all_args=*/false));
22426 if (explicit_targs == error_mark_node)
22427 goto fail;
22429 /* Substitute the explicit args into the function type. This is
22430 necessary so that, for instance, explicitly declared function
22431 arguments can match null pointed constants. If we were given
22432 an incomplete set of explicit args, we must not do semantic
22433 processing during substitution as we could create partial
22434 instantiations. */
22435 for (i = 0; i < len; i++)
22437 tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
22438 bool parameter_pack = false;
22439 tree targ = TREE_VEC_ELT (explicit_targs, i);
22441 /* Dig out the actual parm. */
22442 if (TREE_CODE (parm) == TYPE_DECL
22443 || TREE_CODE (parm) == TEMPLATE_DECL)
22445 parm = TREE_TYPE (parm);
22446 parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
22448 else if (TREE_CODE (parm) == PARM_DECL)
22450 parm = DECL_INITIAL (parm);
22451 parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
22454 if (targ == NULL_TREE)
22455 /* No explicit argument for this template parameter. */
22456 incomplete = true;
22457 else if (parameter_pack && pack_deducible_p (parm, fn))
22459 /* Mark the argument pack as "incomplete". We could
22460 still deduce more arguments during unification.
22461 We remove this mark in type_unification_real. */
22462 ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
22463 ARGUMENT_PACK_EXPLICIT_ARGS (targ)
22464 = ARGUMENT_PACK_ARGS (targ);
22466 /* We have some incomplete argument packs. */
22467 incomplete = true;
22471 if (incomplete)
22473 if (!push_tinst_level (fn, explicit_targs))
22475 excessive_deduction_depth = true;
22476 goto fail;
22478 ++processing_template_decl;
22479 input_location = DECL_SOURCE_LOCATION (fn);
22480 /* Ignore any access checks; we'll see them again in
22481 instantiate_template and they might have the wrong
22482 access path at this point. */
22483 push_deferring_access_checks (dk_deferred);
22484 tsubst_flags_t ecomplain = complain | tf_partial | tf_fndecl_type;
22485 fntype = tsubst (TREE_TYPE (fn), explicit_targs, ecomplain, NULL_TREE);
22486 pop_deferring_access_checks ();
22487 input_location = loc;
22488 --processing_template_decl;
22489 pop_tinst_level ();
22491 if (fntype == error_mark_node)
22492 goto fail;
22495 /* Place the explicitly specified arguments in TARGS. */
22496 explicit_targs = INNERMOST_TEMPLATE_ARGS (explicit_targs);
22497 for (i = NUM_TMPL_ARGS (explicit_targs); i--;)
22498 TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (explicit_targs, i);
22499 if (!incomplete && CHECKING_P
22500 && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
22501 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
22502 (targs, NUM_TMPL_ARGS (explicit_targs));
22505 if (return_type && strict != DEDUCE_CALL)
22507 tree *new_args = XALLOCAVEC (tree, nargs + 1);
22508 new_args[0] = return_type;
22509 memcpy (new_args + 1, args, nargs * sizeof (tree));
22510 args = new_args;
22511 ++nargs;
22514 if (!incomplete)
22515 goto deduced;
22517 /* Never do unification on the 'this' parameter. */
22518 parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
22520 if (return_type && strict == DEDUCE_CALL)
22522 /* We're deducing for a call to the result of a template conversion
22523 function. The parms we really want are in return_type. */
22524 if (INDIRECT_TYPE_P (return_type))
22525 return_type = TREE_TYPE (return_type);
22526 parms = TYPE_ARG_TYPES (return_type);
22528 else if (return_type)
22530 parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
22533 /* We allow incomplete unification without an error message here
22534 because the standard doesn't seem to explicitly prohibit it. Our
22535 callers must be ready to deal with unification failures in any
22536 event. */
22538 /* If we aren't explaining yet, push tinst context so we can see where
22539 any errors (e.g. from class instantiations triggered by instantiation
22540 of default template arguments) come from. If we are explaining, this
22541 context is redundant. */
22542 if (!explain_p && !push_tinst_level (fn, targs))
22544 excessive_deduction_depth = true;
22545 goto fail;
22548 ok = !type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
22549 full_targs, parms, args, nargs, /*subr=*/0,
22550 strict, &checks, explain_p);
22551 if (!explain_p)
22552 pop_tinst_level ();
22553 if (!ok)
22554 goto fail;
22556 /* Now that we have bindings for all of the template arguments,
22557 ensure that the arguments deduced for the template template
22558 parameters have compatible template parameter lists. We cannot
22559 check this property before we have deduced all template
22560 arguments, because the template parameter types of a template
22561 template parameter might depend on prior template parameters
22562 deduced after the template template parameter. The following
22563 ill-formed example illustrates this issue:
22565 template<typename T, template<T> class C> void f(C<5>, T);
22567 template<int N> struct X {};
22569 void g() {
22570 f(X<5>(), 5l); // error: template argument deduction fails
22573 The template parameter list of 'C' depends on the template type
22574 parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
22575 'long'. Thus, we can't check that 'C' cannot bind to 'X' at the
22576 time that we deduce 'C'. */
22577 if (!template_template_parm_bindings_ok_p
22578 (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
22580 unify_inconsistent_template_template_parameters (explain_p);
22581 goto fail;
22584 deduced:
22586 /* As a refinement of CWG2369, check first and foremost non-dependent
22587 conversions that we know are not going to induce template instantiation
22588 (PR99599). */
22589 if (strict == DEDUCE_CALL
22590 && incomplete
22591 && check_non_deducible_conversions (parms, args, nargs, fn, strict, flags,
22592 convs, explain_p,
22593 /*noninst_only_p=*/true))
22594 goto fail;
22596 /* CWG2369: Check satisfaction before non-deducible conversions. */
22597 if (!constraints_satisfied_p (fn, targs))
22599 if (explain_p)
22600 diagnose_constraints (DECL_SOURCE_LOCATION (fn), fn, targs);
22601 goto fail;
22604 /* DR 1391: All parameters have args, now check non-dependent parms for
22605 convertibility. We don't do this if all args were explicitly specified,
22606 as the standard says that we substitute explicit args immediately. */
22607 if (incomplete
22608 && check_non_deducible_conversions (parms, args, nargs, fn, strict, flags,
22609 convs, explain_p,
22610 /*noninst_only_p=*/false))
22611 goto fail;
22613 /* All is well so far. Now, check:
22615 [temp.deduct]
22617 When all template arguments have been deduced, all uses of
22618 template parameters in nondeduced contexts are replaced with
22619 the corresponding deduced argument values. If the
22620 substitution results in an invalid type, as described above,
22621 type deduction fails. */
22622 if (!push_tinst_level (fn, targs))
22624 excessive_deduction_depth = true;
22625 goto fail;
22628 /* Also collect access checks from the instantiation. */
22629 reopen_deferring_access_checks (checks);
22631 decl = instantiate_template (fn, targs, complain);
22633 checks = get_deferred_access_checks ();
22634 pop_deferring_access_checks ();
22636 pop_tinst_level ();
22638 if (decl == error_mark_node)
22639 goto fail;
22641 /* Now perform any access checks encountered during substitution. */
22642 push_access_scope (decl);
22643 ok = perform_access_checks (checks, complain);
22644 pop_access_scope (decl);
22645 if (!ok)
22646 goto fail;
22648 /* If we're looking for an exact match, check that what we got
22649 is indeed an exact match. It might not be if some template
22650 parameters are used in non-deduced contexts. But don't check
22651 for an exact match if we have dependent template arguments;
22652 in that case we're doing partial ordering, and we already know
22653 that we have two candidates that will provide the actual type. */
22654 if (strict == DEDUCE_EXACT && !any_dependent_template_arguments_p (targs))
22656 tree substed = TREE_TYPE (decl);
22657 unsigned int i;
22659 tree sarg
22660 = skip_artificial_parms_for (decl, TYPE_ARG_TYPES (substed));
22661 if (return_type)
22662 sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
22663 for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
22664 if (!same_type_p (args[i], TREE_VALUE (sarg)))
22666 unify_type_mismatch (explain_p, args[i],
22667 TREE_VALUE (sarg));
22668 goto fail;
22670 if ((i < nargs || sarg)
22671 /* add_candidates uses DEDUCE_EXACT for x.operator foo(), but args
22672 doesn't contain the trailing void, and conv fns are always (). */
22673 && !DECL_CONV_FN_P (decl))
22675 unsigned nsargs = i + list_length (sarg);
22676 unify_arity (explain_p, nargs, nsargs);
22677 goto fail;
22681 /* After doing deduction with the inherited constructor, actually return an
22682 instantiation of the inheriting constructor. */
22683 if (orig_fn != fn)
22684 decl = instantiate_template (orig_fn, targs, complain);
22686 r = decl;
22688 fail:
22689 --deduction_depth;
22690 if (excessive_deduction_depth)
22692 if (deduction_depth == 0)
22693 /* Reset once we're all the way out. */
22694 excessive_deduction_depth = false;
22697 return r;
22700 /* Returns true iff PARM is a forwarding reference in the context of
22701 template argument deduction for TMPL. */
22703 static bool
22704 forwarding_reference_p (tree parm, tree tmpl)
22706 /* [temp.deduct.call], "A forwarding reference is an rvalue reference to a
22707 cv-unqualified template parameter ..." */
22708 if (TYPE_REF_P (parm)
22709 && TYPE_REF_IS_RVALUE (parm)
22710 && TREE_CODE (TREE_TYPE (parm)) == TEMPLATE_TYPE_PARM
22711 && cp_type_quals (TREE_TYPE (parm)) == TYPE_UNQUALIFIED)
22713 parm = TREE_TYPE (parm);
22714 /* [temp.deduct.call], "... that does not represent a template parameter
22715 of a class template (during class template argument deduction)." */
22716 if (tmpl
22717 && deduction_guide_p (tmpl)
22718 && DECL_ARTIFICIAL (tmpl))
22720 /* Since the template parameters of a synthesized guide consist of
22721 the template parameters of the class template followed by those of
22722 the constructor (if any), we can tell if PARM represents a template
22723 parameter of the class template by comparing its index with the
22724 arity of the class template. */
22725 tree ctmpl = CLASSTYPE_TI_TEMPLATE (TREE_TYPE (TREE_TYPE (tmpl)));
22726 if (TEMPLATE_TYPE_IDX (parm)
22727 < TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (ctmpl)))
22728 return false;
22730 return true;
22732 return false;
22735 /* Adjust types before performing type deduction, as described in
22736 [temp.deduct.call] and [temp.deduct.conv]. The rules in these two
22737 sections are symmetric. PARM is the type of a function parameter
22738 or the return type of the conversion function. ARG is the type of
22739 the argument passed to the call, or the type of the value
22740 initialized with the result of the conversion function.
22741 ARG_EXPR is the original argument expression, which may be null. */
22743 static int
22744 maybe_adjust_types_for_deduction (tree tparms,
22745 unification_kind_t strict,
22746 tree* parm,
22747 tree* arg,
22748 tree arg_expr)
22750 int result = 0;
22752 switch (strict)
22754 case DEDUCE_CALL:
22755 break;
22757 case DEDUCE_CONV:
22758 /* [temp.deduct.conv] First remove a reference type on parm.
22759 DRs 322 & 976 affected this. */
22760 if (TYPE_REF_P (*parm))
22761 *parm = TREE_TYPE (*parm);
22763 /* Swap PARM and ARG throughout the remainder of this
22764 function; the handling is precisely symmetric since PARM
22765 will initialize ARG rather than vice versa. */
22766 std::swap (parm, arg);
22768 break;
22770 case DEDUCE_EXACT:
22771 /* Core issue #873: Do the DR606 thing (see below) for these cases,
22772 too, but here handle it by stripping the reference from PARM
22773 rather than by adding it to ARG. */
22774 if (forwarding_reference_p (*parm, TPARMS_PRIMARY_TEMPLATE (tparms))
22775 && TYPE_REF_P (*arg)
22776 && !TYPE_REF_IS_RVALUE (*arg))
22777 *parm = TREE_TYPE (*parm);
22778 /* Nothing else to do in this case. */
22779 return 0;
22781 default:
22782 gcc_unreachable ();
22785 if (!TYPE_REF_P (*parm))
22787 /* [temp.deduct.call]
22789 If P is not a reference type:
22791 --If A is an array type, the pointer type produced by the
22792 array-to-pointer standard conversion (_conv.array_) is
22793 used in place of A for type deduction; otherwise,
22795 --If A is a function type, the pointer type produced by
22796 the function-to-pointer standard conversion
22797 (_conv.func_) is used in place of A for type deduction;
22798 otherwise,
22800 --If A is a cv-qualified type, the top level
22801 cv-qualifiers of A's type are ignored for type
22802 deduction. */
22803 if (TREE_CODE (*arg) == ARRAY_TYPE)
22804 *arg = build_pointer_type (TREE_TYPE (*arg));
22805 else if (TREE_CODE (*arg) == FUNCTION_TYPE)
22806 *arg = build_pointer_type (*arg);
22807 else
22808 *arg = TYPE_MAIN_VARIANT (*arg);
22811 /* [temp.deduct.call], "If P is a forwarding reference and the argument is
22812 an lvalue, the type 'lvalue reference to A' is used in place of A for
22813 type deduction." */
22814 if (forwarding_reference_p (*parm, TPARMS_PRIMARY_TEMPLATE (tparms))
22815 && (arg_expr ? lvalue_p (arg_expr)
22816 /* try_one_overload doesn't provide an arg_expr, but
22817 functions are always lvalues. */
22818 : TREE_CODE (*arg) == FUNCTION_TYPE))
22819 *arg = build_reference_type (*arg);
22821 /* [temp.deduct.call]
22823 If P is a cv-qualified type, the top level cv-qualifiers
22824 of P's type are ignored for type deduction. If P is a
22825 reference type, the type referred to by P is used for
22826 type deduction. */
22827 *parm = TYPE_MAIN_VARIANT (*parm);
22828 if (TYPE_REF_P (*parm))
22830 *parm = TREE_TYPE (*parm);
22831 result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
22834 return result;
22837 /* Return true if computing a conversion from FROM to TO might induce template
22838 instantiation. Conversely, if this predicate returns false then computing
22839 the conversion definitely won't induce template instantiation. */
22841 static bool
22842 conversion_may_instantiate_p (tree to, tree from)
22844 to = non_reference (to);
22845 from = non_reference (from);
22847 bool ptr_conv_p = false;
22848 if (TYPE_PTR_P (to)
22849 && TYPE_PTR_P (from))
22851 to = TREE_TYPE (to);
22852 from = TREE_TYPE (from);
22853 ptr_conv_p = true;
22856 /* If one of the types is a not-yet-instantiated class template
22857 specialization, then computing the conversion might instantiate
22858 it in order to inspect bases, conversion functions and/or
22859 converting constructors. */
22860 if ((CLASS_TYPE_P (to)
22861 && !COMPLETE_TYPE_P (to)
22862 && CLASSTYPE_TEMPLATE_INSTANTIATION (to))
22863 || (CLASS_TYPE_P (from)
22864 && !COMPLETE_TYPE_P (from)
22865 && CLASSTYPE_TEMPLATE_INSTANTIATION (from)))
22866 return true;
22868 /* Converting from one pointer type to another, or between
22869 reference-related types, always yields a standard conversion. */
22870 if (ptr_conv_p || reference_related_p (to, from))
22871 return false;
22873 /* Converting to a non-aggregate class type will consider its
22874 user-declared constructors, which might induce instantiation. */
22875 if (CLASS_TYPE_P (to)
22876 && CLASSTYPE_NON_AGGREGATE (to))
22877 return true;
22879 /* Similarly, converting from a class type will consider its conversion
22880 functions. */
22881 if (CLASS_TYPE_P (from)
22882 && TYPE_HAS_CONVERSION (from))
22883 return true;
22885 /* Otherwise, computing this conversion definitely won't induce
22886 template instantiation. */
22887 return false;
22890 /* Subroutine of fn_type_unification. PARM is a function parameter of a
22891 template which doesn't contain any deducible template parameters; check if
22892 ARG is a suitable match for it. STRICT, FLAGS and EXPLAIN_P are as in
22893 unify_one_argument. */
22895 static int
22896 check_non_deducible_conversion (tree parm, tree arg, unification_kind_t strict,
22897 int flags, struct conversion **conv_p,
22898 bool explain_p, bool noninst_only_p)
22900 tree type;
22902 if (!TYPE_P (arg))
22903 type = TREE_TYPE (arg);
22904 else
22905 type = arg;
22907 if (same_type_p (parm, type))
22908 return unify_success (explain_p);
22910 tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
22911 if (strict == DEDUCE_CONV)
22913 if (can_convert_arg (type, parm, NULL_TREE, flags, complain))
22914 return unify_success (explain_p);
22916 else if (strict == DEDUCE_CALL)
22918 if (conv_p && *conv_p)
22920 /* This conversion was already computed earlier (when
22921 computing only non-instantiating conversions). */
22922 gcc_checking_assert (!noninst_only_p);
22923 return unify_success (explain_p);
22926 if (noninst_only_p
22927 && conversion_may_instantiate_p (parm, type))
22928 return unify_success (explain_p);
22930 bool ok = false;
22931 tree conv_arg = TYPE_P (arg) ? NULL_TREE : arg;
22932 if (conv_p)
22933 /* Avoid recalculating this in add_function_candidate. */
22934 ok = (*conv_p
22935 = good_conversion (parm, type, conv_arg, flags, complain));
22936 else
22937 ok = can_convert_arg (parm, type, conv_arg, flags, complain);
22938 if (ok)
22939 return unify_success (explain_p);
22942 if (strict == DEDUCE_EXACT)
22943 return unify_type_mismatch (explain_p, parm, arg);
22944 else
22945 return unify_arg_conversion (explain_p, parm, type, arg);
22948 static bool uses_deducible_template_parms (tree type);
22950 /* Returns true iff the expression EXPR is one from which a template
22951 argument can be deduced. In other words, if it's an undecorated
22952 use of a template non-type parameter. */
22954 static bool
22955 deducible_expression (tree expr)
22957 /* Strip implicit conversions and implicit INDIRECT_REFs. */
22958 while (CONVERT_EXPR_P (expr)
22959 || TREE_CODE (expr) == VIEW_CONVERT_EXPR
22960 || REFERENCE_REF_P (expr))
22961 expr = TREE_OPERAND (expr, 0);
22962 return (TREE_CODE (expr) == TEMPLATE_PARM_INDEX);
22965 /* Returns true iff the array domain DOMAIN uses a template parameter in a
22966 deducible way; that is, if it has a max value of <PARM> - 1. */
22968 static bool
22969 deducible_array_bound (tree domain)
22971 if (domain == NULL_TREE)
22972 return false;
22974 tree max = TYPE_MAX_VALUE (domain);
22975 if (TREE_CODE (max) != MINUS_EXPR)
22976 return false;
22978 return deducible_expression (TREE_OPERAND (max, 0));
22981 /* Returns true iff the template arguments ARGS use a template parameter
22982 in a deducible way. */
22984 static bool
22985 deducible_template_args (tree args)
22987 for (tree elt : tree_vec_range (args))
22989 bool deducible;
22990 if (ARGUMENT_PACK_P (elt))
22991 deducible = deducible_template_args (ARGUMENT_PACK_ARGS (elt));
22992 else
22994 if (PACK_EXPANSION_P (elt))
22995 elt = PACK_EXPANSION_PATTERN (elt);
22996 if (TREE_CODE (elt) == TEMPLATE_TEMPLATE_PARM)
22997 deducible = true;
22998 else if (TYPE_P (elt))
22999 deducible = uses_deducible_template_parms (elt);
23000 else
23001 deducible = deducible_expression (elt);
23003 if (deducible)
23004 return true;
23006 return false;
23009 /* Returns true iff TYPE contains any deducible references to template
23010 parameters, as per 14.8.2.5. */
23012 static bool
23013 uses_deducible_template_parms (tree type)
23015 if (PACK_EXPANSION_P (type))
23016 type = PACK_EXPANSION_PATTERN (type);
23018 /* T
23019 cv-list T
23020 TT<T>
23021 TT<i>
23022 TT<> */
23023 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
23024 || TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
23025 return true;
23027 /* T*
23029 T&& */
23030 if (INDIRECT_TYPE_P (type))
23031 return uses_deducible_template_parms (TREE_TYPE (type));
23033 /* T[integer-constant ]
23034 type [i] */
23035 if (TREE_CODE (type) == ARRAY_TYPE)
23036 return (uses_deducible_template_parms (TREE_TYPE (type))
23037 || deducible_array_bound (TYPE_DOMAIN (type)));
23039 /* T type ::*
23040 type T::*
23041 T T::*
23042 T (type ::*)()
23043 type (T::*)()
23044 type (type ::*)(T)
23045 type (T::*)(T)
23046 T (type ::*)(T)
23047 T (T::*)()
23048 T (T::*)(T) */
23049 if (TYPE_PTRMEM_P (type))
23050 return (uses_deducible_template_parms (TYPE_PTRMEM_CLASS_TYPE (type))
23051 || (uses_deducible_template_parms
23052 (TYPE_PTRMEM_POINTED_TO_TYPE (type))));
23054 /* template-name <T> (where template-name refers to a class template)
23055 template-name <i> (where template-name refers to a class template) */
23056 if (CLASS_TYPE_P (type)
23057 && CLASSTYPE_TEMPLATE_INFO (type)
23058 && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type)))
23059 return deducible_template_args (INNERMOST_TEMPLATE_ARGS
23060 (CLASSTYPE_TI_ARGS (type)));
23062 /* type (T)
23064 T(T) */
23065 if (FUNC_OR_METHOD_TYPE_P (type))
23067 if (uses_deducible_template_parms (TREE_TYPE (type)))
23068 return true;
23069 tree parm = TYPE_ARG_TYPES (type);
23070 if (TREE_CODE (type) == METHOD_TYPE)
23071 parm = TREE_CHAIN (parm);
23072 for (; parm; parm = TREE_CHAIN (parm))
23073 if (uses_deducible_template_parms (TREE_VALUE (parm)))
23074 return true;
23075 if (flag_noexcept_type
23076 && TYPE_RAISES_EXCEPTIONS (type)
23077 && TREE_PURPOSE (TYPE_RAISES_EXCEPTIONS (type))
23078 && deducible_expression (TREE_PURPOSE (TYPE_RAISES_EXCEPTIONS (type))))
23079 return true;
23082 return false;
23085 /* Subroutine of type_unification_real and unify_pack_expansion to
23086 handle unification of a single P/A pair. Parameters are as
23087 for those functions. */
23089 static int
23090 unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
23091 int subr, unification_kind_t strict,
23092 bool explain_p)
23094 tree arg_expr = NULL_TREE;
23095 int arg_strict;
23097 if (arg == error_mark_node || parm == error_mark_node)
23098 return unify_invalid (explain_p);
23099 if (arg == unknown_type_node)
23100 /* We can't deduce anything from this, but we might get all the
23101 template args from other function args. */
23102 return unify_success (explain_p);
23104 /* Implicit conversions (Clause 4) will be performed on a function
23105 argument to convert it to the type of the corresponding function
23106 parameter if the parameter type contains no template-parameters that
23107 participate in template argument deduction. */
23108 if (strict != DEDUCE_EXACT
23109 && TYPE_P (parm) && !uses_deducible_template_parms (parm))
23110 /* For function parameters with no deducible template parameters,
23111 just return. We'll check non-dependent conversions later. */
23112 return unify_success (explain_p);
23114 switch (strict)
23116 case DEDUCE_CALL:
23117 arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
23118 | UNIFY_ALLOW_MORE_CV_QUAL
23119 | UNIFY_ALLOW_DERIVED);
23120 break;
23122 case DEDUCE_CONV:
23123 arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
23124 break;
23126 case DEDUCE_EXACT:
23127 arg_strict = UNIFY_ALLOW_NONE;
23128 break;
23130 default:
23131 gcc_unreachable ();
23134 /* We only do these transformations if this is the top-level
23135 parameter_type_list in a call or declaration matching; in other
23136 situations (nested function declarators, template argument lists) we
23137 won't be comparing a type to an expression, and we don't do any type
23138 adjustments. */
23139 if (!subr)
23141 if (!TYPE_P (arg))
23143 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
23144 if (type_unknown_p (arg))
23146 /* [temp.deduct.type] A template-argument can be
23147 deduced from a pointer to function or pointer
23148 to member function argument if the set of
23149 overloaded functions does not contain function
23150 templates and at most one of a set of
23151 overloaded functions provides a unique
23152 match. */
23153 resolve_overloaded_unification (tparms, targs, parm,
23154 arg, strict,
23155 arg_strict, explain_p);
23156 /* If a unique match was not found, this is a
23157 non-deduced context, so we still succeed. */
23158 return unify_success (explain_p);
23161 arg_expr = arg;
23162 arg = unlowered_expr_type (arg);
23163 if (arg == error_mark_node)
23164 return unify_invalid (explain_p);
23167 arg_strict |= maybe_adjust_types_for_deduction (tparms, strict,
23168 &parm, &arg, arg_expr);
23170 else
23171 if ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
23172 != (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL))
23173 return unify_template_argument_mismatch (explain_p, parm, arg);
23175 /* For deduction from an init-list we need the actual list. */
23176 if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
23177 arg = arg_expr;
23178 return unify (tparms, targs, parm, arg, arg_strict, explain_p);
23181 /* for_each_template_parm callback that always returns 0. */
23183 static int
23184 zero_r (tree, void *)
23186 return 0;
23189 /* for_each_template_parm any_fn callback to handle deduction of a template
23190 type argument from the type of an array bound. */
23192 static int
23193 array_deduction_r (tree t, void *data)
23195 tree_pair_p d = (tree_pair_p)data;
23196 tree &tparms = d->purpose;
23197 tree &targs = d->value;
23199 if (TREE_CODE (t) == ARRAY_TYPE)
23200 if (tree dom = TYPE_DOMAIN (t))
23201 if (tree max = TYPE_MAX_VALUE (dom))
23203 if (TREE_CODE (max) == MINUS_EXPR)
23204 max = TREE_OPERAND (max, 0);
23205 if (TREE_CODE (max) == TEMPLATE_PARM_INDEX)
23206 unify (tparms, targs, TREE_TYPE (max), size_type_node,
23207 UNIFY_ALLOW_NONE, /*explain*/false);
23210 /* Keep walking. */
23211 return 0;
23214 /* Try to deduce any not-yet-deduced template type arguments from the type of
23215 an array bound. This is handled separately from unify because 14.8.2.5 says
23216 "The type of a type parameter is only deduced from an array bound if it is
23217 not otherwise deduced." */
23219 static void
23220 try_array_deduction (tree tparms, tree targs, tree parm)
23222 tree_pair_s data = { tparms, targs };
23223 hash_set<tree> visited;
23224 for_each_template_parm (parm, zero_r, &data, &visited,
23225 /*nondeduced*/false, array_deduction_r);
23228 /* Most parms like fn_type_unification.
23230 If SUBR is 1, we're being called recursively (to unify the
23231 arguments of a function or method parameter of a function
23232 template).
23234 CHECKS is a pointer to a vector of access checks encountered while
23235 substituting default template arguments. */
23237 static int
23238 type_unification_real (tree tparms,
23239 tree full_targs,
23240 tree xparms,
23241 const tree *xargs,
23242 unsigned int xnargs,
23243 int subr,
23244 unification_kind_t strict,
23245 vec<deferred_access_check, va_gc> **checks,
23246 bool explain_p)
23248 tree parm, arg;
23249 int i;
23250 int ntparms = TREE_VEC_LENGTH (tparms);
23251 int saw_undeduced = 0;
23252 tree parms;
23253 const tree *args;
23254 unsigned int nargs;
23255 unsigned int ia;
23257 gcc_assert (TREE_CODE (tparms) == TREE_VEC);
23258 gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
23259 gcc_assert (ntparms > 0);
23261 tree targs = INNERMOST_TEMPLATE_ARGS (full_targs);
23263 /* Reset the number of non-defaulted template arguments contained
23264 in TARGS. */
23265 NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
23267 again:
23268 parms = xparms;
23269 args = xargs;
23270 nargs = xnargs;
23272 /* Only fn_type_unification cares about terminal void. */
23273 if (nargs && args[nargs-1] == void_type_node)
23274 --nargs;
23276 ia = 0;
23277 while (parms && parms != void_list_node
23278 && ia < nargs)
23280 parm = TREE_VALUE (parms);
23282 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
23283 && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
23284 /* For a function parameter pack that occurs at the end of the
23285 parameter-declaration-list, the type A of each remaining
23286 argument of the call is compared with the type P of the
23287 declarator-id of the function parameter pack. */
23288 break;
23290 parms = TREE_CHAIN (parms);
23292 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
23293 /* For a function parameter pack that does not occur at the
23294 end of the parameter-declaration-list, the type of the
23295 parameter pack is a non-deduced context. */
23296 continue;
23298 arg = args[ia];
23299 ++ia;
23301 if (unify_one_argument (tparms, full_targs, parm, arg, subr, strict,
23302 explain_p))
23303 return 1;
23306 if (parms
23307 && parms != void_list_node
23308 && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
23310 /* Unify the remaining arguments with the pack expansion type. */
23311 tree argvec;
23312 tree parmvec = make_tree_vec (1);
23314 /* Allocate a TREE_VEC and copy in all of the arguments */
23315 argvec = make_tree_vec (nargs - ia);
23316 for (i = 0; ia < nargs; ++ia, ++i)
23317 TREE_VEC_ELT (argvec, i) = args[ia];
23319 /* Copy the parameter into parmvec. */
23320 TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
23321 if (unify_pack_expansion (tparms, full_targs, parmvec, argvec, strict,
23322 /*subr=*/subr, explain_p))
23323 return 1;
23325 /* Advance to the end of the list of parameters. */
23326 parms = TREE_CHAIN (parms);
23329 /* Fail if we've reached the end of the parm list, and more args
23330 are present, and the parm list isn't variadic. */
23331 if (ia < nargs && parms == void_list_node)
23332 return unify_too_many_arguments (explain_p, nargs, ia);
23333 /* Fail if parms are left and they don't have default values and
23334 they aren't all deduced as empty packs (c++/57397). This is
23335 consistent with sufficient_parms_p. */
23336 if (parms && parms != void_list_node
23337 && TREE_PURPOSE (parms) == NULL_TREE)
23339 unsigned int count = nargs;
23340 tree p = parms;
23341 bool type_pack_p;
23344 type_pack_p = TREE_CODE (TREE_VALUE (p)) == TYPE_PACK_EXPANSION;
23345 if (!type_pack_p)
23346 count++;
23347 p = TREE_CHAIN (p);
23349 while (p && p != void_list_node);
23350 if (count != nargs)
23351 return unify_too_few_arguments (explain_p, ia, count,
23352 type_pack_p);
23355 if (!subr)
23357 tsubst_flags_t complain = (explain_p
23358 ? tf_warning_or_error
23359 : tf_none);
23360 bool tried_array_deduction = (cxx_dialect < cxx17);
23362 for (i = 0; i < ntparms; i++)
23364 tree targ = TREE_VEC_ELT (targs, i);
23365 tree tparm = TREE_VEC_ELT (tparms, i);
23367 /* Clear the "incomplete" flags on all argument packs now so that
23368 substituting them into later default arguments works. */
23369 if (targ && ARGUMENT_PACK_P (targ))
23371 ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
23372 ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
23375 if (targ || tparm == error_mark_node)
23376 continue;
23377 tparm = TREE_VALUE (tparm);
23379 if (TREE_CODE (tparm) == TYPE_DECL
23380 && !tried_array_deduction)
23382 try_array_deduction (tparms, targs, xparms);
23383 tried_array_deduction = true;
23384 if (TREE_VEC_ELT (targs, i))
23385 continue;
23388 /* If this is an undeduced nontype parameter that depends on
23389 a type parameter, try another pass; its type may have been
23390 deduced from a later argument than the one from which
23391 this parameter can be deduced. */
23392 if (TREE_CODE (tparm) == PARM_DECL
23393 && !is_auto (TREE_TYPE (tparm))
23394 && uses_template_parms (TREE_TYPE (tparm))
23395 && saw_undeduced < 2)
23397 saw_undeduced = 1;
23398 continue;
23401 /* Core issue #226 (C++0x) [temp.deduct]:
23403 If a template argument has not been deduced, its
23404 default template argument, if any, is used.
23406 When we are in C++98 mode, TREE_PURPOSE will either
23407 be NULL_TREE or ERROR_MARK_NODE, so we do not need
23408 to explicitly check cxx_dialect here. */
23409 if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
23410 /* OK, there is a default argument. Wait until after the
23411 conversion check to do substitution. */
23412 continue;
23414 /* If the type parameter is a parameter pack, then it will
23415 be deduced to an empty parameter pack. */
23416 if (template_parameter_pack_p (tparm))
23418 tree arg;
23420 if (TREE_CODE (tparm) == PARM_DECL)
23422 arg = make_node (NONTYPE_ARGUMENT_PACK);
23423 TREE_CONSTANT (arg) = 1;
23425 else
23426 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
23428 ARGUMENT_PACK_ARGS (arg) = make_tree_vec (0);
23430 TREE_VEC_ELT (targs, i) = arg;
23431 continue;
23434 return unify_parameter_deduction_failure (explain_p, tparm);
23437 /* During partial ordering, we deduce dependent template args. */
23438 bool any_dependent_targs = false;
23440 /* Now substitute into the default template arguments. */
23441 for (i = 0; i < ntparms; i++)
23443 tree targ = TREE_VEC_ELT (targs, i);
23444 tree tparm = TREE_VEC_ELT (tparms, i);
23446 if (targ)
23448 if (!any_dependent_targs && dependent_template_arg_p (targ))
23449 any_dependent_targs = true;
23450 continue;
23452 if (tparm == error_mark_node)
23453 continue;
23455 tree parm = TREE_VALUE (tparm);
23456 tree arg = TREE_PURPOSE (tparm);
23457 reopen_deferring_access_checks (*checks);
23458 location_t save_loc = input_location;
23459 if (DECL_P (parm))
23460 input_location = DECL_SOURCE_LOCATION (parm);
23462 if (saw_undeduced == 1
23463 && TREE_CODE (parm) == PARM_DECL
23464 && !is_auto (TREE_TYPE (parm))
23465 && uses_template_parms (TREE_TYPE (parm)))
23467 /* The type of this non-type parameter depends on undeduced
23468 parameters. Don't try to use its default argument yet,
23469 since we might deduce an argument for it on the next pass,
23470 but do check whether the arguments we already have cause
23471 substitution failure, so that that happens before we try
23472 later default arguments (78489). */
23473 ++processing_template_decl;
23474 tree type = tsubst (TREE_TYPE (parm), full_targs, complain,
23475 NULL_TREE);
23476 --processing_template_decl;
23477 if (type == error_mark_node)
23478 arg = error_mark_node;
23479 else
23480 arg = NULL_TREE;
23482 else
23484 /* Even if the call is happening in template context, getting
23485 here means it's non-dependent, and a default argument is
23486 considered a separate definition under [temp.decls], so we can
23487 do this substitution without processing_template_decl. This
23488 is important if the default argument contains something that
23489 might be instantiation-dependent like access (87480). */
23490 processing_template_decl_sentinel s (!any_dependent_targs);
23491 tree substed = NULL_TREE;
23492 if (saw_undeduced == 1 && !any_dependent_targs)
23494 /* First instatiate in template context, in case we still
23495 depend on undeduced template parameters. */
23496 ++processing_template_decl;
23497 substed = tsubst_template_arg (arg, full_targs, complain,
23498 NULL_TREE);
23499 --processing_template_decl;
23500 if (substed != error_mark_node
23501 && !uses_template_parms (substed))
23502 /* We replaced all the tparms, substitute again out of
23503 template context. */
23504 substed = NULL_TREE;
23506 if (!substed)
23507 substed = tsubst_template_arg (arg, full_targs, complain,
23508 NULL_TREE);
23510 if (!uses_template_parms (substed))
23511 arg = convert_template_argument (parm, substed, full_targs,
23512 complain, i, NULL_TREE);
23513 else if (saw_undeduced == 1)
23514 arg = NULL_TREE;
23515 else if (!any_dependent_targs)
23516 arg = error_mark_node;
23519 input_location = save_loc;
23520 *checks = get_deferred_access_checks ();
23521 pop_deferring_access_checks ();
23523 if (arg == error_mark_node)
23524 return 1;
23525 else if (arg)
23527 TREE_VEC_ELT (targs, i) = arg;
23528 /* The position of the first default template argument,
23529 is also the number of non-defaulted arguments in TARGS.
23530 Record that. */
23531 if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
23532 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
23536 if (saw_undeduced++ == 1)
23537 goto again;
23540 if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
23541 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
23543 return unify_success (explain_p);
23546 /* Subroutine of type_unification_real. Args are like the variables
23547 at the call site. ARG is an overloaded function (or template-id);
23548 we try deducing template args from each of the overloads, and if
23549 only one succeeds, we go with that. Modifies TARGS and returns
23550 true on success. */
23552 static bool
23553 resolve_overloaded_unification (tree tparms,
23554 tree targs,
23555 tree parm,
23556 tree arg,
23557 unification_kind_t strict,
23558 int sub_strict,
23559 bool explain_p)
23561 tree tempargs = copy_node (targs);
23562 int good = 0;
23563 tree goodfn = NULL_TREE;
23564 bool addr_p;
23566 if (TREE_CODE (arg) == ADDR_EXPR)
23568 arg = TREE_OPERAND (arg, 0);
23569 addr_p = true;
23571 else
23572 addr_p = false;
23574 if (TREE_CODE (arg) == COMPONENT_REF)
23575 /* Handle `&x' where `x' is some static or non-static member
23576 function name. */
23577 arg = TREE_OPERAND (arg, 1);
23579 if (TREE_CODE (arg) == OFFSET_REF)
23580 arg = TREE_OPERAND (arg, 1);
23582 /* Strip baselink information. */
23583 if (BASELINK_P (arg))
23584 arg = BASELINK_FUNCTIONS (arg);
23586 if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
23588 /* If we got some explicit template args, we need to plug them into
23589 the affected templates before we try to unify, in case the
23590 explicit args will completely resolve the templates in question. */
23592 int ok = 0;
23593 tree expl_subargs = TREE_OPERAND (arg, 1);
23594 arg = TREE_OPERAND (arg, 0);
23596 for (lkp_iterator iter (arg); iter; ++iter)
23598 tree fn = *iter;
23599 tree subargs, elem;
23601 if (TREE_CODE (fn) != TEMPLATE_DECL)
23602 continue;
23604 subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
23605 expl_subargs, NULL_TREE, tf_none);
23606 if (subargs != error_mark_node
23607 && !any_dependent_template_arguments_p (subargs))
23609 fn = instantiate_template (fn, subargs, tf_none);
23610 if (!constraints_satisfied_p (fn))
23611 continue;
23612 if (undeduced_auto_decl (fn))
23614 /* Instantiate the function to deduce its return type. */
23615 ++function_depth;
23616 instantiate_decl (fn, /*defer*/false, /*class*/false);
23617 --function_depth;
23620 if (flag_noexcept_type)
23621 maybe_instantiate_noexcept (fn, tf_none);
23623 elem = TREE_TYPE (fn);
23624 if (try_one_overload (tparms, targs, tempargs, parm,
23625 elem, strict, sub_strict, addr_p, explain_p)
23626 && (!goodfn || !same_type_p (goodfn, elem)))
23628 goodfn = elem;
23629 ++good;
23632 else if (subargs)
23633 ++ok;
23635 /* If no templates (or more than one) are fully resolved by the
23636 explicit arguments, this template-id is a non-deduced context; it
23637 could still be OK if we deduce all template arguments for the
23638 enclosing call through other arguments. */
23639 if (good != 1)
23640 good = ok;
23642 else if (!OVL_P (arg))
23643 /* If ARG is, for example, "(0, &f)" then its type will be unknown
23644 -- but the deduction does not succeed because the expression is
23645 not just the function on its own. */
23646 return false;
23647 else
23648 for (lkp_iterator iter (arg); iter; ++iter)
23650 tree fn = *iter;
23651 if (try_one_overload (tparms, targs, tempargs, parm, TREE_TYPE (fn),
23652 strict, sub_strict, addr_p, explain_p)
23653 && (!goodfn || !decls_match (goodfn, fn)))
23655 goodfn = fn;
23656 ++good;
23660 /* [temp.deduct.type] A template-argument can be deduced from a pointer
23661 to function or pointer to member function argument if the set of
23662 overloaded functions does not contain function templates and at most
23663 one of a set of overloaded functions provides a unique match.
23665 So if we found multiple possibilities, we return success but don't
23666 deduce anything. */
23668 if (good == 1)
23670 int i = TREE_VEC_LENGTH (targs);
23671 for (; i--; )
23672 if (TREE_VEC_ELT (tempargs, i))
23674 tree old = TREE_VEC_ELT (targs, i);
23675 tree new_ = TREE_VEC_ELT (tempargs, i);
23676 if (new_ && old && ARGUMENT_PACK_P (old)
23677 && ARGUMENT_PACK_EXPLICIT_ARGS (old))
23678 /* Don't forget explicit template arguments in a pack. */
23679 ARGUMENT_PACK_EXPLICIT_ARGS (new_)
23680 = ARGUMENT_PACK_EXPLICIT_ARGS (old);
23681 TREE_VEC_ELT (targs, i) = new_;
23684 if (good)
23685 return true;
23687 return false;
23690 /* Core DR 115: In contexts where deduction is done and fails, or in
23691 contexts where deduction is not done, if a template argument list is
23692 specified and it, along with any default template arguments, identifies
23693 a single function template specialization, then the template-id is an
23694 lvalue for the function template specialization. */
23696 tree
23697 resolve_nondeduced_context (tree orig_expr, tsubst_flags_t complain)
23699 tree expr, offset, baselink;
23700 bool addr;
23702 if (!type_unknown_p (orig_expr))
23703 return orig_expr;
23705 expr = orig_expr;
23706 addr = false;
23707 offset = NULL_TREE;
23708 baselink = NULL_TREE;
23710 if (TREE_CODE (expr) == ADDR_EXPR)
23712 expr = TREE_OPERAND (expr, 0);
23713 addr = true;
23715 if (TREE_CODE (expr) == OFFSET_REF)
23717 offset = expr;
23718 expr = TREE_OPERAND (expr, 1);
23720 if (BASELINK_P (expr))
23722 baselink = expr;
23723 expr = BASELINK_FUNCTIONS (expr);
23726 if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
23728 int good = 0;
23729 tree goodfn = NULL_TREE;
23731 /* If we got some explicit template args, we need to plug them into
23732 the affected templates before we try to unify, in case the
23733 explicit args will completely resolve the templates in question. */
23735 tree expl_subargs = TREE_OPERAND (expr, 1);
23736 tree arg = TREE_OPERAND (expr, 0);
23737 tree badfn = NULL_TREE;
23738 tree badargs = NULL_TREE;
23740 for (lkp_iterator iter (arg); iter; ++iter)
23742 tree fn = *iter;
23743 tree subargs, elem;
23745 if (TREE_CODE (fn) != TEMPLATE_DECL)
23746 continue;
23748 subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
23749 expl_subargs, NULL_TREE, tf_none);
23750 if (subargs != error_mark_node
23751 && !any_dependent_template_arguments_p (subargs))
23753 elem = instantiate_template (fn, subargs, tf_none);
23754 if (elem == error_mark_node)
23756 badfn = fn;
23757 badargs = subargs;
23759 else if (elem && (!goodfn || !decls_match (goodfn, elem))
23760 && constraints_satisfied_p (elem))
23762 goodfn = elem;
23763 ++good;
23767 if (good == 1)
23769 mark_used (goodfn);
23770 expr = goodfn;
23771 if (baselink)
23772 expr = build_baselink (BASELINK_BINFO (baselink),
23773 BASELINK_ACCESS_BINFO (baselink),
23774 expr, BASELINK_OPTYPE (baselink));
23775 if (offset)
23777 tree base
23778 = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
23779 expr = build_offset_ref (base, expr, addr, complain);
23781 if (addr)
23782 expr = cp_build_addr_expr (expr, complain);
23783 return expr;
23785 else if (good == 0 && badargs && (complain & tf_error))
23786 /* There were no good options and at least one bad one, so let the
23787 user know what the problem is. */
23788 instantiate_template (badfn, badargs, complain);
23790 return orig_expr;
23793 /* As above, but error out if the expression remains overloaded. */
23795 tree
23796 resolve_nondeduced_context_or_error (tree exp, tsubst_flags_t complain)
23798 exp = resolve_nondeduced_context (exp, complain);
23799 if (type_unknown_p (exp))
23801 if (complain & tf_error)
23802 cxx_incomplete_type_error (exp, TREE_TYPE (exp));
23803 return error_mark_node;
23805 return exp;
23808 /* Subroutine of resolve_overloaded_unification; does deduction for a single
23809 overload. Fills TARGS with any deduced arguments, or error_mark_node if
23810 different overloads deduce different arguments for a given parm.
23811 ADDR_P is true if the expression for which deduction is being
23812 performed was of the form "& fn" rather than simply "fn".
23814 Returns 1 on success. */
23816 static int
23817 try_one_overload (tree tparms,
23818 tree orig_targs,
23819 tree targs,
23820 tree parm,
23821 tree arg,
23822 unification_kind_t strict,
23823 int sub_strict,
23824 bool addr_p,
23825 bool explain_p)
23827 int nargs;
23828 tree tempargs;
23829 int i;
23831 if (arg == error_mark_node)
23832 return 0;
23834 /* [temp.deduct.type] A template-argument can be deduced from a pointer
23835 to function or pointer to member function argument if the set of
23836 overloaded functions does not contain function templates and at most
23837 one of a set of overloaded functions provides a unique match.
23839 So if this is a template, just return success. */
23841 if (uses_template_parms (arg))
23842 return 1;
23844 if (TREE_CODE (arg) == METHOD_TYPE)
23845 arg = build_ptrmemfunc_type (build_pointer_type (arg));
23846 else if (addr_p)
23847 arg = build_pointer_type (arg);
23849 sub_strict |= maybe_adjust_types_for_deduction (tparms, strict,
23850 &parm, &arg, NULL_TREE);
23852 /* We don't copy orig_targs for this because if we have already deduced
23853 some template args from previous args, unify would complain when we
23854 try to deduce a template parameter for the same argument, even though
23855 there isn't really a conflict. */
23856 nargs = TREE_VEC_LENGTH (targs);
23857 tempargs = make_tree_vec (nargs);
23859 if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
23860 return 0;
23862 /* First make sure we didn't deduce anything that conflicts with
23863 explicitly specified args. */
23864 for (i = nargs; i--; )
23866 tree elt = TREE_VEC_ELT (tempargs, i);
23867 tree oldelt = TREE_VEC_ELT (orig_targs, i);
23869 if (!elt)
23870 /*NOP*/;
23871 else if (uses_template_parms (elt))
23872 /* Since we're unifying against ourselves, we will fill in
23873 template args used in the function parm list with our own
23874 template parms. Discard them. */
23875 TREE_VEC_ELT (tempargs, i) = NULL_TREE;
23876 else if (oldelt && ARGUMENT_PACK_P (oldelt))
23878 /* Check that the argument at each index of the deduced argument pack
23879 is equivalent to the corresponding explicitly specified argument.
23880 We may have deduced more arguments than were explicitly specified,
23881 and that's OK. */
23883 /* We used to assert ARGUMENT_PACK_INCOMPLETE_P (oldelt) here, but
23884 that's wrong if we deduce the same argument pack from multiple
23885 function arguments: it's only incomplete the first time. */
23887 tree explicit_pack = ARGUMENT_PACK_ARGS (oldelt);
23888 tree deduced_pack = ARGUMENT_PACK_ARGS (elt);
23890 if (TREE_VEC_LENGTH (deduced_pack)
23891 < TREE_VEC_LENGTH (explicit_pack))
23892 return 0;
23894 for (int j = 0; j < TREE_VEC_LENGTH (explicit_pack); j++)
23895 if (!template_args_equal (TREE_VEC_ELT (explicit_pack, j),
23896 TREE_VEC_ELT (deduced_pack, j)))
23897 return 0;
23899 else if (oldelt && !template_args_equal (oldelt, elt))
23900 return 0;
23903 for (i = nargs; i--; )
23905 tree elt = TREE_VEC_ELT (tempargs, i);
23907 if (elt)
23908 TREE_VEC_ELT (targs, i) = elt;
23911 return 1;
23914 /* PARM is a template class (perhaps with unbound template
23915 parameters). ARG is a fully instantiated type. If ARG can be
23916 bound to PARM, return ARG, otherwise return NULL_TREE. TPARMS and
23917 TARGS are as for unify. */
23919 static tree
23920 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
23921 bool explain_p)
23923 if (!CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
23924 return NULL_TREE;
23925 else if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23926 /* Matches anything. */;
23927 else if (CLASSTYPE_TI_TEMPLATE (arg) != CLASSTYPE_TI_TEMPLATE (parm))
23928 return NULL_TREE;
23930 /* We need to make a new template argument vector for the call to
23931 unify. If we used TARGS, we'd clutter it up with the result of
23932 the attempted unification, even if this class didn't work out.
23933 We also don't want to commit ourselves to all the unifications
23934 we've already done, since unification is supposed to be done on
23935 an argument-by-argument basis. In other words, consider the
23936 following pathological case:
23938 template <int I, int J, int K>
23939 struct S {};
23941 template <int I, int J>
23942 struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
23944 template <int I, int J, int K>
23945 void f(S<I, J, K>, S<I, I, I>);
23947 void g() {
23948 S<0, 0, 0> s0;
23949 S<0, 1, 2> s2;
23951 f(s0, s2);
23954 Now, by the time we consider the unification involving `s2', we
23955 already know that we must have `f<0, 0, 0>'. But, even though
23956 `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
23957 because there are two ways to unify base classes of S<0, 1, 2>
23958 with S<I, I, I>. If we kept the already deduced knowledge, we
23959 would reject the possibility I=1. */
23960 targs = copy_template_args (targs);
23961 for (tree& targ : tree_vec_range (INNERMOST_TEMPLATE_ARGS (targs)))
23962 targ = NULL_TREE;
23964 int err;
23965 if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23966 err = unify_bound_ttp_args (tparms, targs, parm, arg, explain_p);
23967 else
23968 err = unify (tparms, targs,
23969 INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (parm)),
23970 INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (arg)),
23971 UNIFY_ALLOW_NONE, explain_p);
23973 return err ? NULL_TREE : arg;
23976 /* Given a template type PARM and a class type ARG, find the unique
23977 base type in ARG that is an instance of PARM. We do not examine
23978 ARG itself; only its base-classes. If there is not exactly one
23979 appropriate base class, return NULL_TREE. PARM may be the type of
23980 a partial specialization, as well as a plain template type. Used
23981 by unify. */
23983 static enum template_base_result
23984 get_template_base (tree tparms, tree targs, tree parm, tree arg,
23985 bool explain_p, tree *result)
23987 tree rval = NULL_TREE;
23988 tree binfo;
23990 gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
23992 binfo = TYPE_BINFO (complete_type (arg));
23993 if (!binfo)
23995 /* The type could not be completed. */
23996 *result = NULL_TREE;
23997 return tbr_incomplete_type;
24000 /* Walk in inheritance graph order. The search order is not
24001 important, and this avoids multiple walks of virtual bases. */
24002 for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
24004 tree r = try_class_unification (tparms, targs, parm,
24005 BINFO_TYPE (binfo), explain_p);
24007 if (r)
24009 /* If there is more than one satisfactory baseclass, then:
24011 [temp.deduct.call]
24013 If they yield more than one possible deduced A, the type
24014 deduction fails.
24016 applies. */
24017 if (rval && !same_type_p (r, rval))
24019 /* [temp.deduct.call]/4.3: If there is a class C that is a
24020 (direct or indirect) base class of D and derived (directly or
24021 indirectly) from a class B and that would be a valid deduced
24022 A, the deduced A cannot be B or pointer to B, respectively. */
24023 if (DERIVED_FROM_P (r, rval))
24024 /* Ignore r. */
24025 continue;
24026 else if (DERIVED_FROM_P (rval, r))
24027 /* Ignore rval. */;
24028 else
24030 *result = NULL_TREE;
24031 return tbr_ambiguous_baseclass;
24035 rval = r;
24039 *result = rval;
24040 return tbr_success;
24043 /* Returns the level of DECL, which declares a template parameter. */
24045 static int
24046 template_decl_level (tree decl)
24048 switch (TREE_CODE (decl))
24050 case TYPE_DECL:
24051 case TEMPLATE_DECL:
24052 return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
24054 case PARM_DECL:
24055 return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
24057 default:
24058 gcc_unreachable ();
24060 return 0;
24063 /* Decide whether ARG can be unified with PARM, considering only the
24064 cv-qualifiers of each type, given STRICT as documented for unify.
24065 Returns nonzero iff the unification is OK on that basis. */
24067 static int
24068 check_cv_quals_for_unify (int strict, tree arg, tree parm)
24070 int arg_quals = cp_type_quals (arg);
24071 int parm_quals = cp_type_quals (parm);
24073 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
24074 && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
24076 /* Although a CVR qualifier is ignored when being applied to a
24077 substituted template parameter ([8.3.2]/1 for example), that
24078 does not allow us to unify "const T" with "int&" because both
24079 types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
24080 It is ok when we're allowing additional CV qualifiers
24081 at the outer level [14.8.2.1]/3,1st bullet. */
24082 if ((TYPE_REF_P (arg)
24083 || FUNC_OR_METHOD_TYPE_P (arg))
24084 && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
24085 return 0;
24087 if ((!INDIRECT_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
24088 && (parm_quals & TYPE_QUAL_RESTRICT))
24089 return 0;
24092 if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
24093 && (arg_quals & parm_quals) != parm_quals)
24094 return 0;
24096 if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
24097 && (parm_quals & arg_quals) != arg_quals)
24098 return 0;
24100 return 1;
24103 /* Determines the LEVEL and INDEX for the template parameter PARM. */
24104 void
24105 template_parm_level_and_index (tree parm, int* level, int* index)
24107 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
24108 || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
24109 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
24111 *index = TEMPLATE_TYPE_IDX (parm);
24112 *level = TEMPLATE_TYPE_LEVEL (parm);
24114 else
24116 *index = TEMPLATE_PARM_IDX (parm);
24117 *level = TEMPLATE_PARM_LEVEL (parm);
24121 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP) \
24122 do { \
24123 if (unify (TP, TA, P, A, S, EP)) \
24124 return 1; \
24125 } while (0)
24127 /* Unifies the remaining arguments in PACKED_ARGS with the pack
24128 expansion at the end of PACKED_PARMS. Returns 0 if the type
24129 deduction succeeds, 1 otherwise. STRICT is the same as in
24130 fn_type_unification. CALL_ARGS_P is true iff PACKED_ARGS is actually a
24131 function call argument list. We'll need to adjust the arguments to make them
24132 types. SUBR tells us if this is from a recursive call to
24133 type_unification_real, or for comparing two template argument
24134 lists. */
24136 static int
24137 unify_pack_expansion (tree tparms, tree targs, tree packed_parms,
24138 tree packed_args, unification_kind_t strict,
24139 bool subr, bool explain_p)
24141 tree parm
24142 = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
24143 tree pattern = PACK_EXPANSION_PATTERN (parm);
24144 tree pack, packs = NULL_TREE;
24145 int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
24147 /* Add in any args remembered from an earlier partial instantiation. */
24148 targs = add_to_template_args (PACK_EXPANSION_EXTRA_ARGS (parm), targs);
24149 int levels = TMPL_ARGS_DEPTH (targs);
24151 packed_args = expand_template_argument_pack (packed_args);
24153 int len = TREE_VEC_LENGTH (packed_args);
24155 /* Determine the parameter packs we will be deducing from the
24156 pattern, and record their current deductions. */
24157 for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm);
24158 pack; pack = TREE_CHAIN (pack))
24160 tree parm_pack = TREE_VALUE (pack);
24161 int idx, level;
24163 /* Only template parameter packs can be deduced, not e.g. function
24164 parameter packs or __bases or __integer_pack. */
24165 if (!TEMPLATE_PARM_P (parm_pack))
24166 continue;
24168 /* Determine the index and level of this parameter pack. */
24169 template_parm_level_and_index (parm_pack, &level, &idx);
24170 if (level > levels)
24171 continue;
24173 /* Keep track of the parameter packs and their corresponding
24174 argument packs. */
24175 packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
24176 TREE_TYPE (packs) = make_tree_vec (len - start);
24179 /* Loop through all of the arguments that have not yet been
24180 unified and unify each with the pattern. */
24181 for (i = start; i < len; i++)
24183 tree parm;
24184 bool any_explicit = false;
24185 tree arg = TREE_VEC_ELT (packed_args, i);
24187 /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
24188 or the element of its argument pack at the current index if
24189 this argument was explicitly specified. */
24190 for (pack = packs; pack; pack = TREE_CHAIN (pack))
24192 int idx, level;
24193 tree arg, pargs;
24194 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
24196 arg = NULL_TREE;
24197 if (TREE_VALUE (pack)
24198 && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
24199 && (i - start < TREE_VEC_LENGTH (pargs)))
24201 any_explicit = true;
24202 arg = TREE_VEC_ELT (pargs, i - start);
24204 TMPL_ARG (targs, level, idx) = arg;
24207 /* If we had explicit template arguments, substitute them into the
24208 pattern before deduction. */
24209 if (any_explicit)
24211 /* Some arguments might still be unspecified or dependent. */
24212 bool dependent;
24213 ++processing_template_decl;
24214 dependent = any_dependent_template_arguments_p (targs);
24215 if (!dependent)
24216 --processing_template_decl;
24217 parm = tsubst (pattern, targs,
24218 explain_p ? tf_warning_or_error : tf_none,
24219 NULL_TREE);
24220 if (dependent)
24221 --processing_template_decl;
24222 if (parm == error_mark_node)
24223 return 1;
24225 else
24226 parm = pattern;
24228 /* Unify the pattern with the current argument. */
24229 if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
24230 explain_p))
24231 return 1;
24233 /* For each parameter pack, collect the deduced value. */
24234 for (pack = packs; pack; pack = TREE_CHAIN (pack))
24236 int idx, level;
24237 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
24239 TREE_VEC_ELT (TREE_TYPE (pack), i - start) =
24240 TMPL_ARG (targs, level, idx);
24244 /* Verify that the results of unification with the parameter packs
24245 produce results consistent with what we've seen before, and make
24246 the deduced argument packs available. */
24247 for (pack = packs; pack; pack = TREE_CHAIN (pack))
24249 tree old_pack = TREE_VALUE (pack);
24250 tree new_args = TREE_TYPE (pack);
24251 int i, len = TREE_VEC_LENGTH (new_args);
24252 int idx, level;
24253 bool nondeduced_p = false;
24255 /* By default keep the original deduced argument pack.
24256 If necessary, more specific code is going to update the
24257 resulting deduced argument later down in this function. */
24258 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
24259 TMPL_ARG (targs, level, idx) = old_pack;
24261 /* If NEW_ARGS contains any NULL_TREE entries, we didn't
24262 actually deduce anything. */
24263 for (i = 0; i < len && !nondeduced_p; ++i)
24264 if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
24265 nondeduced_p = true;
24266 if (nondeduced_p)
24267 continue;
24269 if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
24271 /* If we had fewer function args than explicit template args,
24272 just use the explicits. */
24273 tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
24274 int explicit_len = TREE_VEC_LENGTH (explicit_args);
24275 if (len < explicit_len)
24276 new_args = explicit_args;
24279 if (!old_pack)
24281 tree result;
24282 /* Build the deduced *_ARGUMENT_PACK. */
24283 if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
24285 result = make_node (NONTYPE_ARGUMENT_PACK);
24286 TREE_CONSTANT (result) = 1;
24288 else
24289 result = cxx_make_type (TYPE_ARGUMENT_PACK);
24291 ARGUMENT_PACK_ARGS (result) = new_args;
24293 /* Note the deduced argument packs for this parameter
24294 pack. */
24295 TMPL_ARG (targs, level, idx) = result;
24297 else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
24298 && (ARGUMENT_PACK_ARGS (old_pack)
24299 == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
24301 /* We only had the explicitly-provided arguments before, but
24302 now we have a complete set of arguments. */
24303 tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
24305 ARGUMENT_PACK_ARGS (old_pack) = new_args;
24306 ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
24307 ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
24309 else
24311 tree bad_old_arg = NULL_TREE, bad_new_arg = NULL_TREE;
24312 tree old_args = ARGUMENT_PACK_ARGS (old_pack);
24313 temp_override<int> ovl (TREE_VEC_LENGTH (old_args));
24314 /* During template argument deduction for the aggregate deduction
24315 candidate, the number of elements in a trailing parameter pack
24316 is only deduced from the number of remaining function
24317 arguments if it is not otherwise deduced. */
24318 if (cxx_dialect >= cxx20
24319 && TREE_VEC_LENGTH (new_args) < TREE_VEC_LENGTH (old_args)
24320 /* FIXME This isn't set properly for partial instantiations. */
24321 && TPARMS_PRIMARY_TEMPLATE (tparms)
24322 && builtin_guide_p (TPARMS_PRIMARY_TEMPLATE (tparms)))
24323 TREE_VEC_LENGTH (old_args) = TREE_VEC_LENGTH (new_args);
24324 if (!comp_template_args (old_args, new_args,
24325 &bad_old_arg, &bad_new_arg))
24326 /* Inconsistent unification of this parameter pack. */
24327 return unify_parameter_pack_inconsistent (explain_p,
24328 bad_old_arg,
24329 bad_new_arg);
24333 return unify_success (explain_p);
24336 /* Handle unification of the domain of an array. PARM_DOM and ARG_DOM are
24337 INTEGER_TYPEs representing the TYPE_DOMAIN of ARRAY_TYPEs. The other
24338 parameters and return value are as for unify. */
24340 static int
24341 unify_array_domain (tree tparms, tree targs,
24342 tree parm_dom, tree arg_dom,
24343 bool explain_p)
24345 tree parm_max;
24346 tree arg_max;
24347 bool parm_cst;
24348 bool arg_cst;
24350 /* Our representation of array types uses "N - 1" as the
24351 TYPE_MAX_VALUE for an array with "N" elements, if "N" is
24352 not an integer constant. We cannot unify arbitrarily
24353 complex expressions, so we eliminate the MINUS_EXPRs
24354 here. */
24355 parm_max = TYPE_MAX_VALUE (parm_dom);
24356 parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
24357 if (!parm_cst)
24359 gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
24360 parm_max = TREE_OPERAND (parm_max, 0);
24362 arg_max = TYPE_MAX_VALUE (arg_dom);
24363 arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
24364 if (!arg_cst)
24366 /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
24367 trying to unify the type of a variable with the type
24368 of a template parameter. For example:
24370 template <unsigned int N>
24371 void f (char (&) [N]);
24372 int g();
24373 void h(int i) {
24374 char a[g(i)];
24375 f(a);
24378 Here, the type of the ARG will be "int [g(i)]", and
24379 may be a SAVE_EXPR, etc. */
24380 if (TREE_CODE (arg_max) != MINUS_EXPR)
24381 return unify_vla_arg (explain_p, arg_dom);
24382 arg_max = TREE_OPERAND (arg_max, 0);
24385 /* If only one of the bounds used a MINUS_EXPR, compensate
24386 by adding one to the other bound. */
24387 if (parm_cst && !arg_cst)
24388 parm_max = fold_build2_loc (input_location, PLUS_EXPR,
24389 integer_type_node,
24390 parm_max,
24391 integer_one_node);
24392 else if (arg_cst && !parm_cst)
24393 arg_max = fold_build2_loc (input_location, PLUS_EXPR,
24394 integer_type_node,
24395 arg_max,
24396 integer_one_node);
24398 return unify (tparms, targs, parm_max, arg_max,
24399 UNIFY_ALLOW_INTEGER, explain_p);
24402 /* Returns whether T, a P or A in unify, is a type, template or expression. */
24404 enum pa_kind_t { pa_type, pa_tmpl, pa_expr };
24406 static pa_kind_t
24407 pa_kind (tree t)
24409 if (PACK_EXPANSION_P (t))
24410 t = PACK_EXPANSION_PATTERN (t);
24411 if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM
24412 || TREE_CODE (t) == UNBOUND_CLASS_TEMPLATE
24413 || DECL_TYPE_TEMPLATE_P (t))
24414 return pa_tmpl;
24415 else if (TYPE_P (t))
24416 return pa_type;
24417 else
24418 return pa_expr;
24421 /* Deduce the value of template parameters. TPARMS is the (innermost)
24422 set of template parameters to a template. TARGS is the bindings
24423 for those template parameters, as determined thus far; TARGS may
24424 include template arguments for outer levels of template parameters
24425 as well. PARM is a parameter to a template function, or a
24426 subcomponent of that parameter; ARG is the corresponding argument.
24427 This function attempts to match PARM with ARG in a manner
24428 consistent with the existing assignments in TARGS. If more values
24429 are deduced, then TARGS is updated.
24431 Returns 0 if the type deduction succeeds, 1 otherwise. The
24432 parameter STRICT is a bitwise or of the following flags:
24434 UNIFY_ALLOW_NONE:
24435 Require an exact match between PARM and ARG.
24436 UNIFY_ALLOW_MORE_CV_QUAL:
24437 Allow the deduced ARG to be more cv-qualified (by qualification
24438 conversion) than ARG.
24439 UNIFY_ALLOW_LESS_CV_QUAL:
24440 Allow the deduced ARG to be less cv-qualified than ARG.
24441 UNIFY_ALLOW_DERIVED:
24442 Allow the deduced ARG to be a template base class of ARG,
24443 or a pointer to a template base class of the type pointed to by
24444 ARG.
24445 UNIFY_ALLOW_INTEGER:
24446 Allow any integral type to be deduced. See the TEMPLATE_PARM_INDEX
24447 case for more information.
24448 UNIFY_ALLOW_OUTER_LEVEL:
24449 This is the outermost level of a deduction. Used to determine validity
24450 of qualification conversions. A valid qualification conversion must
24451 have const qualified pointers leading up to the inner type which
24452 requires additional CV quals, except at the outer level, where const
24453 is not required [conv.qual]. It would be normal to set this flag in
24454 addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
24455 UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
24456 This is the outermost level of a deduction, and PARM can be more CV
24457 qualified at this point.
24458 UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
24459 This is the outermost level of a deduction, and PARM can be less CV
24460 qualified at this point. */
24462 static int
24463 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
24464 bool explain_p)
24466 int idx;
24467 tree targ;
24468 tree tparm;
24469 int strict_in = strict;
24470 tsubst_flags_t complain = (explain_p
24471 ? tf_warning_or_error
24472 : tf_none);
24474 /* I don't think this will do the right thing with respect to types.
24475 But the only case I've seen it in so far has been array bounds, where
24476 signedness is the only information lost, and I think that will be
24477 okay. VIEW_CONVERT_EXPR can appear with class NTTP, thanks to
24478 finish_id_expression_1, and are also OK. */
24479 while (CONVERT_EXPR_P (parm) || TREE_CODE (parm) == VIEW_CONVERT_EXPR)
24480 parm = TREE_OPERAND (parm, 0);
24482 if (arg == error_mark_node)
24483 return unify_invalid (explain_p);
24484 if (arg == unknown_type_node
24485 || arg == init_list_type_node)
24486 /* We can't deduce anything from this, but we might get all the
24487 template args from other function args. */
24488 return unify_success (explain_p);
24490 if (parm == any_targ_node || arg == any_targ_node)
24491 return unify_success (explain_p);
24493 /* If PARM uses template parameters, then we can't bail out here,
24494 even if ARG == PARM, since we won't record unifications for the
24495 template parameters. We might need them if we're trying to
24496 figure out which of two things is more specialized. */
24497 if (arg == parm
24498 && (DECL_P (parm) || !uses_template_parms (parm)))
24499 return unify_success (explain_p);
24501 /* Handle init lists early, so the rest of the function can assume
24502 we're dealing with a type. */
24503 if (BRACE_ENCLOSED_INITIALIZER_P (arg))
24505 tree elttype;
24506 tree orig_parm = parm;
24508 if (!is_std_init_list (parm)
24509 && TREE_CODE (parm) != ARRAY_TYPE)
24510 /* We can only deduce from an initializer list argument if the
24511 parameter is std::initializer_list or an array; otherwise this
24512 is a non-deduced context. */
24513 return unify_success (explain_p);
24515 if (TREE_CODE (parm) == ARRAY_TYPE)
24516 elttype = TREE_TYPE (parm);
24517 else
24519 elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
24520 /* Deduction is defined in terms of a single type, so just punt
24521 on the (bizarre) std::initializer_list<T...>. */
24522 if (PACK_EXPANSION_P (elttype))
24523 return unify_success (explain_p);
24526 if (strict != DEDUCE_EXACT
24527 && TYPE_P (elttype)
24528 && !uses_deducible_template_parms (elttype))
24529 /* If ELTTYPE has no deducible template parms, skip deduction from
24530 the list elements. */;
24531 else
24532 for (auto &e: CONSTRUCTOR_ELTS (arg))
24534 tree elt = e.value;
24535 int elt_strict = strict;
24537 if (elt == error_mark_node)
24538 return unify_invalid (explain_p);
24540 if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
24542 tree type = TREE_TYPE (elt);
24543 if (type == error_mark_node)
24544 return unify_invalid (explain_p);
24545 /* It should only be possible to get here for a call. */
24546 gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
24547 elt_strict |= maybe_adjust_types_for_deduction
24548 (tparms, DEDUCE_CALL, &elttype, &type, elt);
24549 elt = type;
24552 RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
24553 explain_p);
24556 if (TREE_CODE (parm) == ARRAY_TYPE
24557 && deducible_array_bound (TYPE_DOMAIN (parm)))
24559 /* Also deduce from the length of the initializer list. */
24560 tree max = size_int (CONSTRUCTOR_NELTS (arg));
24561 tree idx = compute_array_index_type (NULL_TREE, max, tf_none);
24562 if (idx == error_mark_node)
24563 return unify_invalid (explain_p);
24564 return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
24565 idx, explain_p);
24568 /* If the std::initializer_list<T> deduction worked, replace the
24569 deduced A with std::initializer_list<A>. */
24570 if (orig_parm != parm)
24572 idx = TEMPLATE_TYPE_IDX (orig_parm);
24573 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
24574 targ = listify (targ);
24575 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
24577 return unify_success (explain_p);
24580 /* If parm and arg aren't the same kind of thing (template, type, or
24581 expression), fail early. */
24582 if (pa_kind (parm) != pa_kind (arg))
24583 return unify_invalid (explain_p);
24585 /* Immediately reject some pairs that won't unify because of
24586 cv-qualification mismatches. */
24587 if (TREE_CODE (arg) == TREE_CODE (parm)
24588 && TYPE_P (arg)
24589 /* It is the elements of the array which hold the cv quals of an array
24590 type, and the elements might be template type parms. We'll check
24591 when we recurse. */
24592 && TREE_CODE (arg) != ARRAY_TYPE
24593 /* We check the cv-qualifiers when unifying with template type
24594 parameters below. We want to allow ARG `const T' to unify with
24595 PARM `T' for example, when computing which of two templates
24596 is more specialized, for example. */
24597 && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
24598 && !check_cv_quals_for_unify (strict_in, arg, parm))
24599 return unify_cv_qual_mismatch (explain_p, parm, arg);
24601 if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
24602 && TYPE_P (parm) && !CP_TYPE_CONST_P (parm)
24603 && !FUNC_OR_METHOD_TYPE_P (parm))
24604 strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
24605 /* PMFs recurse at the same level, so don't strip this yet. */
24606 if (!TYPE_PTRMEMFUNC_P (parm))
24607 strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
24608 strict &= ~UNIFY_ALLOW_DERIVED;
24609 strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
24610 strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
24612 switch (TREE_CODE (parm))
24614 case TYPENAME_TYPE:
24615 case SCOPE_REF:
24616 case UNBOUND_CLASS_TEMPLATE:
24617 /* In a type which contains a nested-name-specifier, template
24618 argument values cannot be deduced for template parameters used
24619 within the nested-name-specifier. */
24620 return unify_success (explain_p);
24622 case TEMPLATE_TYPE_PARM:
24623 case TEMPLATE_TEMPLATE_PARM:
24624 case BOUND_TEMPLATE_TEMPLATE_PARM:
24625 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
24626 if (error_operand_p (tparm))
24627 return unify_invalid (explain_p);
24629 if (TEMPLATE_TYPE_LEVEL (parm)
24630 != template_decl_level (tparm))
24631 /* The PARM is not one we're trying to unify. Just check
24632 to see if it matches ARG. */
24634 if (TREE_CODE (arg) == TREE_CODE (parm)
24635 && (is_auto (parm) ? is_auto (arg)
24636 : same_type_p (parm, arg)))
24637 return unify_success (explain_p);
24638 else
24639 return unify_type_mismatch (explain_p, parm, arg);
24641 idx = TEMPLATE_TYPE_IDX (parm);
24642 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
24643 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
24644 if (error_operand_p (tparm))
24645 return unify_invalid (explain_p);
24647 /* Check for mixed types and values. */
24648 if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
24649 && TREE_CODE (tparm) != TYPE_DECL)
24650 || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
24651 && TREE_CODE (tparm) != TEMPLATE_DECL))
24652 gcc_unreachable ();
24654 if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
24656 if ((strict_in & UNIFY_ALLOW_DERIVED)
24657 && CLASS_TYPE_P (arg))
24659 /* First try to match ARG directly. */
24660 tree t = try_class_unification (tparms, targs, parm, arg,
24661 explain_p);
24662 if (!t)
24664 /* Otherwise, look for a suitable base of ARG, as below. */
24665 enum template_base_result r;
24666 r = get_template_base (tparms, targs, parm, arg,
24667 explain_p, &t);
24668 if (!t)
24669 return unify_no_common_base (explain_p, r, parm, arg);
24670 arg = t;
24673 /* ARG must be constructed from a template class or a template
24674 template parameter. */
24675 else if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
24676 && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
24677 return unify_template_deduction_failure (explain_p, parm, arg);
24679 /* Deduce arguments T, i from TT<T> or TT<i>. */
24680 if (unify_bound_ttp_args (tparms, targs, parm, arg, explain_p))
24681 return 1;
24683 arg = TYPE_TI_TEMPLATE (arg);
24684 if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg))
24685 /* If the template is a template template parameter, use the
24686 TEMPLATE_TEMPLATE_PARM for matching. */
24687 arg = TREE_TYPE (arg);
24689 /* Fall through to deduce template name. */
24692 if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
24693 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
24695 /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>. */
24697 /* Simple cases: Value already set, does match or doesn't. */
24698 if (targ != NULL_TREE && template_args_equal (targ, arg))
24699 return unify_success (explain_p);
24700 else if (targ)
24701 return unify_inconsistency (explain_p, parm, targ, arg);
24703 else
24705 /* If PARM is `const T' and ARG is only `int', we don't have
24706 a match unless we are allowing additional qualification.
24707 If ARG is `const int' and PARM is just `T' that's OK;
24708 that binds `const int' to `T'. */
24709 if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
24710 arg, parm))
24711 return unify_cv_qual_mismatch (explain_p, parm, arg);
24713 /* Consider the case where ARG is `const volatile int' and
24714 PARM is `const T'. Then, T should be `volatile int'. */
24715 arg = cp_build_qualified_type
24716 (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
24717 if (arg == error_mark_node)
24718 return unify_invalid (explain_p);
24720 /* Simple cases: Value already set, does match or doesn't. */
24721 if (targ != NULL_TREE && same_type_p (targ, arg))
24722 return unify_success (explain_p);
24723 else if (targ)
24724 return unify_inconsistency (explain_p, parm, targ, arg);
24726 /* Make sure that ARG is not a variable-sized array. (Note
24727 that were talking about variable-sized arrays (like
24728 `int[n]'), rather than arrays of unknown size (like
24729 `int[]').) We'll get very confused by such a type since
24730 the bound of the array is not constant, and therefore
24731 not mangleable. Besides, such types are not allowed in
24732 ISO C++, so we can do as we please here. We do allow
24733 them for 'auto' deduction, since that isn't ABI-exposed. */
24734 if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
24735 return unify_vla_arg (explain_p, arg);
24737 /* Strip typedefs as in convert_template_argument. */
24738 arg = canonicalize_type_argument (arg, tf_none);
24741 /* If ARG is a parameter pack or an expansion, we cannot unify
24742 against it unless PARM is also a parameter pack. */
24743 if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
24744 && !template_parameter_pack_p (parm))
24745 return unify_parameter_pack_mismatch (explain_p, parm, arg);
24747 /* If the argument deduction results is a METHOD_TYPE,
24748 then there is a problem.
24749 METHOD_TYPE doesn't map to any real C++ type the result of
24750 the deduction cannot be of that type. */
24751 if (TREE_CODE (arg) == METHOD_TYPE)
24752 return unify_method_type_error (explain_p, arg);
24754 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
24755 return unify_success (explain_p);
24757 case TEMPLATE_PARM_INDEX:
24758 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
24759 if (error_operand_p (tparm))
24760 return unify_invalid (explain_p);
24762 if (TEMPLATE_PARM_LEVEL (parm)
24763 != template_decl_level (tparm))
24765 /* The PARM is not one we're trying to unify. Just check
24766 to see if it matches ARG. */
24767 int result = !(TREE_CODE (arg) == TREE_CODE (parm)
24768 && cp_tree_equal (parm, arg));
24769 if (result)
24770 unify_expression_unequal (explain_p, parm, arg);
24771 return result;
24774 idx = TEMPLATE_PARM_IDX (parm);
24775 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
24777 if (targ)
24779 if ((strict & UNIFY_ALLOW_INTEGER)
24780 && TREE_TYPE (targ) && TREE_TYPE (arg)
24781 && CP_INTEGRAL_TYPE_P (TREE_TYPE (targ)))
24782 /* We're deducing from an array bound, the type doesn't matter.
24783 This conversion should match the one below. */
24784 arg = fold (build_nop (TREE_TYPE (targ), arg));
24785 int x = !cp_tree_equal (targ, arg);
24786 if (x)
24787 unify_inconsistency (explain_p, parm, targ, arg);
24788 return x;
24791 /* [temp.deduct.type] If, in the declaration of a function template
24792 with a non-type template-parameter, the non-type
24793 template-parameter is used in an expression in the function
24794 parameter-list and, if the corresponding template-argument is
24795 deduced, the template-argument type shall match the type of the
24796 template-parameter exactly, except that a template-argument
24797 deduced from an array bound may be of any integral type.
24798 The non-type parameter might use already deduced type parameters. */
24799 tparm = TREE_TYPE (parm);
24800 if (TEMPLATE_PARM_LEVEL (parm) > TMPL_ARGS_DEPTH (targs))
24801 /* We don't have enough levels of args to do any substitution. This
24802 can happen in the context of -fnew-ttp-matching. */;
24803 else
24805 ++processing_template_decl;
24806 tparm = tsubst (tparm, targs, tf_none, NULL_TREE);
24807 --processing_template_decl;
24809 if (tree a = type_uses_auto (tparm))
24811 tparm = do_auto_deduction (tparm, arg, a,
24812 complain, adc_unify, targs,
24813 LOOKUP_NORMAL,
24814 TPARMS_PRIMARY_TEMPLATE (tparms));
24815 if (tparm == error_mark_node)
24816 return 1;
24820 if (!TREE_TYPE (arg)
24821 || TREE_CODE (TREE_TYPE (arg)) == DEPENDENT_OPERATOR_TYPE)
24822 /* Template-parameter dependent expression. Just accept it for now.
24823 It will later be processed in convert_template_argument. */
24825 else if (same_type_ignoring_top_level_qualifiers_p
24826 (non_reference (TREE_TYPE (arg)),
24827 non_reference (tparm)))
24828 /* OK. Ignore top-level quals here because a class-type template
24829 parameter object is const. */;
24830 else if ((strict & UNIFY_ALLOW_INTEGER)
24831 && CP_INTEGRAL_TYPE_P (tparm))
24832 /* Convert the ARG to the type of PARM; the deduced non-type
24833 template argument must exactly match the types of the
24834 corresponding parameter. This conversion should match the
24835 one above. */
24836 arg = fold (build_nop (tparm, arg));
24837 else if (uses_template_parms (tparm))
24839 /* We haven't deduced the type of this parameter yet. */
24840 if (cxx_dialect >= cxx17
24841 /* We deduce from array bounds in try_array_deduction. */
24842 && !(strict & UNIFY_ALLOW_INTEGER)
24843 && TEMPLATE_PARM_LEVEL (parm) <= TMPL_ARGS_DEPTH (targs))
24845 /* Deduce it from the non-type argument. As above, ignore
24846 top-level quals here too. */
24847 tree atype = cv_unqualified (TREE_TYPE (arg));
24848 RECUR_AND_CHECK_FAILURE (tparms, targs,
24849 tparm, atype,
24850 UNIFY_ALLOW_NONE, explain_p);
24851 /* Now check whether the type of this parameter is still
24852 dependent, and give up if so. */
24853 ++processing_template_decl;
24854 tparm = tsubst (TREE_TYPE (parm), targs, tf_none, NULL_TREE);
24855 --processing_template_decl;
24856 if (uses_template_parms (tparm))
24857 return unify_success (explain_p);
24859 else
24860 /* Try again later. */
24861 return unify_success (explain_p);
24863 else
24864 return unify_type_mismatch (explain_p, tparm, TREE_TYPE (arg));
24866 /* If ARG is a parameter pack or an expansion, we cannot unify
24867 against it unless PARM is also a parameter pack. */
24868 if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
24869 && !TEMPLATE_PARM_PARAMETER_PACK (parm))
24870 return unify_parameter_pack_mismatch (explain_p, parm, arg);
24873 bool removed_attr = false;
24874 arg = strip_typedefs_expr (arg, &removed_attr);
24876 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
24877 return unify_success (explain_p);
24879 case PTRMEM_CST:
24881 /* A pointer-to-member constant can be unified only with
24882 another constant. */
24883 if (TREE_CODE (arg) != PTRMEM_CST)
24884 return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
24886 /* Just unify the class member. It would be useless (and possibly
24887 wrong, depending on the strict flags) to unify also
24888 PTRMEM_CST_CLASS, because we want to be sure that both parm and
24889 arg refer to the same variable, even if through different
24890 classes. For instance:
24892 struct A { int x; };
24893 struct B : A { };
24895 Unification of &A::x and &B::x must succeed. */
24896 return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
24897 PTRMEM_CST_MEMBER (arg), strict, explain_p);
24900 case POINTER_TYPE:
24902 if (!TYPE_PTR_P (arg))
24903 return unify_type_mismatch (explain_p, parm, arg);
24905 /* [temp.deduct.call]
24907 A can be another pointer or pointer to member type that can
24908 be converted to the deduced A via a qualification
24909 conversion (_conv.qual_).
24911 We pass down STRICT here rather than UNIFY_ALLOW_NONE.
24912 This will allow for additional cv-qualification of the
24913 pointed-to types if appropriate. */
24915 if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
24916 /* The derived-to-base conversion only persists through one
24917 level of pointers. */
24918 strict |= (strict_in & UNIFY_ALLOW_DERIVED);
24920 return unify (tparms, targs, TREE_TYPE (parm),
24921 TREE_TYPE (arg), strict, explain_p);
24924 case REFERENCE_TYPE:
24925 if (!TYPE_REF_P (arg))
24926 return unify_type_mismatch (explain_p, parm, arg);
24927 return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
24928 strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
24930 case ARRAY_TYPE:
24931 if (TREE_CODE (arg) != ARRAY_TYPE)
24932 return unify_type_mismatch (explain_p, parm, arg);
24933 if ((TYPE_DOMAIN (parm) == NULL_TREE)
24934 != (TYPE_DOMAIN (arg) == NULL_TREE))
24935 return unify_type_mismatch (explain_p, parm, arg);
24936 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
24937 strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
24938 if (TYPE_DOMAIN (parm) != NULL_TREE)
24939 return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
24940 TYPE_DOMAIN (arg), explain_p);
24941 return unify_success (explain_p);
24943 case REAL_TYPE:
24944 case COMPLEX_TYPE:
24945 case VECTOR_TYPE:
24946 case INTEGER_TYPE:
24947 case BOOLEAN_TYPE:
24948 case ENUMERAL_TYPE:
24949 case VOID_TYPE:
24950 case OPAQUE_TYPE:
24951 case NULLPTR_TYPE:
24952 if (TREE_CODE (arg) != TREE_CODE (parm))
24953 return unify_type_mismatch (explain_p, parm, arg);
24955 /* We have already checked cv-qualification at the top of the
24956 function. */
24957 if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
24958 return unify_type_mismatch (explain_p, parm, arg);
24960 /* As far as unification is concerned, this wins. Later checks
24961 will invalidate it if necessary. */
24962 return unify_success (explain_p);
24964 /* Types INTEGER_CST and MINUS_EXPR can come from array bounds. */
24965 /* Type INTEGER_CST can come from ordinary constant template args. */
24966 case INTEGER_CST:
24967 case REAL_CST:
24968 if (TREE_TYPE (arg) == NULL_TREE
24969 || !same_type_p (TREE_TYPE (parm), TREE_TYPE (arg)))
24970 return unify_template_argument_mismatch (explain_p, parm, arg);
24971 while (CONVERT_EXPR_P (arg))
24972 arg = TREE_OPERAND (arg, 0);
24974 if (TREE_CODE (arg) != TREE_CODE (parm))
24975 return unify_template_argument_mismatch (explain_p, parm, arg);
24976 return (simple_cst_equal (parm, arg)
24977 ? unify_success (explain_p)
24978 : unify_template_argument_mismatch (explain_p, parm, arg));
24980 case TREE_VEC:
24982 int i, len, argslen;
24983 int parm_variadic_p = 0;
24985 if (TREE_CODE (arg) != TREE_VEC)
24986 return unify_template_argument_mismatch (explain_p, parm, arg);
24988 len = TREE_VEC_LENGTH (parm);
24989 argslen = TREE_VEC_LENGTH (arg);
24991 /* Check for pack expansions in the parameters. */
24992 for (i = 0; i < len; ++i)
24994 if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
24996 if (i == len - 1)
24997 /* We can unify against something with a trailing
24998 parameter pack. */
24999 parm_variadic_p = 1;
25000 else
25001 /* [temp.deduct.type]/9: If the template argument list of
25002 P contains a pack expansion that is not the last
25003 template argument, the entire template argument list
25004 is a non-deduced context. */
25005 return unify_success (explain_p);
25009 /* If we don't have enough arguments to satisfy the parameters
25010 (not counting the pack expression at the end), or we have
25011 too many arguments for a parameter list that doesn't end in
25012 a pack expression, we can't unify. */
25013 if (parm_variadic_p
25014 ? argslen < len - parm_variadic_p
25015 : argslen != len)
25016 return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
25018 /* Unify all of the parameters that precede the (optional)
25019 pack expression. */
25020 for (i = 0; i < len - parm_variadic_p; ++i)
25022 RECUR_AND_CHECK_FAILURE (tparms, targs,
25023 TREE_VEC_ELT (parm, i),
25024 TREE_VEC_ELT (arg, i),
25025 UNIFY_ALLOW_NONE, explain_p);
25027 if (parm_variadic_p)
25028 return unify_pack_expansion (tparms, targs, parm, arg,
25029 DEDUCE_EXACT,
25030 /*subr=*/true, explain_p);
25031 return unify_success (explain_p);
25034 case RECORD_TYPE:
25035 case UNION_TYPE:
25036 if (TREE_CODE (arg) != TREE_CODE (parm))
25037 return unify_type_mismatch (explain_p, parm, arg);
25039 if (TYPE_PTRMEMFUNC_P (parm))
25041 if (!TYPE_PTRMEMFUNC_P (arg))
25042 return unify_type_mismatch (explain_p, parm, arg);
25044 return unify (tparms, targs,
25045 TYPE_PTRMEMFUNC_FN_TYPE (parm),
25046 TYPE_PTRMEMFUNC_FN_TYPE (arg),
25047 strict, explain_p);
25049 else if (TYPE_PTRMEMFUNC_P (arg))
25050 return unify_type_mismatch (explain_p, parm, arg);
25052 if (CLASSTYPE_TEMPLATE_INFO (parm))
25054 tree t = NULL_TREE;
25056 if (strict_in & UNIFY_ALLOW_DERIVED)
25058 /* First, we try to unify the PARM and ARG directly. */
25059 t = try_class_unification (tparms, targs,
25060 parm, arg, explain_p);
25062 if (!t)
25064 /* Fallback to the special case allowed in
25065 [temp.deduct.call]:
25067 If P is a class, and P has the form
25068 template-id, then A can be a derived class of
25069 the deduced A. Likewise, if P is a pointer to
25070 a class of the form template-id, A can be a
25071 pointer to a derived class pointed to by the
25072 deduced A. */
25073 enum template_base_result r;
25074 r = get_template_base (tparms, targs, parm, arg,
25075 explain_p, &t);
25077 if (!t)
25079 /* Don't give the derived diagnostic if we're
25080 already dealing with the same template. */
25081 bool same_template
25082 = (CLASSTYPE_TEMPLATE_INFO (arg)
25083 && (CLASSTYPE_TI_TEMPLATE (parm)
25084 == CLASSTYPE_TI_TEMPLATE (arg)));
25085 return unify_no_common_base (explain_p && !same_template,
25086 r, parm, arg);
25090 else if (CLASSTYPE_TEMPLATE_INFO (arg)
25091 && (CLASSTYPE_TI_TEMPLATE (parm)
25092 == CLASSTYPE_TI_TEMPLATE (arg)))
25093 /* Perhaps PARM is something like S<U> and ARG is S<int>.
25094 Then, we should unify `int' and `U'. */
25095 t = arg;
25096 else
25097 /* There's no chance of unification succeeding. */
25098 return unify_type_mismatch (explain_p, parm, arg);
25100 if (PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)))
25101 return unify (tparms, targs,
25102 INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (parm)),
25103 INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (t)),
25104 UNIFY_ALLOW_NONE, explain_p);
25105 else
25106 return unify_success (explain_p);
25108 else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
25109 return unify_type_mismatch (explain_p, parm, arg);
25110 return unify_success (explain_p);
25112 case METHOD_TYPE:
25113 case FUNCTION_TYPE:
25115 unsigned int nargs;
25116 tree *args;
25117 tree a;
25118 unsigned int i;
25120 if (TREE_CODE (arg) != TREE_CODE (parm))
25121 return unify_type_mismatch (explain_p, parm, arg);
25123 /* CV qualifications for methods can never be deduced, they must
25124 match exactly. We need to check them explicitly here,
25125 because type_unification_real treats them as any other
25126 cv-qualified parameter. */
25127 if (TREE_CODE (parm) == METHOD_TYPE
25128 && (!check_cv_quals_for_unify
25129 (UNIFY_ALLOW_NONE,
25130 class_of_this_parm (arg),
25131 class_of_this_parm (parm))))
25132 return unify_cv_qual_mismatch (explain_p, parm, arg);
25133 if (TREE_CODE (arg) == FUNCTION_TYPE
25134 && type_memfn_quals (parm) != type_memfn_quals (arg))
25135 return unify_cv_qual_mismatch (explain_p, parm, arg);
25136 if (type_memfn_rqual (parm) != type_memfn_rqual (arg))
25137 return unify_type_mismatch (explain_p, parm, arg);
25139 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
25140 TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
25142 nargs = list_length (TYPE_ARG_TYPES (arg));
25143 args = XALLOCAVEC (tree, nargs);
25144 for (a = TYPE_ARG_TYPES (arg), i = 0;
25145 a != NULL_TREE && a != void_list_node;
25146 a = TREE_CHAIN (a), ++i)
25147 args[i] = TREE_VALUE (a);
25148 nargs = i;
25150 if (type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
25151 args, nargs, 1, DEDUCE_EXACT,
25152 NULL, explain_p))
25153 return 1;
25155 if (flag_noexcept_type)
25157 tree pspec = TYPE_RAISES_EXCEPTIONS (parm);
25158 tree aspec = canonical_eh_spec (TYPE_RAISES_EXCEPTIONS (arg));
25159 if (pspec == NULL_TREE) pspec = noexcept_false_spec;
25160 if (aspec == NULL_TREE) aspec = noexcept_false_spec;
25161 if (TREE_PURPOSE (pspec) && TREE_PURPOSE (aspec)
25162 && uses_template_parms (TREE_PURPOSE (pspec)))
25163 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_PURPOSE (pspec),
25164 TREE_PURPOSE (aspec),
25165 UNIFY_ALLOW_NONE, explain_p);
25166 else
25168 bool pn = nothrow_spec_p (pspec);
25169 bool an = nothrow_spec_p (aspec);
25170 /* Here "less cv-qual" means the deduced arg (i.e. parm) has
25171 /more/ noexcept, since function pointer conversions are the
25172 reverse of qualification conversions. */
25173 if (an == pn
25174 || (an < pn && (strict & UNIFY_ALLOW_LESS_CV_QUAL))
25175 || (an > pn && (strict & UNIFY_ALLOW_MORE_CV_QUAL)))
25176 /* OK. */;
25177 else
25178 return unify_type_mismatch (explain_p, parm, arg);
25181 if (flag_tm)
25183 /* As for noexcept. */
25184 bool pn = tx_safe_fn_type_p (parm);
25185 bool an = tx_safe_fn_type_p (arg);
25186 if (an == pn
25187 || (an < pn && (strict & UNIFY_ALLOW_LESS_CV_QUAL))
25188 || (an > pn && (strict & UNIFY_ALLOW_MORE_CV_QUAL)))
25189 /* OK. */;
25190 else
25191 return unify_type_mismatch (explain_p, parm, arg);
25194 return 0;
25197 case OFFSET_TYPE:
25198 /* Unify a pointer to member with a pointer to member function, which
25199 deduces the type of the member as a function type. */
25200 if (TYPE_PTRMEMFUNC_P (arg))
25202 /* Check top-level cv qualifiers */
25203 if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
25204 return unify_cv_qual_mismatch (explain_p, parm, arg);
25206 RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
25207 TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
25208 UNIFY_ALLOW_NONE, explain_p);
25210 /* Determine the type of the function we are unifying against. */
25211 tree fntype = static_fn_type (arg);
25213 return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
25216 if (TREE_CODE (arg) != OFFSET_TYPE)
25217 return unify_type_mismatch (explain_p, parm, arg);
25218 RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
25219 TYPE_OFFSET_BASETYPE (arg),
25220 UNIFY_ALLOW_NONE, explain_p);
25221 return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
25222 strict, explain_p);
25224 case CONST_DECL:
25225 /* CONST_DECL should already have been folded to its DECL_INITIAL. */
25226 gcc_unreachable ();
25228 case FIELD_DECL:
25229 case FUNCTION_DECL:
25230 case TEMPLATE_DECL:
25231 /* Matched cases are handled by the ARG == PARM test above. */
25232 return unify_template_argument_mismatch (explain_p, parm, arg);
25234 case VAR_DECL:
25235 /* We might get a variable as a non-type template argument in parm if the
25236 corresponding parameter is type-dependent. Make any necessary
25237 adjustments based on whether arg is a reference. */
25238 if (CONSTANT_CLASS_P (arg))
25239 parm = fold_non_dependent_expr (parm, complain);
25240 else if (REFERENCE_REF_P (arg))
25242 tree sub = TREE_OPERAND (arg, 0);
25243 STRIP_NOPS (sub);
25244 if (TREE_CODE (sub) == ADDR_EXPR)
25245 arg = TREE_OPERAND (sub, 0);
25247 /* Now use the normal expression code to check whether they match. */
25248 goto expr;
25250 case TYPE_ARGUMENT_PACK:
25251 case NONTYPE_ARGUMENT_PACK:
25252 return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
25253 ARGUMENT_PACK_ARGS (arg), strict, explain_p);
25255 case TYPEOF_TYPE:
25256 case DECLTYPE_TYPE:
25257 case TRAIT_TYPE:
25258 /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
25259 or TRAIT_TYPE nodes. */
25260 return unify_success (explain_p);
25262 case ERROR_MARK:
25263 /* Unification fails if we hit an error node. */
25264 return unify_invalid (explain_p);
25266 case INDIRECT_REF:
25267 if (REFERENCE_REF_P (parm))
25269 bool pexp = PACK_EXPANSION_P (arg);
25270 if (pexp)
25271 arg = PACK_EXPANSION_PATTERN (arg);
25272 if (REFERENCE_REF_P (arg))
25273 arg = TREE_OPERAND (arg, 0);
25274 if (pexp)
25275 arg = make_pack_expansion (arg, complain);
25276 return unify (tparms, targs, TREE_OPERAND (parm, 0), arg,
25277 strict, explain_p);
25279 /* FALLTHRU */
25281 default:
25282 /* An unresolved overload is a nondeduced context. */
25283 if (is_overloaded_fn (parm) || type_unknown_p (parm))
25284 return unify_success (explain_p);
25285 gcc_assert (EXPR_P (parm)
25286 || TREE_CODE (parm) == CONSTRUCTOR
25287 || TREE_CODE (parm) == TRAIT_EXPR);
25288 expr:
25289 /* We must be looking at an expression. This can happen with
25290 something like:
25292 template <int I>
25293 void foo(S<I>, S<I + 2>);
25297 template<typename T>
25298 void foo(A<T, T{}>);
25300 This is a "non-deduced context":
25302 [deduct.type]
25304 The non-deduced contexts are:
25306 --A non-type template argument or an array bound in which
25307 a subexpression references a template parameter.
25309 In these cases, we assume deduction succeeded, but don't
25310 actually infer any unifications. */
25312 if (!uses_template_parms (parm)
25313 && !template_args_equal (parm, arg))
25314 return unify_expression_unequal (explain_p, parm, arg);
25315 else
25316 return unify_success (explain_p);
25319 #undef RECUR_AND_CHECK_FAILURE
25321 /* Note that DECL can be defined in this translation unit, if
25322 required. */
25324 static void
25325 mark_definable (tree decl)
25327 tree clone;
25328 DECL_NOT_REALLY_EXTERN (decl) = 1;
25329 FOR_EACH_CLONE (clone, decl)
25330 DECL_NOT_REALLY_EXTERN (clone) = 1;
25333 /* Called if RESULT is explicitly instantiated, or is a member of an
25334 explicitly instantiated class. */
25336 void
25337 mark_decl_instantiated (tree result, int extern_p)
25339 SET_DECL_EXPLICIT_INSTANTIATION (result);
25341 /* If this entity has already been written out, it's too late to
25342 make any modifications. */
25343 if (TREE_ASM_WRITTEN (result))
25344 return;
25346 /* consteval functions are never emitted. */
25347 if (TREE_CODE (result) == FUNCTION_DECL
25348 && DECL_IMMEDIATE_FUNCTION_P (result))
25349 return;
25351 /* For anonymous namespace we don't need to do anything. */
25352 if (decl_internal_context_p (result))
25354 gcc_assert (!TREE_PUBLIC (result));
25355 return;
25358 if (TREE_CODE (result) != FUNCTION_DECL)
25359 /* The TREE_PUBLIC flag for function declarations will have been
25360 set correctly by tsubst. */
25361 TREE_PUBLIC (result) = 1;
25363 if (extern_p)
25365 DECL_EXTERNAL (result) = 1;
25366 DECL_NOT_REALLY_EXTERN (result) = 0;
25368 else
25370 mark_definable (result);
25371 mark_needed (result);
25372 /* Always make artificials weak. */
25373 if (DECL_ARTIFICIAL (result) && flag_weak)
25374 comdat_linkage (result);
25375 /* For WIN32 we also want to put explicit instantiations in
25376 linkonce sections. */
25377 else if (TREE_PUBLIC (result))
25378 maybe_make_one_only (result);
25379 if (TREE_CODE (result) == FUNCTION_DECL
25380 && DECL_TEMPLATE_INSTANTIATED (result))
25381 /* If the function has already been instantiated, clear DECL_EXTERNAL,
25382 since start_preparsed_function wouldn't have if we had an earlier
25383 extern explicit instantiation. */
25384 DECL_EXTERNAL (result) = 0;
25387 /* If EXTERN_P, then this function will not be emitted -- unless
25388 followed by an explicit instantiation, at which point its linkage
25389 will be adjusted. If !EXTERN_P, then this function will be
25390 emitted here. In neither circumstance do we want
25391 import_export_decl to adjust the linkage. */
25392 DECL_INTERFACE_KNOWN (result) = 1;
25395 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
25396 important template arguments. If any are missing, we check whether
25397 they're important by using error_mark_node for substituting into any
25398 args that were used for partial ordering (the ones between ARGS and END)
25399 and seeing if it bubbles up. */
25401 static bool
25402 check_undeduced_parms (tree targs, tree args, tree end)
25404 bool found = false;
25405 for (tree& targ : tree_vec_range (targs))
25406 if (targ == NULL_TREE)
25408 found = true;
25409 targ = error_mark_node;
25411 if (found)
25413 tree substed = tsubst_arg_types (args, targs, end, tf_none, NULL_TREE);
25414 if (substed == error_mark_node)
25415 return true;
25417 return false;
25420 /* Given two function templates PAT1 and PAT2, return:
25422 1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
25423 -1 if PAT2 is more specialized than PAT1.
25424 0 if neither is more specialized.
25426 LEN indicates the number of parameters we should consider
25427 (defaulted parameters should not be considered).
25429 The 1998 std underspecified function template partial ordering, and
25430 DR214 addresses the issue. We take pairs of arguments, one from
25431 each of the templates, and deduce them against each other. One of
25432 the templates will be more specialized if all the *other*
25433 template's arguments deduce against its arguments and at least one
25434 of its arguments *does* *not* deduce against the other template's
25435 corresponding argument. Deduction is done as for class templates.
25436 The arguments used in deduction have reference and top level cv
25437 qualifiers removed. Iff both arguments were originally reference
25438 types *and* deduction succeeds in both directions, an lvalue reference
25439 wins against an rvalue reference and otherwise the template
25440 with the more cv-qualified argument wins for that pairing (if
25441 neither is more cv-qualified, they both are equal). Unlike regular
25442 deduction, after all the arguments have been deduced in this way,
25443 we do *not* verify the deduced template argument values can be
25444 substituted into non-deduced contexts.
25446 The logic can be a bit confusing here, because we look at deduce1 and
25447 targs1 to see if pat2 is at least as specialized, and vice versa; if we
25448 can find template arguments for pat1 to make arg1 look like arg2, that
25449 means that arg2 is at least as specialized as arg1. */
25452 more_specialized_fn (tree pat1, tree pat2, int len)
25454 tree decl1 = DECL_TEMPLATE_RESULT (pat1);
25455 tree decl2 = DECL_TEMPLATE_RESULT (pat2);
25456 tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
25457 tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
25458 tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
25459 tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
25460 tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
25461 tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
25462 tree origs1, origs2;
25463 bool lose1 = false;
25464 bool lose2 = false;
25466 /* C++17 [temp.func.order]/3 (CWG532)
25468 If only one of the function templates M is a non-static member of some
25469 class A, M is considered to have a new first parameter inserted in its
25470 function parameter list. Given cv as the cv-qualifiers of M (if any), the
25471 new parameter is of type "rvalue reference to cv A" if the optional
25472 ref-qualifier of M is && or if M has no ref-qualifier and the first
25473 parameter of the other template has rvalue reference type. Otherwise, the
25474 new parameter is of type "lvalue reference to cv A". */
25476 if (DECL_STATIC_FUNCTION_P (decl1) || DECL_STATIC_FUNCTION_P (decl2))
25478 /* Note C++20 DR2445 extended the above to static member functions, but
25479 I think think the old G++ behavior of just skipping the object
25480 parameter when comparing to a static member function was better, so
25481 let's stick with that for now. This is CWG2834. --jason 2023-12 */
25482 if (DECL_OBJECT_MEMBER_FUNCTION_P (decl1))
25484 len--; /* LEN is the number of significant arguments for DECL1 */
25485 args1 = TREE_CHAIN (args1);
25487 else if (DECL_OBJECT_MEMBER_FUNCTION_P (decl2))
25488 args2 = TREE_CHAIN (args2);
25490 else if (DECL_IOBJ_MEMBER_FUNCTION_P (decl1)
25491 && DECL_IOBJ_MEMBER_FUNCTION_P (decl2))
25493 /* Note DR2445 also (IMO wrongly) removed the "only one" above, which
25494 would break e.g. cpp1y/lambda-generic-variadic5.C. */
25495 len--;
25496 args1 = TREE_CHAIN (args1);
25497 args2 = TREE_CHAIN (args2);
25499 else if (DECL_IOBJ_MEMBER_FUNCTION_P (decl1)
25500 || DECL_IOBJ_MEMBER_FUNCTION_P (decl2))
25502 /* The other is a non-member or explicit object member function;
25503 rewrite the implicit object parameter to a reference. */
25504 tree ns = DECL_IOBJ_MEMBER_FUNCTION_P (decl2) ? decl2 : decl1;
25505 tree &nsargs = ns == decl2 ? args2 : args1;
25506 tree obtype = TREE_TYPE (TREE_VALUE (nsargs));
25508 nsargs = TREE_CHAIN (nsargs);
25510 cp_ref_qualifier rqual = type_memfn_rqual (TREE_TYPE (ns));
25511 if (rqual == REF_QUAL_NONE)
25513 tree otherfirst = ns == decl1 ? args2 : args1;
25514 otherfirst = TREE_VALUE (otherfirst);
25515 if (TREE_CODE (otherfirst) == REFERENCE_TYPE
25516 && TYPE_REF_IS_RVALUE (otherfirst))
25517 rqual = REF_QUAL_RVALUE;
25519 obtype = cp_build_reference_type (obtype, rqual == REF_QUAL_RVALUE);
25520 nsargs = tree_cons (NULL_TREE, obtype, nsargs);
25523 /* If only one is a conversion operator, they are unordered. */
25524 if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
25525 return 0;
25527 /* Consider the return type for a conversion function */
25528 if (DECL_CONV_FN_P (decl1))
25530 args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
25531 args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
25532 len++;
25535 processing_template_decl++;
25537 origs1 = args1;
25538 origs2 = args2;
25540 while (len--
25541 /* Stop when an ellipsis is seen. */
25542 && args1 != NULL_TREE && args2 != NULL_TREE)
25544 tree arg1 = TREE_VALUE (args1);
25545 tree arg2 = TREE_VALUE (args2);
25546 int deduce1, deduce2;
25547 int quals1 = -1;
25548 int quals2 = -1;
25549 int ref1 = 0;
25550 int ref2 = 0;
25552 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
25553 && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25555 /* When both arguments are pack expansions, we need only
25556 unify the patterns themselves. */
25557 arg1 = PACK_EXPANSION_PATTERN (arg1);
25558 arg2 = PACK_EXPANSION_PATTERN (arg2);
25560 /* This is the last comparison we need to do. */
25561 len = 0;
25564 if (TYPE_REF_P (arg1))
25566 ref1 = TYPE_REF_IS_RVALUE (arg1) + 1;
25567 arg1 = TREE_TYPE (arg1);
25568 quals1 = cp_type_quals (arg1);
25571 if (TYPE_REF_P (arg2))
25573 ref2 = TYPE_REF_IS_RVALUE (arg2) + 1;
25574 arg2 = TREE_TYPE (arg2);
25575 quals2 = cp_type_quals (arg2);
25578 arg1 = TYPE_MAIN_VARIANT (arg1);
25579 arg2 = TYPE_MAIN_VARIANT (arg2);
25581 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
25583 int i, len2 = remaining_arguments (args2);
25584 tree parmvec = make_tree_vec (1);
25585 tree argvec = make_tree_vec (len2);
25586 tree ta = args2;
25588 /* Setup the parameter vector, which contains only ARG1. */
25589 TREE_VEC_ELT (parmvec, 0) = arg1;
25591 /* Setup the argument vector, which contains the remaining
25592 arguments. */
25593 for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
25594 TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
25596 deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
25597 argvec, DEDUCE_EXACT,
25598 /*subr=*/true, /*explain_p=*/false)
25599 == 0);
25601 /* We cannot deduce in the other direction, because ARG1 is
25602 a pack expansion but ARG2 is not. */
25603 deduce2 = 0;
25605 else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25607 int i, len1 = remaining_arguments (args1);
25608 tree parmvec = make_tree_vec (1);
25609 tree argvec = make_tree_vec (len1);
25610 tree ta = args1;
25612 /* Setup the parameter vector, which contains only ARG1. */
25613 TREE_VEC_ELT (parmvec, 0) = arg2;
25615 /* Setup the argument vector, which contains the remaining
25616 arguments. */
25617 for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
25618 TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
25620 deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
25621 argvec, DEDUCE_EXACT,
25622 /*subr=*/true, /*explain_p=*/false)
25623 == 0);
25625 /* We cannot deduce in the other direction, because ARG2 is
25626 a pack expansion but ARG1 is not.*/
25627 deduce1 = 0;
25630 else
25632 /* The normal case, where neither argument is a pack
25633 expansion. */
25634 deduce1 = (unify (tparms1, targs1, arg1, arg2,
25635 UNIFY_ALLOW_NONE, /*explain_p=*/false)
25636 == 0);
25637 deduce2 = (unify (tparms2, targs2, arg2, arg1,
25638 UNIFY_ALLOW_NONE, /*explain_p=*/false)
25639 == 0);
25642 /* If we couldn't deduce arguments for tparms1 to make arg1 match
25643 arg2, then arg2 is not as specialized as arg1. */
25644 if (!deduce1)
25645 lose2 = true;
25646 if (!deduce2)
25647 lose1 = true;
25649 /* "If, for a given type, deduction succeeds in both directions
25650 (i.e., the types are identical after the transformations above)
25651 and both P and A were reference types (before being replaced with
25652 the type referred to above):
25653 - if the type from the argument template was an lvalue reference and
25654 the type from the parameter template was not, the argument type is
25655 considered to be more specialized than the other; otherwise,
25656 - if the type from the argument template is more cv-qualified
25657 than the type from the parameter template (as described above),
25658 the argument type is considered to be more specialized than the other;
25659 otherwise,
25660 - neither type is more specialized than the other." */
25662 if (deduce1 && deduce2)
25664 if (ref1 && ref2 && ref1 != ref2)
25666 if (ref1 > ref2)
25667 lose1 = true;
25668 else
25669 lose2 = true;
25671 else if (quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
25673 if ((quals1 & quals2) == quals2)
25674 lose2 = true;
25675 if ((quals1 & quals2) == quals1)
25676 lose1 = true;
25680 if (lose1 && lose2)
25681 /* We've failed to deduce something in either direction.
25682 These must be unordered. */
25683 break;
25685 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
25686 || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25687 /* We have already processed all of the arguments in our
25688 handing of the pack expansion type. */
25689 len = 0;
25691 args1 = TREE_CHAIN (args1);
25692 args2 = TREE_CHAIN (args2);
25695 /* "In most cases, all template parameters must have values in order for
25696 deduction to succeed, but for partial ordering purposes a template
25697 parameter may remain without a value provided it is not used in the
25698 types being used for partial ordering."
25700 Thus, if we are missing any of the targs1 we need to substitute into
25701 origs1, then pat2 is not as specialized as pat1. This can happen when
25702 there is a nondeduced context. */
25703 if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
25704 lose2 = true;
25705 if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
25706 lose1 = true;
25708 processing_template_decl--;
25710 /* If both deductions succeed, the partial ordering selects the more
25711 constrained template. */
25712 /* P2113: If the corresponding template-parameters of the
25713 template-parameter-lists are not equivalent ([temp.over.link]) or if
25714 the function parameters that positionally correspond between the two
25715 templates are not of the same type, neither template is more
25716 specialized than the other. */
25717 if (!lose1 && !lose2
25718 && comp_template_parms (DECL_TEMPLATE_PARMS (pat1),
25719 DECL_TEMPLATE_PARMS (pat2))
25720 && compparms (origs1, origs2))
25722 int winner = more_constrained (decl1, decl2);
25723 if (winner > 0)
25724 lose2 = true;
25725 else if (winner < 0)
25726 lose1 = true;
25729 /* All things being equal, if the next argument is a pack expansion
25730 for one function but not for the other, prefer the
25731 non-variadic function. FIXME this is bogus; see c++/41958. */
25732 if (lose1 == lose2
25733 && args1 && TREE_VALUE (args1)
25734 && args2 && TREE_VALUE (args2))
25736 lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
25737 lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
25740 if (lose1 == lose2)
25741 return 0;
25742 else if (!lose1)
25743 return 1;
25744 else
25745 return -1;
25748 /* Determine which of two partial specializations of TMPL is more
25749 specialized.
25751 PAT1 is a TREE_LIST whose TREE_VALUE is the TEMPLATE_DECL corresponding
25752 to the first partial specialization. The TREE_PURPOSE is the
25753 innermost set of template parameters for the partial
25754 specialization. PAT2 is similar, but for the second template.
25756 Return 1 if the first partial specialization is more specialized;
25757 -1 if the second is more specialized; 0 if neither is more
25758 specialized.
25760 See [temp.class.order] for information about determining which of
25761 two templates is more specialized. */
25763 static int
25764 more_specialized_partial_spec (tree tmpl, tree pat1, tree pat2)
25766 tree targs;
25767 int winner = 0;
25768 bool any_deductions = false;
25770 tree tmpl1 = TREE_VALUE (pat1);
25771 tree tmpl2 = TREE_VALUE (pat2);
25772 tree specargs1 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl1)));
25773 tree specargs2 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl2)));
25775 /* Just like what happens for functions, if we are ordering between
25776 different template specializations, we may encounter dependent
25777 types in the arguments, and we need our dependency check functions
25778 to behave correctly. */
25779 ++processing_template_decl;
25780 targs = get_partial_spec_bindings (tmpl, tmpl1, specargs2);
25781 if (targs)
25783 --winner;
25784 any_deductions = true;
25787 targs = get_partial_spec_bindings (tmpl, tmpl2, specargs1);
25788 if (targs)
25790 ++winner;
25791 any_deductions = true;
25793 --processing_template_decl;
25795 /* If both deductions succeed, the partial ordering selects the more
25796 constrained template. */
25797 if (!winner && any_deductions)
25798 winner = more_constrained (tmpl1, tmpl2);
25800 /* In the case of a tie where at least one of the templates
25801 has a parameter pack at the end, the template with the most
25802 non-packed parameters wins. */
25803 if (winner == 0
25804 && any_deductions
25805 && (template_args_variadic_p (TREE_PURPOSE (pat1))
25806 || template_args_variadic_p (TREE_PURPOSE (pat2))))
25808 tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
25809 tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
25810 int len1 = TREE_VEC_LENGTH (args1);
25811 int len2 = TREE_VEC_LENGTH (args2);
25813 /* We don't count the pack expansion at the end. */
25814 if (template_args_variadic_p (TREE_PURPOSE (pat1)))
25815 --len1;
25816 if (template_args_variadic_p (TREE_PURPOSE (pat2)))
25817 --len2;
25819 if (len1 > len2)
25820 return 1;
25821 else if (len1 < len2)
25822 return -1;
25825 return winner;
25828 /* Return the template arguments that will produce the function signature
25829 DECL from the function template FN, with the explicit template
25830 arguments EXPLICIT_ARGS. If CHECK_RETTYPE is true, the return type must
25831 also match. Return NULL_TREE if no satisfactory arguments could be
25832 found. */
25834 static tree
25835 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
25837 int ntparms = DECL_NTPARMS (fn);
25838 tree targs = make_tree_vec (ntparms);
25839 tree decl_type = TREE_TYPE (decl);
25840 tree decl_arg_types;
25841 tree *args;
25842 unsigned int nargs, ix;
25843 tree arg;
25845 gcc_assert (decl != DECL_TEMPLATE_RESULT (fn));
25847 /* Never do unification on the 'this' parameter. */
25848 decl_arg_types = skip_artificial_parms_for (decl,
25849 TYPE_ARG_TYPES (decl_type));
25851 nargs = list_length (decl_arg_types);
25852 args = XALLOCAVEC (tree, nargs);
25853 for (arg = decl_arg_types, ix = 0;
25854 arg != NULL_TREE;
25855 arg = TREE_CHAIN (arg), ++ix)
25856 args[ix] = TREE_VALUE (arg);
25858 if (fn_type_unification (fn, explicit_args, targs,
25859 args, ix,
25860 (check_rettype || DECL_CONV_FN_P (fn)
25861 ? TREE_TYPE (decl_type) : NULL_TREE),
25862 DEDUCE_EXACT, LOOKUP_NORMAL, NULL,
25863 /*explain_p=*/false,
25864 /*decltype*/false)
25865 == error_mark_node)
25866 return NULL_TREE;
25868 return targs;
25871 /* Return the innermost template arguments that, when applied to a partial
25872 specialization SPEC_TMPL of TMPL, yield the ARGS.
25874 For example, suppose we have:
25876 template <class T, class U> struct S {};
25877 template <class T> struct S<T*, int> {};
25879 Then, suppose we want to get `S<double*, int>'. SPEC_TMPL will be the
25880 partial specialization and the ARGS will be {double*, int}. The resulting
25881 vector will be {double}, indicating that `T' is bound to `double'. */
25883 static tree
25884 get_partial_spec_bindings (tree tmpl, tree spec_tmpl, tree args)
25886 tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (spec_tmpl);
25887 tree spec_args
25888 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (spec_tmpl)));
25889 int i, ntparms = TREE_VEC_LENGTH (tparms);
25890 tree deduced_args;
25891 tree innermost_deduced_args;
25893 innermost_deduced_args = make_tree_vec (ntparms);
25894 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
25896 deduced_args = copy_node (args);
25897 SET_TMPL_ARGS_LEVEL (deduced_args,
25898 TMPL_ARGS_DEPTH (deduced_args),
25899 innermost_deduced_args);
25901 else
25902 deduced_args = innermost_deduced_args;
25904 bool tried_array_deduction = (cxx_dialect < cxx17);
25905 again:
25906 if (unify (tparms, deduced_args,
25907 INNERMOST_TEMPLATE_ARGS (spec_args),
25908 INNERMOST_TEMPLATE_ARGS (args),
25909 UNIFY_ALLOW_NONE, /*explain_p=*/false))
25910 return NULL_TREE;
25912 for (i = 0; i < ntparms; ++i)
25913 if (! TREE_VEC_ELT (innermost_deduced_args, i))
25915 if (!tried_array_deduction)
25917 try_array_deduction (tparms, innermost_deduced_args,
25918 INNERMOST_TEMPLATE_ARGS (spec_args));
25919 tried_array_deduction = true;
25920 if (TREE_VEC_ELT (innermost_deduced_args, i))
25921 goto again;
25923 return NULL_TREE;
25926 if (!push_tinst_level (spec_tmpl, deduced_args))
25928 excessive_deduction_depth = true;
25929 return NULL_TREE;
25932 /* Verify that nondeduced template arguments agree with the type
25933 obtained from argument deduction.
25935 For example:
25937 struct A { typedef int X; };
25938 template <class T, class U> struct C {};
25939 template <class T> struct C<T, typename T::X> {};
25941 Then with the instantiation `C<A, int>', we can deduce that
25942 `T' is `A' but unify () does not check whether `typename T::X'
25943 is `int'. */
25944 spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
25946 if (spec_args != error_mark_node)
25947 spec_args = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
25948 INNERMOST_TEMPLATE_ARGS (spec_args),
25949 tmpl, tf_none, false);
25951 pop_tinst_level ();
25953 if (spec_args == error_mark_node
25954 /* We only need to check the innermost arguments; the other
25955 arguments will always agree. */
25956 || !comp_template_args_porder (INNERMOST_TEMPLATE_ARGS (spec_args),
25957 INNERMOST_TEMPLATE_ARGS (args)))
25958 return NULL_TREE;
25960 /* Now that we have bindings for all of the template arguments,
25961 ensure that the arguments deduced for the template template
25962 parameters have compatible template parameter lists. See the use
25963 of template_template_parm_bindings_ok_p in fn_type_unification
25964 for more information. */
25965 if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
25966 return NULL_TREE;
25968 return deduced_args;
25971 // Compare two function templates T1 and T2 by deducing bindings
25972 // from one against the other. If both deductions succeed, compare
25973 // constraints to see which is more constrained.
25974 static int
25975 more_specialized_inst (tree t1, tree t2)
25977 int fate = 0;
25978 int count = 0;
25980 if (get_bindings (t1, DECL_TEMPLATE_RESULT (t2), NULL_TREE, true))
25982 --fate;
25983 ++count;
25986 if (get_bindings (t2, DECL_TEMPLATE_RESULT (t1), NULL_TREE, true))
25988 ++fate;
25989 ++count;
25992 // If both deductions succeed, then one may be more constrained.
25993 if (count == 2 && fate == 0)
25994 fate = more_constrained (t1, t2);
25996 return fate;
25999 /* TEMPLATES is a TREE_LIST. Each TREE_VALUE is a TEMPLATE_DECL.
26000 Return the TREE_LIST node with the most specialized template, if
26001 any. If there is no most specialized template, the error_mark_node
26002 is returned.
26004 Note that this function does not look at, or modify, the
26005 TREE_PURPOSE or TREE_TYPE of any of the nodes. Since the node
26006 returned is one of the elements of INSTANTIATIONS, callers may
26007 store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
26008 and retrieve it from the value returned. */
26010 tree
26011 most_specialized_instantiation (tree templates)
26013 tree fn, champ;
26015 ++processing_template_decl;
26017 champ = templates;
26018 for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
26020 gcc_assert (TREE_VALUE (champ) != TREE_VALUE (fn));
26021 int fate = more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn));
26022 if (fate == -1)
26023 champ = fn;
26024 else if (!fate)
26026 /* Equally specialized, move to next function. If there
26027 is no next function, nothing's most specialized. */
26028 fn = TREE_CHAIN (fn);
26029 champ = fn;
26030 if (!fn)
26031 break;
26035 if (champ)
26036 /* Now verify that champ is better than everything earlier in the
26037 instantiation list. */
26038 for (fn = templates; fn != champ; fn = TREE_CHAIN (fn)) {
26039 if (more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn)) != 1)
26041 champ = NULL_TREE;
26042 break;
26046 processing_template_decl--;
26048 if (!champ)
26049 return error_mark_node;
26051 return champ;
26054 /* If DECL is a specialization of some template, return the most
26055 general such template. Otherwise, returns NULL_TREE.
26057 For example, given:
26059 template <class T> struct S { template <class U> void f(U); };
26061 if TMPL is `template <class U> void S<int>::f(U)' this will return
26062 the full template. This function will not trace past partial
26063 specializations, however. For example, given in addition:
26065 template <class T> struct S<T*> { template <class U> void f(U); };
26067 if TMPL is `template <class U> void S<int*>::f(U)' this will return
26068 `template <class T> template <class U> S<T*>::f(U)'. */
26070 tree
26071 most_general_template (const_tree decl)
26073 if (TREE_CODE (decl) != TEMPLATE_DECL)
26075 if (tree tinfo = get_template_info (decl))
26076 decl = TI_TEMPLATE (tinfo);
26077 /* The TI_TEMPLATE can be an IDENTIFIER_NODE for a
26078 template friend, or a FIELD_DECL for a capture pack. */
26079 if (TREE_CODE (decl) != TEMPLATE_DECL)
26080 return NULL_TREE;
26083 if (DECL_TEMPLATE_TEMPLATE_PARM_P (decl))
26084 return DECL_TI_TEMPLATE (DECL_TEMPLATE_RESULT (decl));
26086 /* Look for more and more general templates. */
26087 while (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
26089 /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
26090 (See cp-tree.h for details.) */
26091 if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
26092 break;
26094 if (CLASS_TYPE_P (TREE_TYPE (decl))
26095 && !TYPE_DECL_ALIAS_P (TYPE_NAME (TREE_TYPE (decl)))
26096 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
26097 break;
26099 /* Stop if we run into an explicitly specialized class template. */
26100 if (!DECL_NAMESPACE_SCOPE_P (decl)
26101 && DECL_CONTEXT (decl)
26102 && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
26103 break;
26105 decl = DECL_TI_TEMPLATE (decl);
26108 return CONST_CAST_TREE (decl);
26111 /* Return the most specialized of the template partial specializations
26112 which can produce TARGET, a specialization of some class or variable
26113 template. The value returned is a TEMPLATE_INFO; the TI_TEMPLATE is a
26114 TEMPLATE_DECL node corresponding to the partial specialization, while
26115 the TI_ARGS is the set of template arguments that must be substituted
26116 into the template pattern in order to generate TARGET. The result is
26117 cached in the TI_PARTIAL_INFO of the corresponding TEMPLATE_INFO unless
26118 RECHECKING is true.
26120 If the choice of partial specialization is ambiguous, a diagnostic
26121 is issued, and the error_mark_node is returned. If there are no
26122 partial specializations matching TARGET, then NULL_TREE is
26123 returned, indicating that the primary template should be used. */
26125 tree
26126 most_specialized_partial_spec (tree target, tsubst_flags_t complain,
26127 bool rechecking /* = false */)
26129 tree tinfo = NULL_TREE;
26130 tree tmpl, args, decl;
26131 if (TYPE_P (target))
26133 tinfo = CLASSTYPE_TEMPLATE_INFO (target);
26134 tmpl = TI_TEMPLATE (tinfo);
26135 args = TI_ARGS (tinfo);
26136 decl = TYPE_NAME (target);
26138 else if (TREE_CODE (target) == TEMPLATE_ID_EXPR)
26140 tmpl = TREE_OPERAND (target, 0);
26141 args = TREE_OPERAND (target, 1);
26142 decl = DECL_TEMPLATE_RESULT (tmpl);
26144 else if (VAR_P (target))
26146 tinfo = DECL_TEMPLATE_INFO (target);
26147 tmpl = TI_TEMPLATE (tinfo);
26148 args = TI_ARGS (tinfo);
26149 decl = target;
26151 else
26152 gcc_unreachable ();
26154 if (!PRIMARY_TEMPLATE_P (tmpl))
26155 return NULL_TREE;
26157 if (!rechecking
26158 && tinfo
26159 && (VAR_P (target) || COMPLETE_TYPE_P (target)))
26160 return TI_PARTIAL_INFO (tinfo);
26162 tree main_tmpl = most_general_template (tmpl);
26163 tree specs = DECL_TEMPLATE_SPECIALIZATIONS (main_tmpl);
26164 if (!specs)
26165 /* There are no partial specializations of this template. */
26166 return NULL_TREE;
26168 push_access_scope_guard pas (decl);
26169 deferring_access_check_sentinel acs (dk_no_deferred);
26171 /* For determining which partial specialization to use, only the
26172 innermost args are interesting. */
26173 tree outer_args = NULL_TREE;
26174 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
26176 outer_args = strip_innermost_template_args (args, 1);
26177 args = INNERMOST_TEMPLATE_ARGS (args);
26180 /* The caller hasn't called push_to_top_level yet, but we need
26181 get_partial_spec_bindings to be done in non-template context so that we'll
26182 fully resolve everything. */
26183 processing_template_decl_sentinel ptds;
26185 tree list = NULL_TREE;
26186 for (tree t = specs; t; t = TREE_CHAIN (t))
26188 const tree ospec_tmpl = TREE_VALUE (t);
26190 tree spec_tmpl;
26191 if (outer_args)
26193 /* Substitute in the template args from the enclosing class. */
26194 ++processing_template_decl;
26195 spec_tmpl = tsubst (ospec_tmpl, outer_args, tf_none, NULL_TREE);
26196 --processing_template_decl;
26197 if (spec_tmpl == error_mark_node)
26198 return error_mark_node;
26200 else
26201 spec_tmpl = ospec_tmpl;
26203 tree spec_args = get_partial_spec_bindings (tmpl, spec_tmpl, args);
26204 if (spec_args)
26206 if (outer_args)
26207 spec_args = add_to_template_args (outer_args, spec_args);
26209 /* Keep the candidate only if its constraints are satisfied. */
26210 if (constraints_satisfied_p (ospec_tmpl, spec_args))
26211 list = tree_cons (spec_args, ospec_tmpl, list);
26215 if (! list)
26216 return NULL_TREE;
26218 tree champ = list;
26219 bool ambiguous_p = false;
26220 for (tree t = TREE_CHAIN (list); t; t = TREE_CHAIN (t))
26222 int fate = more_specialized_partial_spec (tmpl, champ, t);
26223 if (fate == 1)
26225 else
26227 if (fate == 0)
26229 t = TREE_CHAIN (t);
26230 if (! t)
26232 ambiguous_p = true;
26233 break;
26236 champ = t;
26240 if (!ambiguous_p)
26241 for (tree t = list; t && t != champ; t = TREE_CHAIN (t))
26243 int fate = more_specialized_partial_spec (tmpl, champ, t);
26244 if (fate != 1)
26246 ambiguous_p = true;
26247 break;
26251 if (ambiguous_p)
26253 const char *str;
26254 char *spaces = NULL;
26255 if (!(complain & tf_error))
26256 return error_mark_node;
26257 if (TYPE_P (target))
26258 error ("ambiguous template instantiation for %q#T", target);
26259 else
26260 error ("ambiguous template instantiation for %q#D", target);
26261 str = ngettext ("candidate is:", "candidates are:", list_length (list));
26262 for (tree t = list; t; t = TREE_CHAIN (t))
26264 tree subst = build_tree_list (TREE_VALUE (t), TREE_PURPOSE (t));
26265 inform (DECL_SOURCE_LOCATION (TREE_VALUE (t)),
26266 "%s %#qS", spaces ? spaces : str, subst);
26267 spaces = spaces ? spaces : get_spaces (str);
26269 free (spaces);
26270 return error_mark_node;
26273 tree result = build_template_info (TREE_VALUE (champ), TREE_PURPOSE (champ));
26274 if (!rechecking && tinfo)
26275 TI_PARTIAL_INFO (tinfo) = result;
26276 return result;
26279 /* Explicitly instantiate DECL. */
26281 void
26282 do_decl_instantiation (tree decl, tree storage)
26284 tree result = NULL_TREE;
26285 int extern_p = 0;
26287 if (!decl || decl == error_mark_node)
26288 /* An error occurred, for which grokdeclarator has already issued
26289 an appropriate message. */
26290 return;
26291 else if (! DECL_LANG_SPECIFIC (decl))
26293 error ("explicit instantiation of non-template %q#D", decl);
26294 return;
26296 else if (DECL_DECLARED_CONCEPT_P (decl))
26298 if (VAR_P (decl))
26299 error ("explicit instantiation of variable concept %q#D", decl);
26300 else
26301 error ("explicit instantiation of function concept %q#D", decl);
26302 return;
26305 bool var_templ = (DECL_TEMPLATE_INFO (decl)
26306 && variable_template_p (DECL_TI_TEMPLATE (decl)));
26308 if (VAR_P (decl) && !var_templ)
26310 /* There is an asymmetry here in the way VAR_DECLs and
26311 FUNCTION_DECLs are handled by grokdeclarator. In the case of
26312 the latter, the DECL we get back will be marked as a
26313 template instantiation, and the appropriate
26314 DECL_TEMPLATE_INFO will be set up. This does not happen for
26315 VAR_DECLs so we do the lookup here. Probably, grokdeclarator
26316 should handle VAR_DECLs as it currently handles
26317 FUNCTION_DECLs. */
26318 if (!DECL_CLASS_SCOPE_P (decl))
26320 error ("%qD is not a static data member of a class template", decl);
26321 return;
26323 result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
26324 if (!result || !VAR_P (result))
26326 error ("no matching template for %qD found", decl);
26327 return;
26329 if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
26331 error ("type %qT for explicit instantiation %qD does not match "
26332 "declared type %qT", TREE_TYPE (result), decl,
26333 TREE_TYPE (decl));
26334 return;
26337 else if (TREE_CODE (decl) != FUNCTION_DECL && !var_templ)
26339 error ("explicit instantiation of %q#D", decl);
26340 return;
26342 else
26343 result = decl;
26345 /* Check for various error cases. Note that if the explicit
26346 instantiation is valid the RESULT will currently be marked as an
26347 *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
26348 until we get here. */
26350 if (DECL_TEMPLATE_SPECIALIZATION (result))
26352 /* DR 259 [temp.spec].
26354 Both an explicit instantiation and a declaration of an explicit
26355 specialization shall not appear in a program unless the explicit
26356 instantiation follows a declaration of the explicit specialization.
26358 For a given set of template parameters, if an explicit
26359 instantiation of a template appears after a declaration of an
26360 explicit specialization for that template, the explicit
26361 instantiation has no effect. */
26362 return;
26364 else if (DECL_EXPLICIT_INSTANTIATION (result))
26366 /* [temp.spec]
26368 No program shall explicitly instantiate any template more
26369 than once.
26371 We check DECL_NOT_REALLY_EXTERN so as not to complain when
26372 the first instantiation was `extern' and the second is not,
26373 and EXTERN_P for the opposite case. */
26374 if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
26375 permerror (input_location, "duplicate explicit instantiation of %q#D", result);
26376 /* If an "extern" explicit instantiation follows an ordinary
26377 explicit instantiation, the template is instantiated. */
26378 if (extern_p)
26379 return;
26381 else if (!DECL_IMPLICIT_INSTANTIATION (result))
26383 error ("no matching template for %qD found", result);
26384 return;
26386 else if (!DECL_TEMPLATE_INFO (result))
26388 permerror (input_location, "explicit instantiation of non-template %q#D", result);
26389 return;
26392 if (storage == NULL_TREE)
26394 else if (storage == ridpointers[(int) RID_EXTERN])
26396 if (cxx_dialect == cxx98)
26397 pedwarn (input_location, OPT_Wpedantic,
26398 "ISO C++ 1998 forbids the use of %<extern%> on explicit "
26399 "instantiations");
26400 extern_p = 1;
26402 else
26403 error ("storage class %qD applied to template instantiation", storage);
26405 check_explicit_instantiation_namespace (result);
26406 mark_decl_instantiated (result, extern_p);
26407 if (! extern_p)
26408 instantiate_decl (result, /*defer_ok=*/true,
26409 /*expl_inst_class_mem_p=*/false);
26412 static void
26413 mark_class_instantiated (tree t, int extern_p)
26415 SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
26416 SET_CLASSTYPE_INTERFACE_KNOWN (t);
26417 CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
26418 TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
26419 if (! extern_p)
26421 CLASSTYPE_DEBUG_REQUESTED (t) = 1;
26422 rest_of_type_compilation (t, 1);
26426 /* Perform an explicit instantiation of template class T. STORAGE, if
26427 non-null, is the RID for extern, inline or static. COMPLAIN is
26428 nonzero if this is called from the parser, zero if called recursively,
26429 since the standard is unclear (as detailed below). */
26431 void
26432 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
26434 if (!(CLASS_TYPE_P (t) && CLASSTYPE_TEMPLATE_INFO (t)))
26436 if (tree ti = TYPE_TEMPLATE_INFO (t))
26437 error ("explicit instantiation of non-class template %qD",
26438 TI_TEMPLATE (ti));
26439 else
26440 error ("explicit instantiation of non-template type %qT", t);
26441 return;
26444 complete_type (t);
26446 if (!COMPLETE_TYPE_P (t))
26448 if (complain & tf_error)
26449 error ("explicit instantiation of %q#T before definition of template",
26451 return;
26454 /* At most one of these will be true. */
26455 bool extern_p = false;
26456 bool nomem_p = false;
26457 bool static_p = false;
26459 if (storage != NULL_TREE)
26461 if (storage == ridpointers[(int) RID_EXTERN])
26463 if (cxx_dialect == cxx98)
26464 pedwarn (input_location, OPT_Wpedantic,
26465 "ISO C++ 1998 forbids the use of %<extern%> on "
26466 "explicit instantiations");
26468 else
26469 pedwarn (input_location, OPT_Wpedantic,
26470 "ISO C++ forbids the use of %qE"
26471 " on explicit instantiations", storage);
26473 if (storage == ridpointers[(int) RID_INLINE])
26474 nomem_p = true;
26475 else if (storage == ridpointers[(int) RID_EXTERN])
26476 extern_p = true;
26477 else if (storage == ridpointers[(int) RID_STATIC])
26478 static_p = true;
26479 else
26480 error ("storage class %qD applied to template instantiation",
26481 storage);
26484 if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
26485 /* DR 259 [temp.spec].
26487 Both an explicit instantiation and a declaration of an explicit
26488 specialization shall not appear in a program unless the
26489 explicit instantiation follows a declaration of the explicit
26490 specialization.
26492 For a given set of template parameters, if an explicit
26493 instantiation of a template appears after a declaration of an
26494 explicit specialization for that template, the explicit
26495 instantiation has no effect. */
26496 return;
26498 if (CLASSTYPE_EXPLICIT_INSTANTIATION (t) && !CLASSTYPE_INTERFACE_ONLY (t))
26500 /* We've already instantiated the template. */
26502 /* [temp.spec]
26504 No program shall explicitly instantiate any template more
26505 than once.
26507 If EXTERN_P then this is ok. */
26508 if (!extern_p && (complain & tf_error))
26509 permerror (input_location,
26510 "duplicate explicit instantiation of %q#T", t);
26512 return;
26515 check_explicit_instantiation_namespace (TYPE_NAME (t));
26516 mark_class_instantiated (t, extern_p);
26518 if (nomem_p)
26519 return;
26521 /* In contrast to implicit instantiation, where only the
26522 declarations, and not the definitions, of members are
26523 instantiated, we have here:
26525 [temp.explicit]
26527 An explicit instantiation that names a class template
26528 specialization is also an explicit instantiation of the same
26529 kind (declaration or definition) of each of its members (not
26530 including members inherited from base classes and members
26531 that are templates) that has not been previously explicitly
26532 specialized in the translation unit containing the explicit
26533 instantiation, provided that the associated constraints, if
26534 any, of that member are satisfied by the template arguments
26535 of the explicit instantiation. */
26536 for (tree fld = TYPE_FIELDS (t); fld; fld = DECL_CHAIN (fld))
26537 if ((VAR_P (fld)
26538 || (TREE_CODE (fld) == FUNCTION_DECL
26539 && !static_p
26540 && user_provided_p (fld)))
26541 && DECL_TEMPLATE_INSTANTIATION (fld)
26542 && constraints_satisfied_p (fld))
26544 mark_decl_instantiated (fld, extern_p);
26545 if (! extern_p)
26546 instantiate_decl (fld, /*defer_ok=*/true,
26547 /*expl_inst_class_mem_p=*/true);
26549 else if (DECL_IMPLICIT_TYPEDEF_P (fld))
26551 tree type = TREE_TYPE (fld);
26553 if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
26554 && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
26555 do_type_instantiation (type, storage, 0);
26559 /* Given a function DECL, which is a specialization of TMPL, modify
26560 DECL to be a re-instantiation of TMPL with the same template
26561 arguments. TMPL should be the template into which tsubst'ing
26562 should occur for DECL, not the most general template.
26564 One reason for doing this is a scenario like this:
26566 template <class T>
26567 void f(const T&, int i);
26569 void g() { f(3, 7); }
26571 template <class T>
26572 void f(const T& t, const int i) { }
26574 Note that when the template is first instantiated, with
26575 instantiate_template, the resulting DECL will have no name for the
26576 first parameter, and the wrong type for the second. So, when we go
26577 to instantiate the DECL, we regenerate it. */
26579 static void
26580 regenerate_decl_from_template (tree decl, tree tmpl, tree args)
26582 /* The arguments used to instantiate DECL, from the most general
26583 template. */
26584 tree code_pattern = DECL_TEMPLATE_RESULT (tmpl);
26586 /* Make sure that we can see identifiers, and compute access correctly. */
26587 push_access_scope (decl);
26589 if (TREE_CODE (decl) == FUNCTION_DECL)
26591 tree specs;
26592 int args_depth;
26593 int parms_depth;
26595 /* Don't bother with this for unique friends that can't be redeclared and
26596 might change type if regenerated (PR69836). */
26597 if (DECL_UNIQUE_FRIEND_P (decl))
26598 goto done;
26600 /* Use the source location of the definition. */
26601 DECL_SOURCE_LOCATION (decl) = DECL_SOURCE_LOCATION (tmpl);
26603 args_depth = TMPL_ARGS_DEPTH (args);
26604 parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
26605 if (args_depth > parms_depth)
26606 args = get_innermost_template_args (args, parms_depth);
26608 /* Instantiate a dynamic exception-specification. noexcept will be
26609 handled below. */
26610 if (tree raises = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (code_pattern)))
26611 if (TREE_VALUE (raises))
26613 specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
26614 args, tf_error, NULL_TREE,
26615 /*defer_ok*/false);
26616 if (specs && specs != error_mark_node)
26617 TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
26618 specs);
26621 /* Merge parameter declarations. */
26622 if (tree pattern_parm
26623 = skip_artificial_parms_for (code_pattern,
26624 DECL_ARGUMENTS (code_pattern)))
26626 tree *p = &DECL_ARGUMENTS (decl);
26627 for (int skip = num_artificial_parms_for (decl); skip; --skip)
26628 p = &DECL_CHAIN (*p);
26629 *p = tsubst_decl (pattern_parm, args, tf_error);
26630 for (tree t = *p; t; t = DECL_CHAIN (t))
26631 DECL_CONTEXT (t) = decl;
26634 if (DECL_CONTRACTS (decl))
26636 /* If we're regenerating a specialization, the contracts will have
26637 been copied from the most general template. Replace those with
26638 the ones from the actual specialization. */
26639 tree tmpl = DECL_TI_TEMPLATE (decl);
26640 if (DECL_TEMPLATE_SPECIALIZATION (tmpl))
26642 remove_contract_attributes (decl);
26643 copy_contract_attributes (decl, code_pattern);
26646 tsubst_contract_attributes (decl, args, tf_warning_or_error, code_pattern);
26649 /* Merge additional specifiers from the CODE_PATTERN. */
26650 if (DECL_DECLARED_INLINE_P (code_pattern)
26651 && !DECL_DECLARED_INLINE_P (decl))
26652 DECL_DECLARED_INLINE_P (decl) = 1;
26654 maybe_instantiate_noexcept (decl, tf_error);
26656 else if (VAR_P (decl))
26658 start_lambda_scope (decl);
26659 DECL_INITIAL (decl) =
26660 tsubst_init (DECL_INITIAL (code_pattern), decl, args,
26661 tf_error, DECL_TI_TEMPLATE (decl));
26662 finish_lambda_scope ();
26663 if (VAR_HAD_UNKNOWN_BOUND (decl))
26664 TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
26665 tf_error, DECL_TI_TEMPLATE (decl));
26667 else
26668 gcc_unreachable ();
26670 done:
26671 pop_access_scope (decl);
26674 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
26675 substituted to get DECL. */
26677 tree
26678 template_for_substitution (tree decl)
26680 tree tmpl = DECL_TI_TEMPLATE (decl);
26682 /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
26683 for the instantiation. This is not always the most general
26684 template. Consider, for example:
26686 template <class T>
26687 struct S { template <class U> void f();
26688 template <> void f<int>(); };
26690 and an instantiation of S<double>::f<int>. We want TD to be the
26691 specialization S<T>::f<int>, not the more general S<T>::f<U>. */
26692 while (/* An instantiation cannot have a definition, so we need a
26693 more general template. */
26694 DECL_TEMPLATE_INSTANTIATION (tmpl)
26695 /* We must also deal with friend templates. Given:
26697 template <class T> struct S {
26698 template <class U> friend void f() {};
26701 S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
26702 so far as the language is concerned, but that's still
26703 where we get the pattern for the instantiation from. On
26704 other hand, if the definition comes outside the class, say:
26706 template <class T> struct S {
26707 template <class U> friend void f();
26709 template <class U> friend void f() {}
26711 we don't need to look any further. That's what the check for
26712 DECL_INITIAL is for. */
26713 || (TREE_CODE (decl) == FUNCTION_DECL
26714 && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
26715 && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
26717 /* The present template, TD, should not be a definition. If it
26718 were a definition, we should be using it! Note that we
26719 cannot restructure the loop to just keep going until we find
26720 a template with a definition, since that might go too far if
26721 a specialization was declared, but not defined. */
26723 /* Fetch the more general template. */
26724 tmpl = DECL_TI_TEMPLATE (tmpl);
26727 return tmpl;
26730 /* Returns true if we need to instantiate this template instance even if we
26731 know we aren't going to emit it. */
26733 bool
26734 always_instantiate_p (tree decl)
26736 /* We always instantiate inline functions so that we can inline them. An
26737 explicit instantiation declaration prohibits implicit instantiation of
26738 non-inline functions. With high levels of optimization, we would
26739 normally inline non-inline functions -- but we're not allowed to do
26740 that for "extern template" functions. Therefore, we check
26741 DECL_DECLARED_INLINE_P, rather than possibly_inlined_p. */
26742 return ((TREE_CODE (decl) == FUNCTION_DECL
26743 && (DECL_DECLARED_INLINE_P (decl)
26744 || type_uses_auto (TREE_TYPE (TREE_TYPE (decl)))))
26745 /* And we need to instantiate static data members so that
26746 their initializers are available in integral constant
26747 expressions. */
26748 || (VAR_P (decl)
26749 && decl_maybe_constant_var_p (decl)));
26752 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
26753 instantiate it now, modifying TREE_TYPE (fn). Returns false on
26754 error, true otherwise. */
26756 bool
26757 maybe_instantiate_noexcept (tree fn, tsubst_flags_t complain)
26759 if (fn == error_mark_node)
26760 return false;
26762 /* Don't instantiate a noexcept-specification from template context. */
26763 if (processing_template_decl
26764 && (!flag_noexcept_type || type_dependent_expression_p (fn)))
26765 return true;
26767 tree fntype = TREE_TYPE (fn);
26768 tree spec = TYPE_RAISES_EXCEPTIONS (fntype);
26770 if ((!spec || UNEVALUATED_NOEXCEPT_SPEC_P (spec))
26771 && DECL_MAYBE_DELETED (fn))
26773 if (fn == current_function_decl)
26774 /* We're in start_preparsed_function, keep going. */
26775 return true;
26777 ++function_depth;
26778 maybe_synthesize_method (fn);
26779 --function_depth;
26780 return !DECL_DELETED_FN (fn);
26783 if (!spec || !TREE_PURPOSE (spec))
26784 return true;
26786 tree noex = TREE_PURPOSE (spec);
26787 if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
26788 && TREE_CODE (noex) != DEFERRED_PARSE)
26789 return true;
26791 tree orig_fn = NULL_TREE;
26792 /* For a member friend template we can get a TEMPLATE_DECL. Let's use
26793 its FUNCTION_DECL for the rest of this function -- push_access_scope
26794 doesn't accept TEMPLATE_DECLs. */
26795 if (DECL_FUNCTION_TEMPLATE_P (fn))
26797 orig_fn = fn;
26798 fn = DECL_TEMPLATE_RESULT (fn);
26801 if (DECL_CLONED_FUNCTION_P (fn))
26803 tree prime = DECL_CLONED_FUNCTION (fn);
26804 if (!maybe_instantiate_noexcept (prime, complain))
26805 return false;
26806 spec = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (prime));
26808 else if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
26810 static hash_set<tree>* fns = new hash_set<tree>;
26811 bool added = false;
26812 if (DEFERRED_NOEXCEPT_PATTERN (noex) == NULL_TREE)
26814 spec = get_defaulted_eh_spec (fn, complain);
26815 if (spec == error_mark_node)
26816 /* This might have failed because of an unparsed DMI, so
26817 let's try again later. */
26818 return false;
26820 else if (!(added = !fns->add (fn)))
26822 /* If hash_set::add returns true, the element was already there. */
26823 location_t loc = cp_expr_loc_or_loc (DEFERRED_NOEXCEPT_PATTERN (noex),
26824 DECL_SOURCE_LOCATION (fn));
26825 error_at (loc,
26826 "exception specification of %qD depends on itself",
26827 fn);
26828 spec = noexcept_false_spec;
26830 else if (push_tinst_level (fn))
26832 push_to_top_level ();
26833 push_access_scope (fn);
26834 push_deferring_access_checks (dk_no_deferred);
26835 input_location = DECL_SOURCE_LOCATION (fn);
26837 if (DECL_IOBJ_MEMBER_FUNCTION_P (fn)
26838 && !DECL_LOCAL_DECL_P (fn))
26840 /* If needed, set current_class_ptr for the benefit of
26841 tsubst_copy/PARM_DECL. */
26842 tree this_parm = DECL_ARGUMENTS (fn);
26843 current_class_ptr = NULL_TREE;
26844 current_class_ref = cp_build_fold_indirect_ref (this_parm);
26845 current_class_ptr = this_parm;
26848 /* If this function is represented by a TEMPLATE_DECL, then
26849 the deferred noexcept-specification might still contain
26850 dependent types, even after substitution. And we need the
26851 dependency check functions to work in build_noexcept_spec. */
26852 if (orig_fn)
26853 ++processing_template_decl;
26855 /* Do deferred instantiation of the noexcept-specifier. */
26856 noex = tsubst_expr (DEFERRED_NOEXCEPT_PATTERN (noex),
26857 DEFERRED_NOEXCEPT_ARGS (noex),
26858 tf_warning_or_error, fn);
26860 /* Build up the noexcept-specification. */
26861 spec = build_noexcept_spec (noex, tf_warning_or_error);
26863 if (orig_fn)
26864 --processing_template_decl;
26866 pop_deferring_access_checks ();
26867 pop_access_scope (fn);
26868 pop_tinst_level ();
26869 pop_from_top_level ();
26871 else
26872 spec = noexcept_false_spec;
26874 if (added)
26875 fns->remove (fn);
26878 if (spec == error_mark_node)
26880 /* This failed with a hard error, so let's go with false. */
26881 gcc_assert (seen_error ());
26882 spec = noexcept_false_spec;
26885 TREE_TYPE (fn) = build_exception_variant (fntype, spec);
26886 if (orig_fn)
26887 TREE_TYPE (orig_fn) = TREE_TYPE (fn);
26889 return true;
26892 /* We're starting to process the function INST, an instantiation of PATTERN;
26893 add their parameters to local_specializations. */
26895 void
26896 register_parameter_specializations (tree pattern, tree inst)
26898 tree tmpl_parm = DECL_ARGUMENTS (pattern);
26899 tree spec_parm = DECL_ARGUMENTS (inst);
26900 if (DECL_IOBJ_MEMBER_FUNCTION_P (inst))
26902 register_local_specialization (spec_parm, tmpl_parm);
26903 spec_parm = skip_artificial_parms_for (inst, spec_parm);
26904 tmpl_parm = skip_artificial_parms_for (pattern, tmpl_parm);
26906 for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
26908 if (!DECL_PACK_P (tmpl_parm))
26910 register_local_specialization (spec_parm, tmpl_parm);
26911 spec_parm = DECL_CHAIN (spec_parm);
26913 else
26915 /* Register the (value) argument pack as a specialization of
26916 TMPL_PARM, then move on. */
26917 tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
26918 register_local_specialization (argpack, tmpl_parm);
26921 gcc_assert (!spec_parm);
26924 /* Instantiate the body of D using PATTERN with ARGS. We have
26925 already determined PATTERN is the correct template to use.
26926 NESTED_P is true if this is a nested function, in which case
26927 PATTERN will be a FUNCTION_DECL not a TEMPLATE_DECL. */
26929 static void
26930 instantiate_body (tree pattern, tree args, tree d, bool nested_p)
26932 tree td = NULL_TREE;
26933 tree code_pattern = pattern;
26935 if (!nested_p)
26937 td = pattern;
26938 code_pattern = DECL_TEMPLATE_RESULT (td);
26940 else
26941 /* Only OMP reductions are nested. */
26942 gcc_checking_assert (DECL_OMP_DECLARE_REDUCTION_P (code_pattern));
26944 vec<tree> omp_privatization_save;
26945 if (current_function_decl)
26946 save_omp_privatization_clauses (omp_privatization_save);
26948 bool push_to_top = maybe_push_to_top_level (d);
26950 mark_template_arguments_used (pattern, args);
26952 if (VAR_P (d))
26954 /* The variable might be a lambda's extra scope, and that
26955 lambda's visibility depends on D's. */
26956 maybe_commonize_var (d);
26957 determine_visibility (d);
26960 /* Mark D as instantiated so that recursive calls to
26961 instantiate_decl do not try to instantiate it again. */
26962 DECL_TEMPLATE_INSTANTIATED (d) = 1;
26964 if (td)
26965 /* Regenerate the declaration in case the template has been modified
26966 by a subsequent redeclaration. */
26967 regenerate_decl_from_template (d, td, args);
26969 /* We already set the file and line above. Reset them now in case
26970 they changed as a result of calling regenerate_decl_from_template. */
26971 input_location = DECL_SOURCE_LOCATION (d);
26973 if (VAR_P (d))
26975 /* Clear out DECL_RTL; whatever was there before may not be right
26976 since we've reset the type of the declaration. */
26977 SET_DECL_RTL (d, NULL);
26978 DECL_IN_AGGR_P (d) = 0;
26980 /* The initializer is placed in DECL_INITIAL by
26981 regenerate_decl_from_template so we don't need to
26982 push/pop_access_scope again here. Pull it out so that
26983 cp_finish_decl can process it. */
26984 bool const_init = false;
26985 tree init = DECL_INITIAL (d);
26986 DECL_INITIAL (d) = NULL_TREE;
26987 DECL_INITIALIZED_P (d) = 0;
26989 /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
26990 initializer. That function will defer actual emission until
26991 we have a chance to determine linkage. */
26992 DECL_EXTERNAL (d) = 0;
26994 /* Enter the scope of D so that access-checking works correctly. */
26995 bool enter_context = DECL_CLASS_SCOPE_P (d);
26996 if (enter_context)
26997 push_nested_class (DECL_CONTEXT (d));
26999 const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
27000 cp_finish_decl (d, init, const_init, NULL_TREE, 0);
27002 if (enter_context)
27003 pop_nested_class ();
27005 else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
27006 synthesize_method (d);
27007 else if (TREE_CODE (d) == FUNCTION_DECL)
27009 /* Set up the list of local specializations. */
27010 local_specialization_stack lss (push_to_top ? lss_blank : lss_copy);
27011 tree block = NULL_TREE;
27013 /* Set up context. */
27014 if (nested_p)
27015 block = push_stmt_list ();
27016 else
27018 start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
27020 perform_instantiation_time_access_checks (code_pattern, args);
27023 /* Create substitution entries for the parameters. */
27024 register_parameter_specializations (code_pattern, d);
27026 /* Substitute into the body of the function. */
27027 if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
27028 tsubst_omp_udr (DECL_SAVED_TREE (code_pattern), args,
27029 tf_warning_or_error, d);
27030 else
27032 tsubst_stmt (DECL_SAVED_TREE (code_pattern), args,
27033 tf_warning_or_error, DECL_TI_TEMPLATE (d));
27035 /* Set the current input_location to the end of the function
27036 so that finish_function knows where we are. */
27037 input_location
27038 = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
27040 /* Remember if we saw an infinite loop in the template. */
27041 current_function_infinite_loop
27042 = DECL_STRUCT_FUNCTION (code_pattern)->language->infinite_loop;
27045 /* Finish the function. */
27046 if (nested_p)
27047 DECL_SAVED_TREE (d) = pop_stmt_list (block);
27048 else
27050 d = finish_function (/*inline_p=*/false);
27051 expand_or_defer_fn (d);
27054 if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
27055 cp_check_omp_declare_reduction (d);
27058 /* We're not deferring instantiation any more. */
27059 if (!nested_p)
27060 TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
27062 maybe_pop_from_top_level (push_to_top);
27064 if (current_function_decl)
27065 restore_omp_privatization_clauses (omp_privatization_save);
27068 /* Produce the definition of D, a _DECL generated from a template. If
27069 DEFER_OK is true, then we don't have to actually do the
27070 instantiation now; we just have to do it sometime. Normally it is
27071 an error if this is an explicit instantiation but D is undefined.
27072 EXPL_INST_CLASS_MEM_P is true iff D is a member of an explicitly
27073 instantiated class template. */
27075 tree
27076 instantiate_decl (tree d, bool defer_ok, bool expl_inst_class_mem_p)
27078 tree tmpl = DECL_TI_TEMPLATE (d);
27079 tree gen_args;
27080 tree args;
27081 tree td;
27082 tree code_pattern;
27083 tree spec;
27084 tree gen_tmpl;
27085 bool pattern_defined;
27086 location_t saved_loc = input_location;
27087 bool external_p;
27088 bool deleted_p;
27090 /* This function should only be used to instantiate templates for
27091 functions and static member variables. */
27092 gcc_assert (VAR_OR_FUNCTION_DECL_P (d));
27094 /* A concept is never instantiated. */
27095 gcc_assert (!DECL_DECLARED_CONCEPT_P (d));
27097 gcc_checking_assert (!DECL_FUNCTION_SCOPE_P (d));
27099 if (modules_p ())
27100 /* We may have a pending instantiation of D itself. */
27101 lazy_load_pendings (d);
27103 /* Variables are never deferred; if instantiation is required, they
27104 are instantiated right away. That allows for better code in the
27105 case that an expression refers to the value of the variable --
27106 if the variable has a constant value the referring expression can
27107 take advantage of that fact. */
27108 if (VAR_P (d))
27109 defer_ok = false;
27111 /* Don't instantiate cloned functions. Instead, instantiate the
27112 functions they cloned. */
27113 if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
27114 d = DECL_CLONED_FUNCTION (d);
27116 if (DECL_TEMPLATE_INSTANTIATED (d)
27117 || TREE_TYPE (d) == error_mark_node
27118 || (TREE_CODE (d) == FUNCTION_DECL
27119 && DECL_DEFAULTED_FN (d) && DECL_INITIAL (d))
27120 || DECL_TEMPLATE_SPECIALIZATION (d))
27121 /* D has already been instantiated or explicitly specialized, so
27122 there's nothing for us to do here.
27124 It might seem reasonable to check whether or not D is an explicit
27125 instantiation, and, if so, stop here. But when an explicit
27126 instantiation is deferred until the end of the compilation,
27127 DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
27128 the instantiation. */
27129 return d;
27131 /* Check to see whether we know that this template will be
27132 instantiated in some other file, as with "extern template"
27133 extension. */
27134 external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
27136 /* In general, we do not instantiate such templates. */
27137 if (external_p && !always_instantiate_p (d))
27138 return d;
27140 gen_tmpl = most_general_template (tmpl);
27141 gen_args = DECL_TI_ARGS (d);
27143 /* We should already have the extra args. */
27144 gcc_checking_assert (tmpl == gen_tmpl
27145 || (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
27146 == TMPL_ARGS_DEPTH (gen_args)));
27147 /* And what's in the hash table should match D. */
27148 gcc_checking_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0))
27149 == d
27150 || spec == NULL_TREE);
27152 /* This needs to happen before any tsubsting. */
27153 if (! push_tinst_level (d))
27154 return d;
27156 auto_timevar tv (TV_TEMPLATE_INST);
27158 /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
27159 for the instantiation. */
27160 td = template_for_substitution (d);
27161 args = gen_args;
27163 if (variable_template_specialization_p (d))
27165 /* Look up an explicit specialization, if any. */
27166 tree partial_ti = most_specialized_partial_spec (d, tf_warning_or_error);
27167 if (partial_ti && partial_ti != error_mark_node)
27169 td = TI_TEMPLATE (partial_ti);
27170 args = TI_ARGS (partial_ti);
27174 code_pattern = DECL_TEMPLATE_RESULT (td);
27176 /* We should never be trying to instantiate a member of a class
27177 template or partial specialization. */
27178 gcc_assert (d != code_pattern);
27180 if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
27181 || DECL_TEMPLATE_SPECIALIZATION (td))
27182 /* In the case of a friend template whose definition is provided
27183 outside the class, we may have too many arguments. Drop the
27184 ones we don't need. The same is true for specializations. */
27185 args = get_innermost_template_args
27186 (args, TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (td)));
27188 if (TREE_CODE (d) == FUNCTION_DECL)
27190 deleted_p = DECL_DELETED_FN (code_pattern);
27191 pattern_defined = ((DECL_SAVED_TREE (code_pattern) != NULL_TREE
27192 && DECL_INITIAL (code_pattern) != error_mark_node)
27193 || DECL_DEFAULTED_FN (code_pattern)
27194 || deleted_p);
27196 else
27198 deleted_p = false;
27199 if (DECL_CLASS_SCOPE_P (code_pattern))
27200 pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
27201 else
27202 pattern_defined = ! DECL_EXTERNAL (code_pattern);
27205 /* We may be in the middle of deferred access check. Disable it now. */
27206 push_deferring_access_checks (dk_no_deferred);
27208 /* Unless an explicit instantiation directive has already determined
27209 the linkage of D, remember that a definition is available for
27210 this entity. */
27211 if (pattern_defined
27212 && !DECL_INTERFACE_KNOWN (d)
27213 && !DECL_NOT_REALLY_EXTERN (d))
27214 mark_definable (d);
27216 DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
27217 DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
27218 input_location = DECL_SOURCE_LOCATION (d);
27220 /* If D is a member of an explicitly instantiated class template,
27221 and no definition is available, treat it like an implicit
27222 instantiation. */
27223 if (!pattern_defined && expl_inst_class_mem_p
27224 && DECL_EXPLICIT_INSTANTIATION (d))
27226 /* Leave linkage flags alone on instantiations with anonymous
27227 visibility. */
27228 if (TREE_PUBLIC (d))
27230 DECL_NOT_REALLY_EXTERN (d) = 0;
27231 DECL_INTERFACE_KNOWN (d) = 0;
27233 SET_DECL_IMPLICIT_INSTANTIATION (d);
27236 /* Defer all other templates, unless we have been explicitly
27237 forbidden from doing so. */
27238 if (/* If there is no definition, we cannot instantiate the
27239 template. */
27240 ! pattern_defined
27241 /* If it's OK to postpone instantiation, do so. */
27242 || defer_ok
27243 /* If this is a static data member that will be defined
27244 elsewhere, we don't want to instantiate the entire data
27245 member, but we do want to instantiate the initializer so that
27246 we can substitute that elsewhere. */
27247 || (external_p && VAR_P (d))
27248 /* Handle here a deleted function too, avoid generating
27249 its body (c++/61080). */
27250 || deleted_p)
27252 /* The definition of the static data member is now required so
27253 we must substitute the initializer. */
27254 if (VAR_P (d)
27255 && !DECL_INITIAL (d)
27256 && DECL_INITIAL (code_pattern))
27258 tree ns;
27259 tree init;
27260 bool const_init = false;
27261 bool enter_context = DECL_CLASS_SCOPE_P (d);
27263 ns = decl_namespace_context (d);
27264 push_nested_namespace (ns);
27265 if (enter_context)
27266 push_nested_class (DECL_CONTEXT (d));
27267 init = tsubst_expr (DECL_INITIAL (code_pattern),
27268 args,
27269 tf_warning_or_error, NULL_TREE);
27270 /* If instantiating the initializer involved instantiating this
27271 again, don't call cp_finish_decl twice. */
27272 if (!DECL_INITIAL (d))
27274 /* Make sure the initializer is still constant, in case of
27275 circular dependency (template/instantiate6.C). */
27276 const_init
27277 = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
27278 cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
27279 /*asmspec_tree=*/NULL_TREE, 0);
27281 if (enter_context)
27282 pop_nested_class ();
27283 pop_nested_namespace (ns);
27286 /* We restore the source position here because it's used by
27287 add_pending_template. */
27288 input_location = saved_loc;
27290 if (at_eof && !pattern_defined
27291 && DECL_EXPLICIT_INSTANTIATION (d)
27292 && DECL_NOT_REALLY_EXTERN (d))
27293 /* [temp.explicit]
27295 The definition of a non-exported function template, a
27296 non-exported member function template, or a non-exported
27297 member function or static data member of a class template
27298 shall be present in every translation unit in which it is
27299 explicitly instantiated. */
27300 permerror (input_location, "explicit instantiation of %qD "
27301 "but no definition available", d);
27303 /* If we're in unevaluated context, we just wanted to get the
27304 constant value; this isn't an odr use, so don't queue
27305 a full instantiation. */
27306 if (!cp_unevaluated_operand
27307 /* ??? Historically, we have instantiated inline functions, even
27308 when marked as "extern template". */
27309 && !(external_p && VAR_P (d)))
27310 add_pending_template (d);
27312 else
27314 set_instantiating_module (d);
27315 if (variable_template_p (gen_tmpl))
27316 note_vague_linkage_variable (d);
27317 instantiate_body (td, args, d, false);
27320 pop_deferring_access_checks ();
27321 pop_tinst_level ();
27322 input_location = saved_loc;
27324 return d;
27327 /* Run through the list of templates that we wish we could
27328 instantiate, and instantiate any we can. RETRIES is the
27329 number of times we retry pending template instantiation. */
27331 void
27332 instantiate_pending_templates (int retries)
27334 int reconsider;
27335 location_t saved_loc = input_location;
27337 /* Instantiating templates may trigger vtable generation. This in turn
27338 may require further template instantiations. We place a limit here
27339 to avoid infinite loop. */
27340 if (pending_templates && retries >= max_tinst_depth)
27342 tree decl = pending_templates->tinst->maybe_get_node ();
27344 fatal_error (input_location,
27345 "template instantiation depth exceeds maximum of %d"
27346 " instantiating %q+D, possibly from virtual table generation"
27347 " (use %<-ftemplate-depth=%> to increase the maximum)",
27348 max_tinst_depth, decl);
27349 if (TREE_CODE (decl) == FUNCTION_DECL)
27350 /* Pretend that we defined it. */
27351 DECL_INITIAL (decl) = error_mark_node;
27352 return;
27357 struct pending_template **t = &pending_templates;
27358 struct pending_template *last = NULL;
27359 reconsider = 0;
27360 while (*t)
27362 tree instantiation = reopen_tinst_level ((*t)->tinst);
27363 bool complete = false;
27365 if (TYPE_P (instantiation))
27367 if (!COMPLETE_TYPE_P (instantiation))
27369 instantiate_class_template (instantiation);
27370 if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
27371 for (tree fld = TYPE_FIELDS (instantiation);
27372 fld; fld = TREE_CHAIN (fld))
27373 if ((VAR_P (fld)
27374 || (TREE_CODE (fld) == FUNCTION_DECL
27375 && !DECL_ARTIFICIAL (fld)))
27376 && DECL_TEMPLATE_INSTANTIATION (fld))
27377 instantiate_decl (fld,
27378 /*defer_ok=*/false,
27379 /*expl_inst_class_mem_p=*/false);
27381 if (COMPLETE_TYPE_P (instantiation))
27382 reconsider = 1;
27385 complete = COMPLETE_TYPE_P (instantiation);
27387 else
27389 if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
27390 && !DECL_TEMPLATE_INSTANTIATED (instantiation))
27392 instantiation
27393 = instantiate_decl (instantiation,
27394 /*defer_ok=*/false,
27395 /*expl_inst_class_mem_p=*/false);
27396 if (DECL_TEMPLATE_INSTANTIATED (instantiation))
27397 reconsider = 1;
27400 complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
27401 || DECL_TEMPLATE_INSTANTIATED (instantiation));
27404 if (complete)
27406 /* If INSTANTIATION has been instantiated, then we don't
27407 need to consider it again in the future. */
27408 struct pending_template *drop = *t;
27409 *t = (*t)->next;
27410 set_refcount_ptr (drop->tinst);
27411 pending_template_freelist ().free (drop);
27413 else
27415 last = *t;
27416 t = &(*t)->next;
27418 tinst_depth = 0;
27419 set_refcount_ptr (current_tinst_level);
27421 last_pending_template = last;
27423 while (reconsider);
27425 input_location = saved_loc;
27428 /* Substitute ARGVEC into T, which is a list of initializers for
27429 either base class or a non-static data member. The TREE_PURPOSEs
27430 are DECLs, and the TREE_VALUEs are the initializer values. Used by
27431 instantiate_decl. */
27433 static tree
27434 tsubst_initializer_list (tree t, tree argvec)
27436 tree inits = NULL_TREE;
27437 tree target_ctor = error_mark_node;
27439 for (; t; t = TREE_CHAIN (t))
27441 tree decl;
27442 tree init;
27443 tree expanded_bases = NULL_TREE;
27444 tree expanded_arguments = NULL_TREE;
27445 int i, len = 1;
27447 if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
27449 tree expr;
27450 tree arg;
27452 /* Expand the base class expansion type into separate base
27453 classes. */
27454 expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
27455 tf_warning_or_error,
27456 NULL_TREE);
27457 if (expanded_bases == error_mark_node)
27458 continue;
27460 /* We'll be building separate TREE_LISTs of arguments for
27461 each base. */
27462 len = TREE_VEC_LENGTH (expanded_bases);
27463 expanded_arguments = make_tree_vec (len);
27464 for (i = 0; i < len; i++)
27465 TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
27467 /* Build a dummy EXPR_PACK_EXPANSION that will be used to
27468 expand each argument in the TREE_VALUE of t. */
27469 expr = make_node (EXPR_PACK_EXPANSION);
27470 PACK_EXPANSION_LOCAL_P (expr) = true;
27471 PACK_EXPANSION_PARAMETER_PACKS (expr) =
27472 PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
27474 if (TREE_VALUE (t) == void_type_node)
27475 /* VOID_TYPE_NODE is used to indicate
27476 value-initialization. */
27478 for (i = 0; i < len; i++)
27479 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
27481 else
27483 /* Substitute parameter packs into each argument in the
27484 TREE_LIST. */
27485 in_base_initializer = 1;
27486 for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
27488 tree expanded_exprs;
27490 /* Expand the argument. */
27491 tree value;
27492 if (TREE_CODE (TREE_VALUE (arg)) == EXPR_PACK_EXPANSION)
27493 value = TREE_VALUE (arg);
27494 else
27496 value = expr;
27497 PACK_EXPANSION_PATTERN (value) = TREE_VALUE (arg);
27499 expanded_exprs
27500 = tsubst_pack_expansion (value, argvec,
27501 tf_warning_or_error,
27502 NULL_TREE);
27503 if (expanded_exprs == error_mark_node)
27504 continue;
27506 /* Prepend each of the expanded expressions to the
27507 corresponding TREE_LIST in EXPANDED_ARGUMENTS. */
27508 for (i = 0; i < len; i++)
27509 if (TREE_CODE (TREE_VALUE (arg)) == EXPR_PACK_EXPANSION)
27510 for (int j = 0; j < TREE_VEC_LENGTH (expanded_exprs); j++)
27511 TREE_VEC_ELT (expanded_arguments, i)
27512 = tree_cons (NULL_TREE,
27513 TREE_VEC_ELT (expanded_exprs, j),
27514 TREE_VEC_ELT (expanded_arguments, i));
27515 else
27516 TREE_VEC_ELT (expanded_arguments, i)
27517 = tree_cons (NULL_TREE,
27518 TREE_VEC_ELT (expanded_exprs, i),
27519 TREE_VEC_ELT (expanded_arguments, i));
27521 in_base_initializer = 0;
27523 /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
27524 since we built them backwards. */
27525 for (i = 0; i < len; i++)
27527 TREE_VEC_ELT (expanded_arguments, i) =
27528 nreverse (TREE_VEC_ELT (expanded_arguments, i));
27533 for (i = 0; i < len; ++i)
27535 if (expanded_bases)
27537 decl = TREE_VEC_ELT (expanded_bases, i);
27538 decl = expand_member_init (decl);
27539 init = TREE_VEC_ELT (expanded_arguments, i);
27541 else
27543 tree tmp;
27544 if (TYPE_P (TREE_PURPOSE (t)))
27545 decl = tsubst (TREE_PURPOSE (t), argvec,
27546 tf_warning_or_error, NULL_TREE);
27547 else
27548 decl = tsubst_expr (TREE_PURPOSE (t), argvec,
27549 tf_warning_or_error, NULL_TREE);
27551 decl = expand_member_init (decl);
27552 if (decl && !DECL_P (decl))
27553 in_base_initializer = 1;
27555 init = TREE_VALUE (t);
27556 tmp = init;
27557 if (init != void_type_node)
27558 init = tsubst_expr (init, argvec,
27559 tf_warning_or_error, NULL_TREE);
27560 if (init == NULL_TREE && tmp != NULL_TREE)
27561 /* If we had an initializer but it instantiated to nothing,
27562 value-initialize the object. This will only occur when
27563 the initializer was a pack expansion where the parameter
27564 packs used in that expansion were of length zero. */
27565 init = void_type_node;
27566 in_base_initializer = 0;
27569 if (target_ctor != error_mark_node
27570 && init != error_mark_node)
27572 error ("mem-initializer for %qD follows constructor delegation",
27573 decl);
27574 return inits;
27576 /* Look for a target constructor. */
27577 if (init != error_mark_node
27578 && decl && CLASS_TYPE_P (decl)
27579 && same_type_p (decl, current_class_type))
27581 maybe_warn_cpp0x (CPP0X_DELEGATING_CTORS);
27582 if (inits)
27584 error ("constructor delegation follows mem-initializer for %qD",
27585 TREE_PURPOSE (inits));
27586 continue;
27588 target_ctor = init;
27591 if (decl)
27593 init = build_tree_list (decl, init);
27594 /* Carry over the dummy TREE_TYPE node containing the source
27595 location. */
27596 TREE_TYPE (init) = TREE_TYPE (t);
27597 TREE_CHAIN (init) = inits;
27598 inits = init;
27602 return inits;
27605 /* Instantiate an enumerated type. TAG is the template type, NEWTAG
27606 is the instantiation (which should have been created with
27607 start_enum) and ARGS are the template arguments to use. */
27609 static void
27610 tsubst_enum (tree tag, tree newtag, tree args)
27612 tree e;
27614 if (SCOPED_ENUM_P (newtag))
27615 begin_scope (sk_scoped_enum, newtag);
27617 for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
27619 tree value;
27620 tree decl = TREE_VALUE (e);
27622 /* Note that in a template enum, the TREE_VALUE is the
27623 CONST_DECL, not the corresponding INTEGER_CST. */
27624 value = tsubst_expr (DECL_INITIAL (decl),
27625 args, tf_warning_or_error, NULL_TREE);
27627 /* Give this enumeration constant the correct access. */
27628 set_current_access_from_decl (decl);
27630 /* Actually build the enumerator itself. Here we're assuming that
27631 enumerators can't have dependent attributes. */
27632 tree newdecl = build_enumerator (DECL_NAME (decl), value, newtag,
27633 DECL_ATTRIBUTES (decl),
27634 DECL_SOURCE_LOCATION (decl));
27635 /* Attribute deprecated without an argument isn't sticky: it'll
27636 melt into a tree flag, so we need to propagate the flag here,
27637 since we just created a new enumerator. */
27638 TREE_DEPRECATED (newdecl) = TREE_DEPRECATED (decl);
27639 TREE_UNAVAILABLE (newdecl) = TREE_UNAVAILABLE (decl);
27642 if (SCOPED_ENUM_P (newtag))
27643 finish_scope ();
27645 finish_enum_value_list (newtag);
27646 finish_enum (newtag);
27648 DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
27649 = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
27650 TREE_DEPRECATED (newtag) = TREE_DEPRECATED (tag);
27651 TREE_UNAVAILABLE (newtag) = TREE_UNAVAILABLE (tag);
27654 /* DECL is a FUNCTION_DECL that is a template specialization. Return
27655 its type -- but without substituting the innermost set of template
27656 arguments. So, innermost set of template parameters will appear in
27657 the type. */
27659 tree
27660 get_mostly_instantiated_function_type (tree decl)
27662 /* For a function, DECL_TI_TEMPLATE is partially instantiated. */
27663 return TREE_TYPE (DECL_TI_TEMPLATE (decl));
27666 /* Return truthvalue if we're processing a template different from
27667 the last one involved in diagnostics. */
27668 bool
27669 problematic_instantiation_changed (void)
27671 return current_tinst_level != last_error_tinst_level;
27674 /* Remember current template involved in diagnostics. */
27675 void
27676 record_last_problematic_instantiation (void)
27678 set_refcount_ptr (last_error_tinst_level, current_tinst_level);
27681 struct tinst_level *
27682 current_instantiation (void)
27684 return current_tinst_level;
27687 /* Return TRUE if current_function_decl is being instantiated, false
27688 otherwise. */
27690 bool
27691 instantiating_current_function_p (void)
27693 return (current_instantiation ()
27694 && (current_instantiation ()->maybe_get_node ()
27695 == current_function_decl));
27698 /* [temp.param] Check that template non-type parm TYPE is of an allowable
27699 type. Return false for ok, true for disallowed. Issue error and
27700 inform messages under control of COMPLAIN. */
27702 static bool
27703 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
27705 if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
27706 return false;
27707 else if (TYPE_PTR_P (type))
27708 return false;
27709 else if (TYPE_REF_P (type)
27710 && !TYPE_REF_IS_RVALUE (type))
27711 return false;
27712 else if (TYPE_PTRMEM_P (type))
27713 return false;
27714 else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
27716 if (CLASS_PLACEHOLDER_TEMPLATE (type) && cxx_dialect < cxx20)
27718 if (complain & tf_error)
27719 error ("non-type template parameters of deduced class type only "
27720 "available with %<-std=c++20%> or %<-std=gnu++20%>");
27721 return true;
27723 return false;
27725 else if (TREE_CODE (type) == NULLPTR_TYPE)
27726 return false;
27727 else if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM
27728 && cxx_dialect < cxx11)
27729 /* Fall through; before C++11 alias templates, a bound ttp
27730 always instantiates into a class type. */;
27731 else if (WILDCARD_TYPE_P (type))
27732 /* Any other wildcard type not already handled above is allowed. */
27733 return false;
27734 else if (TREE_CODE (type) == COMPLEX_TYPE)
27735 /* Fall through. */;
27736 else if (VOID_TYPE_P (type))
27737 /* Fall through. */;
27738 else if (cxx_dialect >= cxx20)
27740 if (dependent_type_p (type))
27741 return false;
27742 if (!complete_type_or_maybe_complain (type, NULL_TREE, complain))
27743 return true;
27744 if (structural_type_p (type))
27745 return false;
27746 if (complain & tf_error)
27748 auto_diagnostic_group d;
27749 error ("%qT is not a valid type for a template non-type "
27750 "parameter because it is not structural", type);
27751 structural_type_p (type, true);
27753 return true;
27755 else if (CLASS_TYPE_P (type))
27757 if (complain & tf_error)
27758 error ("non-type template parameters of class type only available "
27759 "with %<-std=c++20%> or %<-std=gnu++20%>");
27760 return true;
27763 if (complain & tf_error)
27765 if (type == error_mark_node)
27766 inform (input_location, "invalid template non-type parameter");
27767 else
27768 error ("%q#T is not a valid type for a template non-type parameter",
27769 type);
27771 return true;
27774 /* Returns true iff the noexcept-specifier for TYPE is value-dependent. */
27776 static bool
27777 value_dependent_noexcept_spec_p (tree type)
27779 if (tree spec = TYPE_RAISES_EXCEPTIONS (type))
27780 if (tree noex = TREE_PURPOSE (spec))
27781 /* Treat DEFERRED_NOEXCEPT as non-dependent, since it doesn't
27782 affect overload resolution and treating it as dependent breaks
27783 things. Same for an unparsed noexcept expression. */
27784 if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
27785 && TREE_CODE (noex) != DEFERRED_PARSE
27786 && value_dependent_expression_p (noex))
27787 return true;
27789 return false;
27792 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
27793 Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
27795 static bool
27796 dependent_type_p_r (tree type)
27798 tree scope;
27800 /* [temp.dep.type]
27802 A type is dependent if it is:
27804 -- a template parameter. Template template parameters are types
27805 for us (since TYPE_P holds true for them) so we handle
27806 them here. */
27807 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
27808 || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
27809 return true;
27810 /* -- a qualified-id with a nested-name-specifier which contains a
27811 class-name that names a dependent type or whose unqualified-id
27812 names a dependent type. */
27813 if (TREE_CODE (type) == TYPENAME_TYPE)
27814 return true;
27816 /* An alias template specialization can be dependent even if the
27817 resulting type is not. */
27818 if (dependent_alias_template_spec_p (type, nt_transparent))
27819 return true;
27821 /* -- a cv-qualified type where the cv-unqualified type is
27822 dependent.
27823 No code is necessary for this bullet; the code below handles
27824 cv-qualified types, and we don't want to strip aliases with
27825 TYPE_MAIN_VARIANT because of DR 1558. */
27826 /* -- a compound type constructed from any dependent type. */
27827 if (TYPE_PTRMEM_P (type))
27828 return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
27829 || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
27830 (type)));
27831 else if (INDIRECT_TYPE_P (type))
27832 return dependent_type_p (TREE_TYPE (type));
27833 else if (FUNC_OR_METHOD_TYPE_P (type))
27835 tree arg_type;
27837 if (dependent_type_p (TREE_TYPE (type)))
27838 return true;
27839 for (arg_type = TYPE_ARG_TYPES (type);
27840 arg_type;
27841 arg_type = TREE_CHAIN (arg_type))
27842 if (dependent_type_p (TREE_VALUE (arg_type)))
27843 return true;
27844 if (cxx_dialect >= cxx17
27845 && value_dependent_noexcept_spec_p (type))
27846 /* A value-dependent noexcept-specifier makes the type dependent. */
27847 return true;
27848 return false;
27850 /* -- an array type constructed from any dependent type or whose
27851 size is specified by a constant expression that is
27852 value-dependent.
27854 We checked for type- and value-dependence of the bounds in
27855 compute_array_index_type, so TYPE_DEPENDENT_P is already set. */
27856 if (TREE_CODE (type) == ARRAY_TYPE)
27858 if (TYPE_DOMAIN (type)
27859 && dependent_type_p (TYPE_DOMAIN (type)))
27860 return true;
27861 return dependent_type_p (TREE_TYPE (type));
27864 /* -- a template-id in which either the template name is a template
27865 parameter ... */
27866 if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
27867 return true;
27868 /* ... or any of the template arguments is a dependent type or
27869 an expression that is type-dependent or value-dependent. */
27870 else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
27871 && (any_dependent_template_arguments_p
27872 (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
27873 return true;
27875 /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and TRAIT_TYPEs are
27876 dependent; if the argument of the `typeof' expression is not
27877 type-dependent, then it should already been have resolved. */
27878 if (TREE_CODE (type) == TYPEOF_TYPE
27879 || TREE_CODE (type) == DECLTYPE_TYPE
27880 || TREE_CODE (type) == TRAIT_TYPE)
27881 return true;
27883 /* A template argument pack is dependent if any of its packed
27884 arguments are. */
27885 if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
27887 tree args = ARGUMENT_PACK_ARGS (type);
27888 for (tree arg : tree_vec_range (args))
27889 if (dependent_template_arg_p (arg))
27890 return true;
27893 /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
27894 be template parameters. */
27895 if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
27896 return true;
27898 if (TREE_CODE (type) == DEPENDENT_OPERATOR_TYPE)
27899 return true;
27901 if (any_dependent_type_attributes_p (TYPE_ATTRIBUTES (type)))
27902 return true;
27904 /* The standard does not specifically mention types that are local
27905 to template functions or local classes, but they should be
27906 considered dependent too. For example:
27908 template <int I> void f() {
27909 enum E { a = I };
27910 S<sizeof (E)> s;
27913 The size of `E' cannot be known until the value of `I' has been
27914 determined. Therefore, `E' must be considered dependent. */
27915 scope = TYPE_CONTEXT (type);
27916 if (scope && TYPE_P (scope))
27917 return dependent_type_p (scope);
27918 /* Don't use type_dependent_expression_p here, as it can lead
27919 to infinite recursion trying to determine whether a lambda
27920 nested in a lambda is dependent (c++/47687). */
27921 else if (scope && TREE_CODE (scope) == FUNCTION_DECL
27922 && DECL_LANG_SPECIFIC (scope)
27923 && DECL_TEMPLATE_INFO (scope)
27924 && (any_dependent_template_arguments_p
27925 (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
27926 return true;
27928 /* Other types are non-dependent. */
27929 return false;
27932 /* Returns TRUE if TYPE is dependent, in the sense of
27933 [temp.dep.type]. Note that a NULL type is considered dependent. */
27935 bool
27936 dependent_type_p (tree type)
27938 /* If there are no template parameters in scope, then there can't be
27939 any dependent types. */
27940 if (!processing_template_decl)
27942 /* If we are not processing a template, then nobody should be
27943 providing us with a dependent type. */
27944 gcc_assert (type);
27945 gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
27946 return false;
27949 /* If the type is NULL, we have not computed a type for the entity
27950 in question; in that case, the type is dependent. */
27951 if (!type)
27952 return true;
27954 /* Erroneous types can be considered non-dependent. */
27955 if (type == error_mark_node)
27956 return false;
27958 /* If we have not already computed the appropriate value for TYPE,
27959 do so now. */
27960 if (!TYPE_DEPENDENT_P_VALID (type))
27962 TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
27963 TYPE_DEPENDENT_P_VALID (type) = 1;
27966 return TYPE_DEPENDENT_P (type);
27969 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
27970 lookup. In other words, a dependent type that is not the current
27971 instantiation. */
27973 bool
27974 dependent_scope_p (tree scope)
27976 return (scope && TYPE_P (scope) && dependent_type_p (scope)
27977 && !currently_open_class (scope));
27980 /* True if we might find more declarations in SCOPE during instantiation than
27981 we can when parsing the template. */
27983 bool
27984 dependentish_scope_p (tree scope)
27986 return dependent_scope_p (scope) || any_dependent_bases_p (scope);
27989 /* T is a SCOPE_REF. Return whether it represents a non-static member of
27990 an unknown base of 'this' (and is therefore instantiation-dependent). */
27992 static bool
27993 unknown_base_ref_p (tree t)
27995 if (!current_class_ptr)
27996 return false;
27998 tree mem = TREE_OPERAND (t, 1);
27999 if (shared_member_p (mem))
28000 return false;
28002 tree cur = current_nonlambda_class_type ();
28003 if (!any_dependent_bases_p (cur))
28004 return false;
28006 tree ctx = TREE_OPERAND (t, 0);
28007 if (DERIVED_FROM_P (ctx, cur))
28008 return false;
28010 return true;
28013 /* T is a SCOPE_REF; return whether we need to consider it
28014 instantiation-dependent so that we can check access at instantiation
28015 time even though we know which member it resolves to. */
28017 static bool
28018 instantiation_dependent_scope_ref_p (tree t)
28020 if (DECL_P (TREE_OPERAND (t, 1))
28021 && CLASS_TYPE_P (TREE_OPERAND (t, 0))
28022 && !dependent_scope_p (TREE_OPERAND (t, 0))
28023 && !unknown_base_ref_p (t)
28024 && accessible_in_template_p (TREE_OPERAND (t, 0),
28025 TREE_OPERAND (t, 1)))
28026 return false;
28027 else
28028 return true;
28031 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
28032 [temp.dep.constexpr]. EXPRESSION is already known to be a constant
28033 expression. */
28035 /* Note that this predicate is not appropriate for general expressions;
28036 only constant expressions (that satisfy potential_constant_expression)
28037 can be tested for value dependence. */
28039 bool
28040 value_dependent_expression_p (tree expression)
28042 if (!processing_template_decl || expression == NULL_TREE)
28043 return false;
28045 /* A type-dependent expression is also value-dependent. */
28046 if (type_dependent_expression_p (expression))
28047 return true;
28049 switch (TREE_CODE (expression))
28051 case BASELINK:
28052 /* A dependent member function of the current instantiation. */
28053 return dependent_type_p (BINFO_TYPE (BASELINK_BINFO (expression)));
28055 case FUNCTION_DECL:
28056 /* A dependent member function of the current instantiation. */
28057 if (DECL_CLASS_SCOPE_P (expression)
28058 && dependent_type_p (DECL_CONTEXT (expression)))
28059 return true;
28060 break;
28062 case IDENTIFIER_NODE:
28063 /* A name that has not been looked up -- must be dependent. */
28064 return true;
28066 case TEMPLATE_PARM_INDEX:
28067 /* A non-type template parm. */
28068 return true;
28070 case CONST_DECL:
28071 /* A non-type template parm. */
28072 if (DECL_TEMPLATE_PARM_P (expression))
28073 return true;
28074 return value_dependent_expression_p (DECL_INITIAL (expression));
28076 case VAR_DECL:
28077 /* A constant with literal type and is initialized
28078 with an expression that is value-dependent. */
28079 if (DECL_DEPENDENT_INIT_P (expression))
28080 return true;
28081 if (DECL_HAS_VALUE_EXPR_P (expression))
28083 tree value_expr = DECL_VALUE_EXPR (expression);
28084 if (value_dependent_expression_p (value_expr)
28085 /* __PRETTY_FUNCTION__ inside a template function is dependent
28086 on the name of the function. */
28087 || (DECL_PRETTY_FUNCTION_P (expression)
28088 /* It might be used in a template, but not a template
28089 function, in which case its DECL_VALUE_EXPR will be
28090 "top level". */
28091 && value_expr == error_mark_node))
28092 return true;
28094 else if (TYPE_REF_P (TREE_TYPE (expression)))
28095 /* FIXME cp_finish_decl doesn't fold reference initializers. */
28096 return true;
28097 /* We have a constexpr variable and we're processing a template. When
28098 there's lifetime extension involved (for which finish_compound_literal
28099 used to create a temporary), we'll not be able to evaluate the
28100 variable until instantiating, so pretend it's value-dependent. */
28101 else if (DECL_DECLARED_CONSTEXPR_P (expression)
28102 && !TREE_CONSTANT (expression))
28103 return true;
28104 return false;
28106 case DYNAMIC_CAST_EXPR:
28107 case STATIC_CAST_EXPR:
28108 case CONST_CAST_EXPR:
28109 case REINTERPRET_CAST_EXPR:
28110 case CAST_EXPR:
28111 case IMPLICIT_CONV_EXPR:
28112 /* These expressions are value-dependent if the type to which
28113 the cast occurs is dependent or the expression being casted
28114 is value-dependent. */
28116 tree type = TREE_TYPE (expression);
28118 if (dependent_type_p (type))
28119 return true;
28121 /* A functional cast has a list of operands. */
28122 expression = TREE_OPERAND (expression, 0);
28123 if (!expression)
28125 /* If there are no operands, it must be an expression such
28126 as "int()". This should not happen for aggregate types
28127 because it would form non-constant expressions. */
28128 gcc_assert (cxx_dialect >= cxx11
28129 || INTEGRAL_OR_ENUMERATION_TYPE_P (type));
28131 return false;
28134 if (TREE_CODE (expression) == TREE_LIST)
28135 return any_value_dependent_elements_p (expression);
28137 if (TREE_CODE (type) == REFERENCE_TYPE
28138 && has_value_dependent_address (expression))
28139 return true;
28141 return value_dependent_expression_p (expression);
28144 case SIZEOF_EXPR:
28145 if (SIZEOF_EXPR_TYPE_P (expression))
28146 return dependent_type_p (TREE_TYPE (TREE_OPERAND (expression, 0)));
28147 /* FALLTHRU */
28148 case ALIGNOF_EXPR:
28149 case TYPEID_EXPR:
28150 /* A `sizeof' expression is value-dependent if the operand is
28151 type-dependent or is a pack expansion. */
28152 expression = TREE_OPERAND (expression, 0);
28153 if (PACK_EXPANSION_P (expression))
28154 return true;
28155 else if (TYPE_P (expression))
28156 return dependent_type_p (expression);
28157 return instantiation_dependent_uneval_expression_p (expression);
28159 case AT_ENCODE_EXPR:
28160 /* An 'encode' expression is value-dependent if the operand is
28161 type-dependent. */
28162 expression = TREE_OPERAND (expression, 0);
28163 return dependent_type_p (expression);
28165 case NOEXCEPT_EXPR:
28166 expression = TREE_OPERAND (expression, 0);
28167 return instantiation_dependent_uneval_expression_p (expression);
28169 case SCOPE_REF:
28170 /* All instantiation-dependent expressions should also be considered
28171 value-dependent. */
28172 return instantiation_dependent_scope_ref_p (expression);
28174 case COMPONENT_REF:
28175 return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
28176 || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
28178 case NONTYPE_ARGUMENT_PACK:
28179 /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
28180 is value-dependent. */
28181 for (tree arg : tree_vec_range (ARGUMENT_PACK_ARGS (expression)))
28182 if (value_dependent_expression_p (arg))
28183 return true;
28184 return false;
28186 case TRAIT_EXPR:
28188 if (dependent_type_p (TRAIT_EXPR_TYPE1 (expression)))
28189 return true;
28191 tree type2 = TRAIT_EXPR_TYPE2 (expression);
28192 if (!type2)
28193 return false;
28195 if (TREE_CODE (type2) != TREE_VEC)
28196 return dependent_type_p (type2);
28198 for (tree arg : tree_vec_range (type2))
28199 if (dependent_type_p (arg))
28200 return true;
28202 return false;
28205 case MODOP_EXPR:
28206 return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
28207 || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
28209 case ARRAY_REF:
28210 return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
28211 || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
28213 case ADDR_EXPR:
28215 tree op = TREE_OPERAND (expression, 0);
28216 return (value_dependent_expression_p (op)
28217 || has_value_dependent_address (op));
28220 case REQUIRES_EXPR:
28221 /* Treat all requires-expressions as value-dependent so
28222 we don't try to fold them. */
28223 return true;
28225 case TYPE_REQ:
28226 return dependent_type_p (TREE_OPERAND (expression, 0));
28228 case CALL_EXPR:
28230 if (value_dependent_expression_p (CALL_EXPR_FN (expression)))
28231 return true;
28232 tree fn = get_callee_fndecl (expression);
28233 int i, nargs;
28234 nargs = call_expr_nargs (expression);
28235 for (i = 0; i < nargs; ++i)
28237 tree op = CALL_EXPR_ARG (expression, i);
28238 /* In a call to a constexpr member function, look through the
28239 implicit ADDR_EXPR on the object argument so that it doesn't
28240 cause the call to be considered value-dependent. We also
28241 look through it in potential_constant_expression. */
28242 if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
28243 && DECL_IOBJ_MEMBER_FUNCTION_P (fn)
28244 && TREE_CODE (op) == ADDR_EXPR)
28245 op = TREE_OPERAND (op, 0);
28246 if (value_dependent_expression_p (op))
28247 return true;
28249 return false;
28252 case TEMPLATE_ID_EXPR:
28253 return concept_definition_p (TREE_OPERAND (expression, 0))
28254 && any_dependent_template_arguments_p (TREE_OPERAND (expression, 1));
28256 case CONSTRUCTOR:
28258 unsigned ix;
28259 tree val;
28260 if (dependent_type_p (TREE_TYPE (expression)))
28261 return true;
28262 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
28263 if (value_dependent_expression_p (val))
28264 return true;
28265 return false;
28268 case STMT_EXPR:
28269 /* Treat a GNU statement expression as dependent to avoid crashing
28270 under instantiate_non_dependent_expr; it can't be constant. */
28271 return true;
28273 case NEW_EXPR:
28274 case VEC_NEW_EXPR:
28275 /* The second operand is a type, which type_dependent_expression_p
28276 (and therefore value_dependent_expression_p) doesn't want to see. */
28277 return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
28278 || value_dependent_expression_p (TREE_OPERAND (expression, 2))
28279 || value_dependent_expression_p (TREE_OPERAND (expression, 3)));
28281 default:
28282 /* A constant expression is value-dependent if any subexpression is
28283 value-dependent. */
28284 switch (TREE_CODE_CLASS (TREE_CODE (expression)))
28286 case tcc_reference:
28287 case tcc_unary:
28288 case tcc_comparison:
28289 case tcc_binary:
28290 case tcc_expression:
28291 case tcc_vl_exp:
28293 int i, len = cp_tree_operand_length (expression);
28295 for (i = 0; i < len; i++)
28297 tree t = TREE_OPERAND (expression, i);
28299 /* In some cases, some of the operands may be missing.
28300 (For example, in the case of PREDECREMENT_EXPR, the
28301 amount to increment by may be missing.) That doesn't
28302 make the expression dependent. */
28303 if (t && value_dependent_expression_p (t))
28304 return true;
28307 break;
28308 default:
28309 break;
28311 break;
28314 /* The expression is not value-dependent. */
28315 return false;
28318 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
28319 [temp.dep.expr]. Note that an expression with no type is
28320 considered dependent. Other parts of the compiler arrange for an
28321 expression with type-dependent subexpressions to have no type, so
28322 this function doesn't have to be fully recursive. */
28324 bool
28325 type_dependent_expression_p (tree expression)
28327 if (!processing_template_decl)
28328 return false;
28330 if (expression == NULL_TREE || expression == error_mark_node)
28331 return false;
28333 gcc_checking_assert (!TYPE_P (expression));
28335 STRIP_ANY_LOCATION_WRAPPER (expression);
28337 /* An unresolved name is always dependent. */
28338 if (identifier_p (expression)
28339 || TREE_CODE (expression) == USING_DECL
28340 || TREE_CODE (expression) == WILDCARD_DECL)
28341 return true;
28343 /* A lambda-expression in template context is dependent. dependent_type_p is
28344 true for a lambda in the scope of a class or function template, but that
28345 doesn't cover all template contexts, like a default template argument. */
28346 if (TREE_CODE (expression) == LAMBDA_EXPR)
28347 return true;
28349 /* A fold expression is type-dependent. */
28350 if (TREE_CODE (expression) == UNARY_LEFT_FOLD_EXPR
28351 || TREE_CODE (expression) == UNARY_RIGHT_FOLD_EXPR
28352 || TREE_CODE (expression) == BINARY_LEFT_FOLD_EXPR
28353 || TREE_CODE (expression) == BINARY_RIGHT_FOLD_EXPR)
28354 return true;
28356 /* Some expression forms are never type-dependent. */
28357 if (TREE_CODE (expression) == SIZEOF_EXPR
28358 || TREE_CODE (expression) == ALIGNOF_EXPR
28359 || TREE_CODE (expression) == AT_ENCODE_EXPR
28360 || TREE_CODE (expression) == NOEXCEPT_EXPR
28361 || TREE_CODE (expression) == TRAIT_EXPR
28362 || TREE_CODE (expression) == TYPEID_EXPR
28363 || TREE_CODE (expression) == DELETE_EXPR
28364 || TREE_CODE (expression) == VEC_DELETE_EXPR
28365 || TREE_CODE (expression) == THROW_EXPR
28366 || TREE_CODE (expression) == REQUIRES_EXPR)
28367 return false;
28369 /* The types of these expressions depends only on the type to which
28370 the cast occurs. */
28371 if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
28372 || TREE_CODE (expression) == STATIC_CAST_EXPR
28373 || TREE_CODE (expression) == CONST_CAST_EXPR
28374 || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
28375 || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
28376 || TREE_CODE (expression) == CAST_EXPR)
28377 return dependent_type_p (TREE_TYPE (expression));
28379 /* The types of these expressions depends only on the type created
28380 by the expression. */
28381 if (TREE_CODE (expression) == NEW_EXPR
28382 || TREE_CODE (expression) == VEC_NEW_EXPR)
28384 /* For NEW_EXPR tree nodes created inside a template, either
28385 the object type itself or a TREE_LIST may appear as the
28386 operand 1. */
28387 tree type = TREE_OPERAND (expression, 1);
28388 if (TREE_CODE (type) == TREE_LIST)
28389 /* This is an array type. We need to check array dimensions
28390 as well. */
28391 return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
28392 || value_dependent_expression_p
28393 (TREE_OPERAND (TREE_VALUE (type), 1));
28394 /* Array type whose dimension has to be deduced. */
28395 else if (TREE_CODE (type) == ARRAY_TYPE
28396 && TREE_OPERAND (expression, 2) == NULL_TREE)
28397 return true;
28398 else
28399 return dependent_type_p (type);
28402 if (TREE_CODE (expression) == SCOPE_REF)
28404 tree scope = TREE_OPERAND (expression, 0);
28405 tree name = TREE_OPERAND (expression, 1);
28407 /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
28408 contains an identifier associated by name lookup with one or more
28409 declarations declared with a dependent type, or...a
28410 nested-name-specifier or qualified-id that names a member of an
28411 unknown specialization. */
28412 return (type_dependent_expression_p (name)
28413 || dependent_scope_p (scope));
28416 if (TREE_CODE (expression) == TEMPLATE_DECL
28417 && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
28418 return uses_outer_template_parms (expression);
28420 if (TREE_CODE (expression) == STMT_EXPR)
28421 expression = stmt_expr_value_expr (expression);
28423 if (BRACE_ENCLOSED_INITIALIZER_P (expression))
28425 for (auto &elt : CONSTRUCTOR_ELTS (expression))
28426 if (type_dependent_expression_p (elt.value))
28427 return true;
28428 return false;
28431 /* A static data member of the current instantiation with incomplete
28432 array type is type-dependent, as the definition and specializations
28433 can have different bounds. */
28434 if (VAR_P (expression)
28435 && DECL_CLASS_SCOPE_P (expression)
28436 && dependent_type_p (DECL_CONTEXT (expression))
28437 && VAR_HAD_UNKNOWN_BOUND (expression))
28438 return true;
28440 /* An array of unknown bound depending on a variadic parameter, eg:
28442 template<typename... Args>
28443 void foo (Args... args)
28445 int arr[] = { args... };
28448 template<int... vals>
28449 void bar ()
28451 int arr[] = { vals... };
28454 If the array has no length and has an initializer, it must be that
28455 we couldn't determine its length in cp_complete_array_type because
28456 it is dependent. */
28457 if (((VAR_P (expression) && DECL_INITIAL (expression))
28458 || COMPOUND_LITERAL_P (expression))
28459 && TREE_TYPE (expression) != NULL_TREE
28460 && TREE_CODE (TREE_TYPE (expression)) == ARRAY_TYPE
28461 && !TYPE_DOMAIN (TREE_TYPE (expression)))
28462 return true;
28464 /* Pull a FUNCTION_DECL out of a BASELINK if we can. */
28465 if (BASELINK_P (expression))
28467 if (BASELINK_OPTYPE (expression)
28468 && dependent_type_p (BASELINK_OPTYPE (expression)))
28469 return true;
28470 expression = BASELINK_FUNCTIONS (expression);
28473 /* A function or variable template-id is type-dependent if it has any
28474 dependent template arguments. */
28475 if (VAR_OR_FUNCTION_DECL_P (expression)
28476 && DECL_LANG_SPECIFIC (expression)
28477 && DECL_TEMPLATE_INFO (expression))
28479 /* Consider the innermost template arguments, since those are the ones
28480 that come from the template-id; the template arguments for the
28481 enclosing class do not make it type-dependent unless they are used in
28482 the type of the decl. */
28483 if (instantiates_primary_template_p (expression)
28484 && (any_dependent_template_arguments_p
28485 (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
28486 return true;
28489 /* Otherwise, if the function decl isn't from a dependent scope, it can't be
28490 type-dependent. Checking this is important for functions with auto return
28491 type, which looks like a dependent type. */
28492 if (TREE_CODE (expression) == FUNCTION_DECL
28493 && !(DECL_CLASS_SCOPE_P (expression)
28494 && dependent_type_p (DECL_CONTEXT (expression)))
28495 && !(DECL_LANG_SPECIFIC (expression)
28496 && DECL_UNIQUE_FRIEND_P (expression)
28497 && (!DECL_FRIEND_CONTEXT (expression)
28498 || dependent_type_p (DECL_FRIEND_CONTEXT (expression))))
28499 && !DECL_LOCAL_DECL_P (expression))
28501 gcc_assert (!dependent_type_p (TREE_TYPE (expression))
28502 || undeduced_auto_decl (expression));
28503 return false;
28506 /* Otherwise, its constraints could still depend on outer template parameters
28507 from its (dependent) scope. */
28508 if (TREE_CODE (expression) == FUNCTION_DECL
28509 /* As an optimization, check this cheaper sufficient condition first.
28510 (At this point we've established that we're looking at a member of
28511 a dependent class, so it makes sense to start treating say undeduced
28512 auto as dependent.) */
28513 && !dependent_type_p (TREE_TYPE (expression))
28514 && uses_outer_template_parms_in_constraints (expression))
28515 return true;
28517 /* Always dependent, on the number of arguments if nothing else. */
28518 if (TREE_CODE (expression) == EXPR_PACK_EXPANSION)
28519 return true;
28521 if (TREE_TYPE (expression) == unknown_type_node)
28523 if (TREE_CODE (expression) == ADDR_EXPR)
28524 return type_dependent_expression_p (TREE_OPERAND (expression, 0));
28525 if (TREE_CODE (expression) == COMPONENT_REF
28526 || TREE_CODE (expression) == OFFSET_REF)
28528 if (type_dependent_object_expression_p (TREE_OPERAND (expression, 0)))
28529 return true;
28530 expression = TREE_OPERAND (expression, 1);
28531 if (identifier_p (expression))
28532 return false;
28534 /* SCOPE_REF with non-null TREE_TYPE is always non-dependent. */
28535 if (TREE_CODE (expression) == SCOPE_REF)
28536 return false;
28538 /* CO_AWAIT/YIELD_EXPR with unknown type is always dependent. */
28539 if (TREE_CODE (expression) == CO_AWAIT_EXPR
28540 || TREE_CODE (expression) == CO_YIELD_EXPR)
28541 return true;
28543 if (BASELINK_P (expression))
28545 if (BASELINK_OPTYPE (expression)
28546 && dependent_type_p (BASELINK_OPTYPE (expression)))
28547 return true;
28548 expression = BASELINK_FUNCTIONS (expression);
28551 if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
28553 if (any_dependent_template_arguments_p
28554 (TREE_OPERAND (expression, 1)))
28555 return true;
28556 expression = TREE_OPERAND (expression, 0);
28557 if (identifier_p (expression))
28558 return true;
28561 gcc_assert (OVL_P (expression));
28563 for (lkp_iterator iter (expression); iter; ++iter)
28564 if (type_dependent_expression_p (*iter))
28565 return true;
28567 return false;
28570 /* The type of a non-type template parm declared with a placeholder type
28571 depends on the corresponding template argument, even though
28572 placeholders are not normally considered dependent. */
28573 if (TREE_CODE (expression) == TEMPLATE_PARM_INDEX
28574 && is_auto (TREE_TYPE (expression)))
28575 return true;
28577 gcc_assert (TREE_CODE (expression) != TYPE_DECL);
28579 /* Dependent type attributes might not have made it from the decl to
28580 the type yet. */
28581 if (DECL_P (expression)
28582 && any_dependent_type_attributes_p (DECL_ATTRIBUTES (expression)))
28583 return true;
28585 return (dependent_type_p (TREE_TYPE (expression)));
28588 /* [temp.dep.expr]/5: A class member access expression (5.2.5) is
28589 type-dependent if the expression refers to a member of the current
28590 instantiation and the type of the referenced member is dependent, or the
28591 class member access expression refers to a member of an unknown
28592 specialization.
28594 This function returns true if the OBJECT in such a class member access
28595 expression is of an unknown specialization. */
28597 bool
28598 type_dependent_object_expression_p (tree object)
28600 /* An IDENTIFIER_NODE can sometimes have a TREE_TYPE, but it's still
28601 dependent. */
28602 if (TREE_CODE (object) == IDENTIFIER_NODE)
28603 return true;
28604 tree scope = TREE_TYPE (object);
28605 return (!scope || dependent_scope_p (scope));
28608 /* walk_tree callback function for instantiation_dependent_expression_p,
28609 below. Returns non-zero if a dependent subexpression is found. */
28611 static tree
28612 instantiation_dependent_r (tree *tp, int *walk_subtrees,
28613 void * /*data*/)
28615 if (TYPE_P (*tp))
28617 /* We don't have to worry about decltype currently because decltype
28618 of an instantiation-dependent expr is a dependent type. This
28619 might change depending on the resolution of DR 1172. */
28620 *walk_subtrees = false;
28621 return NULL_TREE;
28623 enum tree_code code = TREE_CODE (*tp);
28624 switch (code)
28626 /* Don't treat an argument list as dependent just because it has no
28627 TREE_TYPE. */
28628 case TREE_LIST:
28629 case TREE_VEC:
28630 case NONTYPE_ARGUMENT_PACK:
28631 return NULL_TREE;
28633 case TEMPLATE_PARM_INDEX:
28634 if (dependent_type_p (TREE_TYPE (*tp)))
28635 return *tp;
28636 if (TEMPLATE_PARM_PARAMETER_PACK (*tp))
28637 return *tp;
28638 /* We'll check value-dependence separately. */
28639 return NULL_TREE;
28641 /* Handle expressions with type operands. */
28642 case SIZEOF_EXPR:
28643 case ALIGNOF_EXPR:
28644 case TYPEID_EXPR:
28645 case AT_ENCODE_EXPR:
28647 tree op = TREE_OPERAND (*tp, 0);
28648 if (code == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (*tp))
28649 op = TREE_TYPE (op);
28650 if (TYPE_P (op))
28652 if (dependent_type_p (op))
28653 return *tp;
28654 else
28656 *walk_subtrees = false;
28657 return NULL_TREE;
28660 break;
28663 case COMPONENT_REF:
28664 if (identifier_p (TREE_OPERAND (*tp, 1)))
28665 /* In a template, finish_class_member_access_expr creates a
28666 COMPONENT_REF with an IDENTIFIER_NODE for op1 even if it isn't
28667 type-dependent, so that we can check access control at
28668 instantiation time (PR 42277). See also Core issue 1273. */
28669 return *tp;
28670 break;
28672 case SCOPE_REF:
28673 if (instantiation_dependent_scope_ref_p (*tp))
28674 return *tp;
28675 else
28676 break;
28678 /* Treat statement-expressions as dependent. */
28679 case BIND_EXPR:
28680 return *tp;
28682 /* Treat requires-expressions as dependent. */
28683 case REQUIRES_EXPR:
28684 return *tp;
28686 case CONSTRUCTOR:
28687 if (CONSTRUCTOR_IS_DEPENDENT (*tp))
28688 return *tp;
28689 break;
28691 case TEMPLATE_DECL:
28692 case FUNCTION_DECL:
28693 /* Before C++17, a noexcept-specifier isn't part of the function type
28694 so it doesn't affect type dependence, but we still want to consider it
28695 for instantiation dependence. */
28696 if (cxx_dialect < cxx17
28697 && DECL_DECLARES_FUNCTION_P (*tp)
28698 && value_dependent_noexcept_spec_p (TREE_TYPE (*tp)))
28699 return *tp;
28700 break;
28702 default:
28703 break;
28706 if (type_dependent_expression_p (*tp))
28707 return *tp;
28708 else
28709 return NULL_TREE;
28712 /* Returns TRUE if the EXPRESSION is instantiation-dependent, in the
28713 sense defined by the ABI:
28715 "An expression is instantiation-dependent if it is type-dependent
28716 or value-dependent, or it has a subexpression that is type-dependent
28717 or value-dependent."
28719 Except don't actually check value-dependence for unevaluated expressions,
28720 because in sizeof(i) we don't care about the value of i. Checking
28721 type-dependence will in turn check value-dependence of array bounds/template
28722 arguments as needed. */
28724 bool
28725 instantiation_dependent_uneval_expression_p (tree expression)
28727 tree result;
28729 if (!processing_template_decl)
28730 return false;
28732 if (expression == error_mark_node)
28733 return false;
28735 result = cp_walk_tree_without_duplicates (&expression,
28736 instantiation_dependent_r, NULL);
28737 return result != NULL_TREE;
28740 /* As above, but also check value-dependence of the expression as a whole. */
28742 bool
28743 instantiation_dependent_expression_p (tree expression)
28745 return (instantiation_dependent_uneval_expression_p (expression)
28746 || (processing_template_decl
28747 && potential_constant_expression (expression)
28748 && value_dependent_expression_p (expression)));
28751 /* Like type_dependent_expression_p, but it also works while not processing
28752 a template definition, i.e. during substitution or mangling. */
28754 bool
28755 type_dependent_expression_p_push (tree expr)
28757 bool b;
28758 ++processing_template_decl;
28759 b = type_dependent_expression_p (expr);
28760 --processing_template_decl;
28761 return b;
28764 /* Returns TRUE if ARGS contains a type-dependent expression. */
28766 bool
28767 any_type_dependent_arguments_p (const vec<tree, va_gc> *args)
28769 if (!processing_template_decl || !args)
28770 return false;
28772 for (tree arg : *args)
28773 if (type_dependent_expression_p (arg))
28774 return true;
28776 return false;
28779 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
28780 expressions) contains any type-dependent expressions. */
28782 bool
28783 any_type_dependent_elements_p (const_tree list)
28785 for (; list; list = TREE_CHAIN (list))
28786 if (type_dependent_expression_p (TREE_VALUE (list)))
28787 return true;
28789 return false;
28792 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
28793 expressions) contains any value-dependent expressions. */
28795 bool
28796 any_value_dependent_elements_p (const_tree list)
28798 for (; list; list = TREE_CHAIN (list))
28799 if (value_dependent_expression_p (TREE_VALUE (list)))
28800 return true;
28802 return false;
28805 /* Returns TRUE if the ARG (a template argument) is dependent. */
28807 bool
28808 dependent_template_arg_p (tree arg)
28810 if (!processing_template_decl)
28811 return false;
28813 /* Assume a template argument that was wrongly written by the user
28814 is dependent. This is consistent with what
28815 any_dependent_template_arguments_p [that calls this function]
28816 does. */
28817 if (!arg || arg == error_mark_node)
28818 return true;
28820 if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
28821 arg = argument_pack_select_arg (arg);
28823 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
28824 return true;
28825 if (TREE_CODE (arg) == TEMPLATE_DECL)
28827 if (DECL_TEMPLATE_PARM_P (arg))
28828 return true;
28829 /* A member template of a dependent class is not necessarily
28830 type-dependent, but it is a dependent template argument because it
28831 will be a member of an unknown specialization to that template. */
28832 tree scope = CP_DECL_CONTEXT (arg);
28833 return TYPE_P (scope) && dependent_type_p (scope);
28835 else if (ARGUMENT_PACK_P (arg))
28837 tree args = ARGUMENT_PACK_ARGS (arg);
28838 for (tree arg : tree_vec_range (args))
28839 if (dependent_template_arg_p (arg))
28840 return true;
28841 return false;
28843 else if (TYPE_P (arg))
28844 return dependent_type_p (arg);
28845 else
28846 return value_dependent_expression_p (arg);
28849 /* Identify any expressions that use function parms. */
28851 static tree
28852 find_parm_usage_r (tree *tp, int *walk_subtrees, void*)
28854 tree t = *tp;
28855 if (TREE_CODE (t) == PARM_DECL)
28857 *walk_subtrees = 0;
28858 return t;
28860 return NULL_TREE;
28863 /* Returns true if a type specialization formed using the template
28864 arguments ARGS needs to use structural equality. */
28866 bool
28867 any_template_arguments_need_structural_equality_p (tree args)
28869 int i;
28870 int j;
28872 if (!args)
28873 return false;
28874 if (args == error_mark_node)
28875 return true;
28877 for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
28879 tree level = TMPL_ARGS_LEVEL (args, i + 1);
28880 for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
28882 tree arg = TREE_VEC_ELT (level, j);
28883 tree packed_args = NULL_TREE;
28884 int k, len = 1;
28886 if (ARGUMENT_PACK_P (arg))
28888 /* Look inside the argument pack. */
28889 packed_args = ARGUMENT_PACK_ARGS (arg);
28890 len = TREE_VEC_LENGTH (packed_args);
28893 for (k = 0; k < len; ++k)
28895 if (packed_args)
28896 arg = TREE_VEC_ELT (packed_args, k);
28898 if (error_operand_p (arg))
28899 return true;
28900 else if (TREE_CODE (arg) == TEMPLATE_DECL)
28901 continue;
28902 else if (arg == any_targ_node)
28903 /* An any_targ_node argument (added by add_defaults_to_ttp)
28904 makes the corresponding specialization not canonicalizable,
28905 since template_args_equal always return true for it. We
28906 may see this when called from bind_template_template_parm. */
28907 return true;
28908 /* Checking current_function_decl because this structural
28909 comparison is only necessary for redeclaration. */
28910 else if (!current_function_decl
28911 && dependent_template_arg_p (arg)
28912 && (cp_walk_tree_without_duplicates
28913 (&arg, find_parm_usage_r, NULL)))
28914 /* The identity of a class template specialization that uses
28915 a function parameter depends on the identity of the function.
28916 And if this specialization appeared in the trailing return
28917 type thereof, we don't know the identity of the function
28918 (e.g. if it's a redeclaration or a new function) until we
28919 form its signature and go through duplicate_decls. Thus
28920 it's unsafe to decide on a canonical type now (which depends
28921 on the DECL_CONTEXT of the function parameter, which can get
28922 mutated after the fact by duplicate_decls), so just require
28923 structural equality in this case (PR52830). */
28924 return true;
28925 else if (TYPE_P (arg)
28926 && TYPE_STRUCTURAL_EQUALITY_P (arg)
28927 && dependent_alias_template_spec_p (arg, nt_transparent))
28928 /* Require structural equality for specializations written
28929 in terms of a dependent alias template specialization. */
28930 return true;
28931 else if (CLASS_TYPE_P (arg)
28932 && TYPE_TEMPLATE_INFO (arg)
28933 && TYPE_STRUCTURAL_EQUALITY_P (arg))
28934 /* Require structural equality for specializations written
28935 in terms of a class template specialization that itself
28936 needs structural equality. */
28937 return true;
28942 return false;
28945 /* Returns true if ARGS (a collection of template arguments) contains
28946 any dependent arguments. */
28948 bool
28949 any_dependent_template_arguments_p (const_tree args)
28951 if (args == error_mark_node)
28952 return true;
28953 if (!processing_template_decl || !args)
28954 return false;
28956 for (int i = 0, depth = TMPL_ARGS_DEPTH (args); i < depth; ++i)
28958 const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
28959 for (tree arg : tree_vec_range (CONST_CAST_TREE (level)))
28960 if (dependent_template_arg_p (arg))
28961 return true;
28964 return false;
28967 /* Returns true if ARGS contains any errors. */
28969 bool
28970 any_erroneous_template_args_p (const_tree args)
28972 int i;
28973 int j;
28975 if (args == error_mark_node)
28976 return true;
28978 if (args && TREE_CODE (args) != TREE_VEC)
28980 if (tree ti = get_template_info (args))
28981 args = TI_ARGS (ti);
28982 else
28983 args = NULL_TREE;
28986 if (!args)
28987 return false;
28989 for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
28991 const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
28992 for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
28993 if (error_operand_p (TREE_VEC_ELT (level, j)))
28994 return true;
28997 return false;
29000 /* Returns TRUE if the template TMPL is type-dependent. */
29002 bool
29003 dependent_template_p (tree tmpl)
29005 if (TREE_CODE (tmpl) == OVERLOAD)
29007 for (lkp_iterator iter (tmpl); iter; ++iter)
29008 if (dependent_template_p (*iter))
29009 return true;
29010 return false;
29013 /* Template template parameters are dependent. */
29014 if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
29015 || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
29016 return true;
29017 /* So are names that have not been looked up. */
29018 if (TREE_CODE (tmpl) == SCOPE_REF || identifier_p (tmpl))
29019 return true;
29020 return false;
29023 /* Returns TRUE if the specialization TMPL<ARGS> is dependent. */
29025 bool
29026 dependent_template_id_p (tree tmpl, tree args)
29028 return (dependent_template_p (tmpl)
29029 || any_dependent_template_arguments_p (args));
29032 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
29033 are dependent. */
29035 bool
29036 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
29038 int i;
29040 if (!processing_template_decl)
29041 return false;
29043 for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
29045 tree decl = TREE_VEC_ELT (declv, i);
29046 tree init = TREE_VEC_ELT (initv, i);
29047 tree cond = TREE_VEC_ELT (condv, i);
29048 tree incr = TREE_VEC_ELT (incrv, i);
29050 if (type_dependent_expression_p (decl)
29051 || TREE_CODE (decl) == SCOPE_REF)
29052 return true;
29054 if (init && type_dependent_expression_p (init))
29055 return true;
29057 if (cond == global_namespace)
29058 return true;
29060 if (type_dependent_expression_p (cond))
29061 return true;
29063 if (COMPARISON_CLASS_P (cond)
29064 && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
29065 || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
29066 return true;
29068 if (TREE_CODE (incr) == MODOP_EXPR)
29070 if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
29071 || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
29072 return true;
29074 else if (type_dependent_expression_p (incr))
29075 return true;
29076 else if (TREE_CODE (incr) == MODIFY_EXPR)
29078 if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
29079 return true;
29080 else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
29082 tree t = TREE_OPERAND (incr, 1);
29083 if (type_dependent_expression_p (TREE_OPERAND (t, 0))
29084 || type_dependent_expression_p (TREE_OPERAND (t, 1)))
29085 return true;
29087 /* If this loop has a class iterator with != comparison
29088 with increment other than i++/++i/i--/--i, make sure the
29089 increment is constant. */
29090 if (CLASS_TYPE_P (TREE_TYPE (decl))
29091 && TREE_CODE (cond) == NE_EXPR)
29093 if (TREE_OPERAND (t, 0) == decl)
29094 t = TREE_OPERAND (t, 1);
29095 else
29096 t = TREE_OPERAND (t, 0);
29097 if (TREE_CODE (t) != INTEGER_CST)
29098 return true;
29104 return false;
29107 /* TYPE is a TYPENAME_TYPE. Returns the ordinary TYPE to which the
29108 TYPENAME_TYPE corresponds. Returns the original TYPENAME_TYPE if
29109 no such TYPE can be found. Note that this function peers inside
29110 uninstantiated templates and therefore should be used only in
29111 extremely limited situations. ONLY_CURRENT_P restricts this
29112 peering to the currently open classes hierarchy (which is required
29113 when comparing types). */
29115 tree
29116 resolve_typename_type (tree type, bool only_current_p)
29118 tree scope;
29119 tree name;
29120 tree decl;
29121 int quals;
29122 tree pushed_scope;
29123 tree result;
29125 gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
29127 scope = TYPE_CONTEXT (type);
29128 /* We shouldn't have built a TYPENAME_TYPE with a non-dependent scope. */
29129 gcc_checking_assert (uses_template_parms (scope));
29131 /* Usually the non-qualified identifier of a TYPENAME_TYPE is
29132 TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of a
29133 TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL
29134 representing the typedef. In that case TYPE_IDENTIFIER (type) is
29135 not the non-qualified identifier of the TYPENAME_TYPE anymore.
29136 So by getting the TYPE_IDENTIFIER of the _main declaration_ of
29137 the TYPENAME_TYPE instead, we avoid messing up with a possible
29138 typedef variant case. */
29139 name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
29141 /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
29142 it first before we can figure out what NAME refers to. */
29143 if (TREE_CODE (scope) == TYPENAME_TYPE)
29145 if (TYPENAME_IS_RESOLVING_P (scope))
29146 /* Given a class template A with a dependent base with nested type C,
29147 typedef typename A::C::C C will land us here, as trying to resolve
29148 the initial A::C leads to the local C typedef, which leads back to
29149 A::C::C. So we break the recursion now. */
29150 return type;
29151 else
29152 scope = resolve_typename_type (scope, only_current_p);
29154 /* If we don't know what SCOPE refers to, then we cannot resolve the
29155 TYPENAME_TYPE. */
29156 if (!CLASS_TYPE_P (scope))
29157 return type;
29158 /* If this is a typedef, we don't want to look inside (c++/11987). */
29159 if (typedef_variant_p (type))
29160 return type;
29161 /* If SCOPE isn't the template itself, it will not have a valid
29162 TYPE_FIELDS list. */
29163 if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
29164 /* scope is either the template itself or a compatible instantiation
29165 like X<T>, so look up the name in the original template. */
29166 scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
29167 /* If scope has no fields, it can't be a current instantiation. Check this
29168 before currently_open_class to avoid infinite recursion (71515). */
29169 if (!TYPE_FIELDS (scope))
29170 return type;
29171 /* If the SCOPE is not the current instantiation, there's no reason
29172 to look inside it. */
29173 if (only_current_p && !currently_open_class (scope))
29174 return type;
29175 /* Enter the SCOPE so that name lookup will be resolved as if we
29176 were in the class definition. In particular, SCOPE will no
29177 longer be considered a dependent type. */
29178 pushed_scope = push_scope (scope);
29179 /* Look up the declaration. */
29180 decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true,
29181 tf_warning_or_error);
29183 result = NULL_TREE;
29185 /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
29186 find a TEMPLATE_DECL. Otherwise, we want to find a TYPE_DECL. */
29187 tree fullname = TYPENAME_TYPE_FULLNAME (type);
29188 if (!decl)
29189 /*nop*/;
29190 else if (identifier_p (fullname)
29191 && TREE_CODE (decl) == TYPE_DECL)
29193 result = TREE_TYPE (decl);
29194 if (result == error_mark_node)
29195 result = NULL_TREE;
29197 else if (TREE_CODE (fullname) == TEMPLATE_ID_EXPR
29198 && DECL_CLASS_TEMPLATE_P (decl))
29200 /* Obtain the template and the arguments. */
29201 tree tmpl = TREE_OPERAND (fullname, 0);
29202 if (TREE_CODE (tmpl) == IDENTIFIER_NODE)
29204 /* We get here with a plain identifier because a previous tentative
29205 parse of the nested-name-specifier as part of a ptr-operator saw
29206 ::template X<A>. The use of ::template is necessary in a
29207 ptr-operator, but wrong in a declarator-id.
29209 [temp.names]: In a qualified-id of a declarator-id, the keyword
29210 template shall not appear at the top level. */
29211 pedwarn (cp_expr_loc_or_input_loc (fullname), OPT_Wpedantic,
29212 "keyword %<template%> not allowed in declarator-id");
29213 tmpl = decl;
29215 tree args = TREE_OPERAND (fullname, 1);
29216 /* Instantiate the template. */
29217 result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
29218 /*entering_scope=*/true,
29219 tf_error | tf_user);
29220 if (result == error_mark_node)
29221 result = NULL_TREE;
29224 /* Leave the SCOPE. */
29225 if (pushed_scope)
29226 pop_scope (pushed_scope);
29228 /* If we failed to resolve it, return the original typename. */
29229 if (!result)
29230 return type;
29232 /* If lookup found a typename type, resolve that too. */
29233 if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
29235 /* Ill-formed programs can cause infinite recursion here, so we
29236 must catch that. */
29237 TYPENAME_IS_RESOLVING_P (result) = 1;
29238 result = resolve_typename_type (result, only_current_p);
29239 TYPENAME_IS_RESOLVING_P (result) = 0;
29242 /* Qualify the resulting type. */
29243 quals = cp_type_quals (type);
29244 if (quals)
29245 result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
29247 return result;
29250 /* Returns a type which represents 'auto' or 'decltype(auto)'. We use a
29251 TEMPLATE_TYPE_PARM with a level one deeper than the actual template parms,
29252 by default. If set_canonical is true, we set TYPE_CANONICAL on it. */
29254 static tree
29255 make_auto_1 (tree name, bool set_canonical, int level = -1)
29257 if (level == -1)
29258 level = current_template_depth + 1;
29259 tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
29260 TYPE_NAME (au) = build_decl (input_location, TYPE_DECL, name, au);
29261 TYPE_STUB_DECL (au) = TYPE_NAME (au);
29262 TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
29263 (0, level, level, TYPE_NAME (au), NULL_TREE);
29264 if (set_canonical)
29265 TYPE_CANONICAL (au) = canonical_type_parameter (au);
29266 DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
29267 SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
29268 if (name == decltype_auto_identifier)
29269 AUTO_IS_DECLTYPE (au) = true;
29271 return au;
29274 tree
29275 make_decltype_auto (void)
29277 return make_auto_1 (decltype_auto_identifier, true);
29280 tree
29281 make_auto (void)
29283 return make_auto_1 (auto_identifier, true);
29286 /* Return a C++17 deduction placeholder for class template TMPL.
29287 There are represented as an 'auto' with the special level 0 and
29288 CLASS_PLACEHOLDER_TEMPLATE set. */
29290 tree
29291 make_template_placeholder (tree tmpl)
29293 tree t = make_auto_1 (auto_identifier, false, /*level=*/0);
29294 CLASS_PLACEHOLDER_TEMPLATE (t) = tmpl;
29295 /* Our canonical type depends on the placeholder. */
29296 TYPE_CANONICAL (t) = canonical_type_parameter (t);
29297 return t;
29300 /* True iff T is a C++17 class template deduction placeholder. */
29302 bool
29303 template_placeholder_p (tree t)
29305 return is_auto (t) && CLASS_PLACEHOLDER_TEMPLATE (t);
29308 /* Make a "constrained auto" type-specifier. This is an auto or
29309 decltype(auto) type with constraints that must be associated after
29310 deduction. The constraint is formed from the given concept CON
29311 and its optional sequence of template arguments ARGS.
29313 TYPE must be the result of make_auto_type or make_decltype_auto_type. */
29315 static tree
29316 make_constrained_placeholder_type (tree type, tree con, tree args)
29318 /* Build the constraint. */
29319 tree tmpl = DECL_TI_TEMPLATE (con);
29320 tree expr = tmpl;
29321 if (TREE_CODE (con) == FUNCTION_DECL)
29322 expr = ovl_make (tmpl);
29323 ++processing_template_decl;
29324 expr = build_concept_check (expr, type, args, tf_warning_or_error);
29325 --processing_template_decl;
29327 PLACEHOLDER_TYPE_CONSTRAINTS_INFO (type)
29328 = build_tree_list (current_template_parms, expr);
29330 /* Our canonical type depends on the constraint. */
29331 TYPE_CANONICAL (type) = canonical_type_parameter (type);
29333 /* Attach the constraint to the type declaration. */
29334 return TYPE_NAME (type);
29337 /* Make a "constrained auto" type-specifier. */
29339 tree
29340 make_constrained_auto (tree con, tree args)
29342 tree type = make_auto_1 (auto_identifier, false);
29343 return make_constrained_placeholder_type (type, con, args);
29346 /* Make a "constrained decltype(auto)" type-specifier. */
29348 tree
29349 make_constrained_decltype_auto (tree con, tree args)
29351 tree type = make_auto_1 (decltype_auto_identifier, false);
29352 return make_constrained_placeholder_type (type, con, args);
29355 /* Returns true if the placeholder type constraint T has any dependent
29356 (explicit) template arguments. */
29358 static bool
29359 placeholder_type_constraint_dependent_p (tree t)
29361 tree id = unpack_concept_check (t);
29362 tree args = TREE_OPERAND (id, 1);
29363 tree first = TREE_VEC_ELT (args, 0);
29364 if (ARGUMENT_PACK_P (first))
29366 args = expand_template_argument_pack (args);
29367 first = TREE_VEC_ELT (args, 0);
29369 gcc_checking_assert (TREE_CODE (first) == WILDCARD_DECL
29370 || is_auto (first));
29371 for (int i = 1; i < TREE_VEC_LENGTH (args); ++i)
29372 if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
29373 return true;
29374 return false;
29377 /* Build and return a concept definition. Like other templates, the
29378 CONCEPT_DECL node is wrapped by a TEMPLATE_DECL. This returns the
29379 the TEMPLATE_DECL. */
29381 tree
29382 finish_concept_definition (cp_expr id, tree init, tree attrs)
29384 gcc_assert (identifier_p (id));
29385 gcc_assert (processing_template_decl);
29387 location_t loc = id.get_location();
29389 /* A concept-definition shall not have associated constraints. */
29390 if (TEMPLATE_PARMS_CONSTRAINTS (current_template_parms))
29392 error_at (loc, "a concept cannot be constrained");
29393 TEMPLATE_PARMS_CONSTRAINTS (current_template_parms) = NULL_TREE;
29396 /* A concept-definition shall appear in namespace scope. Templates
29397 aren't allowed in block scope, so we only need to check for class
29398 scope. */
29399 if (TYPE_P (current_scope()) || !DECL_NAMESPACE_SCOPE_P (current_scope ()))
29401 error_at (loc, "concept %qE not in namespace scope", *id);
29402 return error_mark_node;
29405 if (current_template_depth > 1)
29407 error_at (loc, "concept %qE has multiple template parameter lists", *id);
29408 return error_mark_node;
29411 /* Initially build the concept declaration; its type is bool. */
29412 tree decl = build_lang_decl_loc (loc, CONCEPT_DECL, *id, boolean_type_node);
29413 DECL_CONTEXT (decl) = current_scope ();
29414 DECL_INITIAL (decl) = init;
29416 if (attrs)
29417 cplus_decl_attributes (&decl, attrs, 0);
29419 set_originating_module (decl, false);
29421 /* Push the enclosing template. */
29422 return push_template_decl (decl);
29425 /* Given type ARG, return std::initializer_list<ARG>. */
29427 static tree
29428 listify (tree arg)
29430 tree std_init_list = lookup_qualified_name (std_node, init_list_identifier);
29432 if (std_init_list == error_mark_node
29433 || !DECL_CLASS_TEMPLATE_P (std_init_list))
29435 gcc_rich_location richloc (input_location);
29436 maybe_add_include_fixit (&richloc, "<initializer_list>", false);
29437 error_at (&richloc,
29438 "deducing from brace-enclosed initializer list"
29439 " requires %<#include <initializer_list>%>");
29441 return error_mark_node;
29443 tree argvec = make_tree_vec (1);
29444 TREE_VEC_ELT (argvec, 0) = arg;
29446 return lookup_template_class (std_init_list, argvec, NULL_TREE,
29447 NULL_TREE, 0, tf_warning_or_error);
29450 /* Replace auto in TYPE with std::initializer_list<auto>. */
29452 static tree
29453 listify_autos (tree type, tree auto_node)
29455 tree init_auto = listify (strip_top_quals (auto_node));
29456 tree argvec = make_tree_vec (1);
29457 TREE_VEC_ELT (argvec, 0) = init_auto;
29458 if (processing_template_decl)
29459 argvec = add_to_template_args (current_template_args (), argvec);
29460 return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
29463 /* Hash traits for hashing possibly constrained 'auto'
29464 TEMPLATE_TYPE_PARMs for use by do_auto_deduction. */
29466 struct auto_hash : default_hash_traits<tree>
29468 static inline hashval_t hash (tree);
29469 static inline bool equal (tree, tree);
29472 /* Hash the 'auto' T. */
29474 inline hashval_t
29475 auto_hash::hash (tree t)
29477 if (tree c = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (t)))
29478 /* Matching constrained-type-specifiers denote the same template
29479 parameter, so hash the constraint. */
29480 return hash_placeholder_constraint (c);
29481 else
29482 /* But unconstrained autos are all separate, so just hash the pointer. */
29483 return iterative_hash_object (t, 0);
29486 /* Compare two 'auto's. */
29488 inline bool
29489 auto_hash::equal (tree t1, tree t2)
29491 if (t1 == t2)
29492 return true;
29494 tree c1 = PLACEHOLDER_TYPE_CONSTRAINTS (t1);
29495 tree c2 = PLACEHOLDER_TYPE_CONSTRAINTS (t2);
29497 /* Two unconstrained autos are distinct. */
29498 if (!c1 || !c2)
29499 return false;
29501 return equivalent_placeholder_constraints (c1, c2);
29504 /* for_each_template_parm callback for extract_autos: if t is a (possibly
29505 constrained) auto, add it to the vector. */
29507 static int
29508 extract_autos_r (tree t, void *data)
29510 hash_table<auto_hash> &hash = *(hash_table<auto_hash>*)data;
29511 if (is_auto (t) && !template_placeholder_p (t))
29513 /* All the autos were built with index 0; fix that up now. */
29514 tree *p = hash.find_slot (t, INSERT);
29515 int idx;
29516 if (*p)
29517 /* If this is a repeated constrained-type-specifier, use the index we
29518 chose before. */
29519 idx = TEMPLATE_TYPE_IDX (*p);
29520 else
29522 /* Otherwise this is new, so use the current count. */
29523 *p = t;
29524 idx = hash.elements () - 1;
29526 if (idx != TEMPLATE_TYPE_IDX (t))
29528 gcc_checking_assert (TEMPLATE_TYPE_IDX (t) == 0);
29529 gcc_checking_assert (TYPE_CANONICAL (t) != t);
29530 TEMPLATE_TYPE_IDX (t) = idx;
29531 TYPE_CANONICAL (t) = canonical_type_parameter (t);
29535 /* Always keep walking. */
29536 return 0;
29539 /* Return a TREE_VEC of the 'auto's used in type under the Concepts TS, which
29540 says they can appear anywhere in the type. */
29542 static tree
29543 extract_autos (tree type)
29545 hash_set<tree> visited;
29546 hash_table<auto_hash> hash (2);
29548 for_each_template_parm (type, extract_autos_r, &hash, &visited, true);
29550 tree tree_vec = make_tree_vec (hash.elements());
29551 for (tree elt : hash)
29553 unsigned i = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (elt));
29554 TREE_VEC_ELT (tree_vec, i)
29555 = build_tree_list (NULL_TREE, TYPE_NAME (elt));
29558 return tree_vec;
29561 /* The stem for deduction guide names. */
29562 const char *const dguide_base = "__dguide_";
29564 /* Return the name for a deduction guide for class template TMPL. */
29566 tree
29567 dguide_name (tree tmpl)
29569 tree type = (TYPE_P (tmpl) ? tmpl : TREE_TYPE (tmpl));
29570 tree tname = TYPE_IDENTIFIER (type);
29571 char *buf = (char *) alloca (1 + strlen (dguide_base)
29572 + IDENTIFIER_LENGTH (tname));
29573 memcpy (buf, dguide_base, strlen (dguide_base));
29574 memcpy (buf + strlen (dguide_base), IDENTIFIER_POINTER (tname),
29575 IDENTIFIER_LENGTH (tname) + 1);
29576 tree dname = get_identifier (buf);
29577 TREE_TYPE (dname) = type;
29578 return dname;
29581 /* True if NAME is the name of a deduction guide. */
29583 bool
29584 dguide_name_p (tree name)
29586 return (TREE_CODE (name) == IDENTIFIER_NODE
29587 && TREE_TYPE (name)
29588 && startswith (IDENTIFIER_POINTER (name), dguide_base));
29591 /* True if FN is a deduction guide. */
29593 bool
29594 deduction_guide_p (const_tree fn)
29596 if (DECL_P (fn))
29597 if (tree name = DECL_NAME (fn))
29598 return dguide_name_p (name);
29599 return false;
29602 /* True if FN is the copy deduction guide, i.e. A(A)->A. */
29604 bool
29605 copy_guide_p (const_tree fn)
29607 gcc_assert (deduction_guide_p (fn));
29608 if (!DECL_ARTIFICIAL (fn))
29609 return false;
29610 tree parms = FUNCTION_FIRST_USER_PARMTYPE (DECL_TI_TEMPLATE (fn));
29611 return (TREE_CHAIN (parms) == void_list_node
29612 && same_type_p (TREE_VALUE (parms), TREE_TYPE (DECL_NAME (fn))));
29615 /* True if FN is a guide generated from a constructor template. */
29617 bool
29618 template_guide_p (const_tree fn)
29620 gcc_assert (deduction_guide_p (fn));
29621 if (!DECL_ARTIFICIAL (fn))
29622 return false;
29623 tree tmpl = DECL_TI_TEMPLATE (fn);
29624 if (tree org = DECL_ABSTRACT_ORIGIN (tmpl))
29625 return PRIMARY_TEMPLATE_P (org);
29626 return false;
29629 /* True if FN is an aggregate initialization guide or the copy deduction
29630 guide. */
29632 bool
29633 builtin_guide_p (const_tree fn)
29635 if (!deduction_guide_p (fn))
29636 return false;
29637 if (!DECL_ARTIFICIAL (fn))
29638 /* Explicitly declared. */
29639 return false;
29640 if (DECL_ABSTRACT_ORIGIN (fn))
29641 /* Derived from a constructor. */
29642 return false;
29643 return true;
29646 /* OLDDECL is a _DECL for a template parameter. Return a similar parameter at
29647 LEVEL:INDEX, using tsubst_args and complain for substitution into non-type
29648 template parameter types. Note that the handling of template template
29649 parameters relies on current_template_parms being set appropriately for the
29650 new template. */
29652 static tree
29653 rewrite_template_parm (tree olddecl, unsigned index, unsigned level,
29654 tree tsubst_args, tsubst_flags_t complain)
29656 if (olddecl == error_mark_node)
29657 return error_mark_node;
29659 tree oldidx = get_template_parm_index (olddecl);
29661 tree newtype;
29662 if (TREE_CODE (olddecl) == TYPE_DECL
29663 || TREE_CODE (olddecl) == TEMPLATE_DECL)
29665 tree oldtype = TREE_TYPE (olddecl);
29666 newtype = cxx_make_type (TREE_CODE (oldtype));
29667 TYPE_MAIN_VARIANT (newtype) = newtype;
29669 else
29671 newtype = TREE_TYPE (olddecl);
29672 if (type_uses_auto (newtype))
29674 // Substitute once to fix references to other template parameters.
29675 newtype = tsubst (newtype, tsubst_args,
29676 complain|tf_partial, NULL_TREE);
29677 // Now substitute again to reduce the level of the auto.
29678 newtype = tsubst (newtype, current_template_args (),
29679 complain, NULL_TREE);
29681 else
29682 newtype = tsubst (newtype, tsubst_args,
29683 complain, NULL_TREE);
29686 tree newdecl
29687 = build_decl (DECL_SOURCE_LOCATION (olddecl), TREE_CODE (olddecl),
29688 DECL_NAME (olddecl), newtype);
29689 SET_DECL_TEMPLATE_PARM_P (newdecl);
29691 tree newidx;
29692 if (TREE_CODE (olddecl) == TYPE_DECL
29693 || TREE_CODE (olddecl) == TEMPLATE_DECL)
29695 newidx = TEMPLATE_TYPE_PARM_INDEX (newtype)
29696 = build_template_parm_index (index, level, level,
29697 newdecl, newtype);
29698 TEMPLATE_PARM_PARAMETER_PACK (newidx)
29699 = TEMPLATE_PARM_PARAMETER_PACK (oldidx);
29700 TYPE_STUB_DECL (newtype) = TYPE_NAME (newtype) = newdecl;
29702 if (TREE_CODE (olddecl) == TEMPLATE_DECL)
29704 tree newresult
29705 = build_lang_decl_loc (DECL_SOURCE_LOCATION (olddecl), TYPE_DECL,
29706 DECL_NAME (olddecl), newtype);
29707 DECL_ARTIFICIAL (newresult) = true;
29708 DECL_TEMPLATE_RESULT (newdecl) = newresult;
29709 // First create a copy (ttargs) of tsubst_args with an
29710 // additional level for the template template parameter's own
29711 // template parameters (ttparms).
29712 tree ttparms = (INNERMOST_TEMPLATE_PARMS
29713 (DECL_TEMPLATE_PARMS (olddecl)));
29714 const int depth = TMPL_ARGS_DEPTH (tsubst_args);
29715 tree ttargs = make_tree_vec (depth + 1);
29716 for (int i = 0; i < depth; ++i)
29717 TREE_VEC_ELT (ttargs, i) = TMPL_ARGS_LEVEL (tsubst_args, i + 1);
29718 TREE_VEC_ELT (ttargs, depth)
29719 = template_parms_level_to_args (ttparms);
29720 // Substitute ttargs into ttparms to fix references to
29721 // other template parameters.
29722 ttparms = tsubst_template_parms_level (ttparms, ttargs,
29723 complain|tf_partial);
29724 // Now substitute again with args based on tparms, to reduce
29725 // the level of the ttparms.
29726 ttargs = current_template_args ();
29727 ttparms = tsubst_template_parms_level (ttparms, ttargs,
29728 complain);
29729 // Finally, tack the adjusted parms onto tparms.
29730 ttparms = tree_cons (size_int (level + 1), ttparms,
29731 copy_node (current_template_parms));
29732 // As with all template template parms, the parameter list captured
29733 // by this template template parm that corresponds to its own level
29734 // should be empty. This avoids infinite recursion when structurally
29735 // comparing two such rewritten template template parms (PR102479).
29736 gcc_assert (!TREE_VEC_LENGTH
29737 (TREE_VALUE (TREE_CHAIN (DECL_TEMPLATE_PARMS (olddecl)))));
29738 gcc_assert (TMPL_PARMS_DEPTH (TREE_CHAIN (ttparms)) == level);
29739 TREE_VALUE (TREE_CHAIN (ttparms)) = make_tree_vec (0);
29740 // All done.
29741 DECL_TEMPLATE_PARMS (newdecl) = ttparms;
29742 DECL_TEMPLATE_INFO (newresult)
29743 = build_template_info (newdecl, template_parms_to_args (ttparms));
29746 if (TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (olddecl)))
29747 SET_TYPE_STRUCTURAL_EQUALITY (newtype);
29748 else
29749 TYPE_CANONICAL (newtype) = canonical_type_parameter (newtype);
29751 else
29753 tree oldconst = TEMPLATE_PARM_DECL (oldidx);
29754 tree newconst
29755 = build_decl (DECL_SOURCE_LOCATION (oldconst),
29756 TREE_CODE (oldconst),
29757 DECL_NAME (oldconst), newtype);
29758 TREE_CONSTANT (newconst) = TREE_CONSTANT (newdecl)
29759 = TREE_READONLY (newconst) = TREE_READONLY (newdecl) = true;
29760 SET_DECL_TEMPLATE_PARM_P (newconst);
29761 newidx = build_template_parm_index (index, level, level,
29762 newconst, newtype);
29763 TEMPLATE_PARM_PARAMETER_PACK (newidx)
29764 = TEMPLATE_PARM_PARAMETER_PACK (oldidx);
29765 DECL_INITIAL (newdecl) = DECL_INITIAL (newconst) = newidx;
29768 return newdecl;
29771 /* As rewrite_template_parm, but for the whole TREE_LIST representing a
29772 template parameter. */
29774 static tree
29775 rewrite_tparm_list (tree oldelt, unsigned index, unsigned level,
29776 tree targs, unsigned targs_index, tsubst_flags_t complain)
29778 tree olddecl = TREE_VALUE (oldelt);
29779 tree newdecl = rewrite_template_parm (olddecl, index, level,
29780 targs, complain);
29781 if (newdecl == error_mark_node)
29782 return error_mark_node;
29783 tree newdef = tsubst_template_arg (TREE_PURPOSE (oldelt),
29784 targs, complain, NULL_TREE);
29785 tree list = build_tree_list (newdef, newdecl);
29786 TEMPLATE_PARM_CONSTRAINTS (list)
29787 = tsubst_constraint_info (TEMPLATE_PARM_CONSTRAINTS (oldelt),
29788 targs, complain, NULL_TREE);
29789 int depth = TMPL_ARGS_DEPTH (targs);
29790 TMPL_ARG (targs, depth, targs_index) = template_parm_to_arg (list);
29791 return list;
29794 /* Returns a C++17 class deduction guide template based on the constructor
29795 CTOR. As a special case, CTOR can be a RECORD_TYPE for an implicit default
29796 guide, REFERENCE_TYPE for an implicit copy/move guide, or TREE_LIST for an
29797 aggregate initialization guide. OUTER_ARGS are the template arguments
29798 for the enclosing scope of the class. */
29800 static tree
29801 build_deduction_guide (tree type, tree ctor, tree outer_args, tsubst_flags_t complain)
29803 tree tparms, targs, fparms, fargs, ci;
29804 bool memtmpl = false;
29805 bool explicit_p;
29806 location_t loc;
29807 tree fn_tmpl = NULL_TREE;
29809 if (outer_args)
29811 ++processing_template_decl;
29812 type = tsubst (type, outer_args, complain, CLASSTYPE_TI_TEMPLATE (type));
29813 --processing_template_decl;
29816 if (!DECL_DECLARES_FUNCTION_P (ctor))
29818 if (TYPE_P (ctor))
29820 bool copy_p = TYPE_REF_P (ctor);
29821 if (copy_p)
29822 fparms = tree_cons (NULL_TREE, type, void_list_node);
29823 else
29824 fparms = void_list_node;
29826 else if (TREE_CODE (ctor) == TREE_LIST)
29827 fparms = ctor;
29828 else
29829 gcc_unreachable ();
29831 tree ctmpl = CLASSTYPE_TI_TEMPLATE (type);
29832 tparms = DECL_TEMPLATE_PARMS (ctmpl);
29833 targs = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
29834 ci = NULL_TREE;
29835 fargs = NULL_TREE;
29836 loc = DECL_SOURCE_LOCATION (ctmpl);
29837 explicit_p = false;
29839 else
29841 ++processing_template_decl;
29842 bool ok = true;
29844 complain |= tf_dguide;
29846 fn_tmpl
29847 = (TREE_CODE (ctor) == TEMPLATE_DECL ? ctor
29848 : DECL_TI_TEMPLATE (ctor));
29849 if (outer_args)
29850 fn_tmpl = tsubst (fn_tmpl, outer_args, complain, ctor);
29851 ctor = DECL_TEMPLATE_RESULT (fn_tmpl);
29853 tparms = DECL_TEMPLATE_PARMS (fn_tmpl);
29854 /* If type is a member class template, DECL_TI_ARGS (ctor) will have
29855 fully specialized args for the enclosing class. Strip those off, as
29856 the deduction guide won't have those template parameters. */
29857 targs = get_innermost_template_args (DECL_TI_ARGS (ctor),
29858 TMPL_PARMS_DEPTH (tparms));
29859 /* Discard the 'this' parameter. */
29860 fparms = FUNCTION_ARG_CHAIN (ctor);
29861 fargs = TREE_CHAIN (DECL_ARGUMENTS (ctor));
29862 ci = get_constraints (ctor);
29863 loc = DECL_SOURCE_LOCATION (ctor);
29864 explicit_p = DECL_NONCONVERTING_P (ctor);
29866 if (PRIMARY_TEMPLATE_P (fn_tmpl))
29868 memtmpl = true;
29870 /* For a member template constructor, we need to flatten the two
29871 template parameter lists into one, and then adjust the function
29872 signature accordingly. This gets...complicated. */
29873 tree save_parms = current_template_parms;
29875 /* For a member template we should have two levels of parms/args, one
29876 for the class and one for the constructor. We stripped
29877 specialized args for further enclosing classes above. */
29878 const int depth = 2;
29879 gcc_assert (TMPL_ARGS_DEPTH (targs) == depth);
29881 /* Template args for translating references to the two-level template
29882 parameters into references to the one-level template parameters we
29883 are creating. */
29884 tree tsubst_args = copy_node (targs);
29885 TMPL_ARGS_LEVEL (tsubst_args, depth)
29886 = copy_node (TMPL_ARGS_LEVEL (tsubst_args, depth));
29888 /* Template parms for the constructor template. */
29889 tree ftparms = TREE_VALUE (tparms);
29890 unsigned flen = TREE_VEC_LENGTH (ftparms);
29891 /* Template parms for the class template. */
29892 tparms = TREE_CHAIN (tparms);
29893 tree ctparms = TREE_VALUE (tparms);
29894 unsigned clen = TREE_VEC_LENGTH (ctparms);
29895 /* Template parms for the deduction guide start as a copy of the
29896 template parms for the class. We set current_template_parms for
29897 lookup_template_class_1. */
29898 current_template_parms = tparms = copy_node (tparms);
29899 tree new_vec = TREE_VALUE (tparms) = make_tree_vec (flen + clen);
29900 for (unsigned i = 0; i < clen; ++i)
29901 TREE_VEC_ELT (new_vec, i) = TREE_VEC_ELT (ctparms, i);
29903 /* Now we need to rewrite the constructor parms to append them to the
29904 class parms. */
29905 for (unsigned i = 0; i < flen; ++i)
29907 unsigned index = i + clen;
29908 unsigned level = 1;
29909 tree oldelt = TREE_VEC_ELT (ftparms, i);
29910 tree newelt
29911 = rewrite_tparm_list (oldelt, index, level,
29912 tsubst_args, i, complain);
29913 if (newelt == error_mark_node)
29914 ok = false;
29915 TREE_VEC_ELT (new_vec, index) = newelt;
29918 /* Now we have a final set of template parms to substitute into the
29919 function signature. */
29920 targs = template_parms_to_args (tparms);
29921 fparms = tsubst_arg_types (fparms, tsubst_args, NULL_TREE,
29922 complain, ctor);
29923 if (fparms == error_mark_node)
29924 ok = false;
29925 if (ci)
29927 if (outer_args)
29928 /* FIXME: We'd like to avoid substituting outer template
29929 arguments into the constraint ahead of time, but the
29930 construction of tsubst_args assumes that outer arguments
29931 are already substituted in. */
29932 ci = tsubst_constraint_info (ci, outer_args, complain, ctor);
29933 ci = tsubst_constraint_info (ci, tsubst_args, complain, ctor);
29936 /* Parms are to have DECL_CHAIN tsubsted, which would be skipped if
29937 cp_unevaluated_operand. */
29938 cp_evaluated ev;
29939 fargs = tsubst (fargs, tsubst_args, complain, ctor);
29940 current_template_parms = save_parms;
29942 else
29944 /* Substitute in the same arguments to rewrite class members into
29945 references to members of an unknown specialization. */
29946 cp_evaluated ev;
29947 fparms = tsubst_arg_types (fparms, targs, NULL_TREE, complain, ctor);
29948 fargs = tsubst (fargs, targs, complain, ctor);
29949 if (ci)
29951 if (outer_args)
29952 /* FIXME: As above. */
29953 ci = tsubst_constraint_info (ci, outer_args, complain, ctor);
29954 ci = tsubst_constraint_info (ci, targs, complain, ctor);
29958 --processing_template_decl;
29959 if (!ok)
29960 return error_mark_node;
29963 if (!memtmpl)
29965 /* Copy the parms so we can set DECL_PRIMARY_TEMPLATE. */
29966 tparms = copy_node (tparms);
29967 INNERMOST_TEMPLATE_PARMS (tparms)
29968 = copy_node (INNERMOST_TEMPLATE_PARMS (tparms));
29971 tree fntype = build_function_type (type, fparms);
29972 tree ded_fn = build_lang_decl_loc (loc,
29973 FUNCTION_DECL,
29974 dguide_name (type), fntype);
29975 DECL_ARGUMENTS (ded_fn) = fargs;
29976 DECL_ARTIFICIAL (ded_fn) = true;
29977 DECL_NONCONVERTING_P (ded_fn) = explicit_p;
29978 tree ded_tmpl = build_template_decl (ded_fn, tparms, /*member*/false);
29979 DECL_ARTIFICIAL (ded_tmpl) = true;
29980 DECL_TEMPLATE_INFO (ded_fn) = build_template_info (ded_tmpl, targs);
29981 DECL_PRIMARY_TEMPLATE (ded_tmpl) = ded_tmpl;
29982 if (DECL_P (ctor))
29983 DECL_ABSTRACT_ORIGIN (ded_tmpl) = fn_tmpl;
29984 if (ci)
29985 set_constraints (ded_tmpl, ci);
29987 return ded_tmpl;
29990 /* Add to LIST the member types for the reshaped initializer CTOR. */
29992 static tree
29993 collect_ctor_idx_types (tree ctor, tree list, tree elt = NULL_TREE)
29995 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (ctor);
29996 tree idx, val; unsigned i;
29997 FOR_EACH_CONSTRUCTOR_ELT (v, i, idx, val)
29999 tree ftype = elt ? elt : TREE_TYPE (idx);
30000 if (BRACE_ENCLOSED_INITIALIZER_P (val)
30001 && CONSTRUCTOR_BRACES_ELIDED_P (val))
30003 tree subelt = NULL_TREE;
30004 if (TREE_CODE (ftype) == ARRAY_TYPE)
30005 subelt = TREE_TYPE (ftype);
30006 list = collect_ctor_idx_types (val, list, subelt);
30007 continue;
30009 tree arg = NULL_TREE;
30010 if (i == v->length() - 1
30011 && PACK_EXPANSION_P (ftype))
30012 /* Give the trailing pack expansion parameter a default argument to
30013 match aggregate initialization behavior, even if we deduce the
30014 length of the pack separately to more than we have initializers. */
30015 arg = build_constructor (init_list_type_node, NULL);
30016 /* if ei is of array type and xi is a braced-init-list or string literal,
30017 Ti is an rvalue reference to the declared type of ei */
30018 STRIP_ANY_LOCATION_WRAPPER (val);
30019 if (TREE_CODE (ftype) == ARRAY_TYPE
30020 && (BRACE_ENCLOSED_INITIALIZER_P (val)
30021 || TREE_CODE (val) == STRING_CST))
30023 if (TREE_CODE (val) == STRING_CST)
30024 ftype = cp_build_qualified_type
30025 (ftype, cp_type_quals (ftype) | TYPE_QUAL_CONST);
30026 ftype = (cp_build_reference_type
30027 (ftype, BRACE_ENCLOSED_INITIALIZER_P (val)));
30029 list = tree_cons (arg, ftype, list);
30032 return list;
30035 /* Return whether ETYPE is, or is derived from, a specialization of TMPL. */
30037 static bool
30038 is_spec_or_derived (tree etype, tree tmpl)
30040 if (!etype || !CLASS_TYPE_P (etype))
30041 return false;
30043 etype = cv_unqualified (etype);
30044 tree type = TREE_TYPE (tmpl);
30045 tree tparms = (INNERMOST_TEMPLATE_PARMS
30046 (DECL_TEMPLATE_PARMS (tmpl)));
30047 tree targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
30048 int err = unify (tparms, targs, type, etype,
30049 UNIFY_ALLOW_DERIVED, /*explain*/false);
30050 ggc_free (targs);
30051 return !err;
30054 /* Return a C++20 aggregate deduction candidate for TYPE initialized from
30055 INIT. */
30057 static tree
30058 maybe_aggr_guide (tree tmpl, tree init, vec<tree,va_gc> *args)
30060 if (cxx_dialect < cxx20)
30061 return NULL_TREE;
30063 if (init == NULL_TREE)
30064 return NULL_TREE;
30066 if (DECL_ALIAS_TEMPLATE_P (tmpl))
30068 tree under = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30069 tree tinfo = get_template_info (under);
30070 if (tree guide = maybe_aggr_guide (TI_TEMPLATE (tinfo), init, args))
30071 return alias_ctad_tweaks (tmpl, guide);
30072 return NULL_TREE;
30075 /* We might be creating a guide for a class member template, e.g.,
30077 template<typename U> struct A {
30078 template<typename T> struct B { T t; };
30081 At this point, A will have been instantiated. Below, we need to
30082 use both A<U>::B<T> (TEMPLATE_TYPE) and A<int>::B<T> (TYPE) types. */
30083 const bool member_template_p
30084 = (DECL_TEMPLATE_INFO (tmpl)
30085 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (tmpl)));
30086 tree type = TREE_TYPE (tmpl);
30087 tree template_type = (member_template_p
30088 ? TREE_TYPE (DECL_TI_TEMPLATE (tmpl))
30089 : type);
30090 if (!CP_AGGREGATE_TYPE_P (template_type))
30091 return NULL_TREE;
30093 /* No aggregate candidate for copy-initialization. */
30094 if (args->length() == 1)
30096 tree val = (*args)[0];
30097 if (is_spec_or_derived (TREE_TYPE (val), tmpl))
30098 return NULL_TREE;
30101 /* If we encounter a problem, we just won't add the candidate. */
30102 tsubst_flags_t complain = tf_none;
30104 tree parms = NULL_TREE;
30105 if (BRACE_ENCLOSED_INITIALIZER_P (init))
30107 init = reshape_init (template_type, init, complain);
30108 if (init == error_mark_node)
30109 return NULL_TREE;
30110 parms = collect_ctor_idx_types (init, parms);
30111 /* If we're creating a deduction guide for a member class template,
30112 we've used the original template pattern type for the reshape_init
30113 above; this is done because we want PARMS to be a template parameter
30114 type, something that can be deduced when used as a function template
30115 parameter. At this point the outer class template has already been
30116 partially instantiated (we deferred the deduction until the enclosing
30117 scope is non-dependent). Therefore we have to partially instantiate
30118 PARMS, so that its template level is properly reduced and we don't get
30119 mismatches when deducing types using the guide with PARMS. */
30120 if (member_template_p)
30122 ++processing_template_decl;
30123 parms = tsubst (parms, DECL_TI_ARGS (tmpl), complain, init);
30124 --processing_template_decl;
30127 else if (TREE_CODE (init) == TREE_LIST)
30129 int len = list_length (init);
30130 for (tree field = TYPE_FIELDS (type);
30131 len;
30132 --len, field = DECL_CHAIN (field))
30134 field = next_aggregate_field (field);
30135 if (!field)
30136 return NULL_TREE;
30137 tree ftype = finish_decltype_type (field, true, complain);
30138 parms = tree_cons (NULL_TREE, ftype, parms);
30141 else
30142 /* Aggregate initialization doesn't apply to an initializer expression. */
30143 return NULL_TREE;
30145 if (parms)
30147 tree last = parms;
30148 parms = nreverse (parms);
30149 TREE_CHAIN (last) = void_list_node;
30150 tree guide = build_deduction_guide (type, parms, NULL_TREE, complain);
30151 return guide;
30154 return NULL_TREE;
30157 /* UGUIDES are the deduction guides for the underlying template of alias
30158 template TMPL; adjust them to be deduction guides for TMPL.
30160 This routine also handles C++23 inherited CTAD, in which case TMPL is a
30161 TREE_LIST representing a synthetic alias template whose TREE_PURPOSE is
30162 the template parameter list of the alias template (equivalently, of the
30163 derived class) and TREE_VALUE the defining-type-id (equivalently, the
30164 base whose guides we're inheriting). UGUIDES are the base's guides. */
30166 static tree
30167 alias_ctad_tweaks (tree tmpl, tree uguides)
30169 /* [over.match.class.deduct]: When resolving a placeholder for a deduced
30170 class type (9.2.8.2) where the template-name names an alias template A,
30171 the defining-type-id of A must be of the form
30173 typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
30175 as specified in 9.2.8.2. The guides of A are the set of functions or
30176 function templates formed as follows. For each function or function
30177 template f in the guides of the template named by the simple-template-id
30178 of the defining-type-id, the template arguments of the return type of f
30179 are deduced from the defining-type-id of A according to the process in
30180 13.10.2.5 with the exception that deduction does not fail if not all
30181 template arguments are deduced. Let g denote the result of substituting
30182 these deductions into f. If substitution succeeds, form a function or
30183 function template f' with the following properties and add it to the set
30184 of guides of A:
30186 * The function type of f' is the function type of g.
30188 * If f is a function template, f' is a function template whose template
30189 parameter list consists of all the template parameters of A (including
30190 their default template arguments) that appear in the above deductions or
30191 (recursively) in their default template arguments, followed by the
30192 template parameters of f that were not deduced (including their default
30193 template arguments), otherwise f' is not a function template.
30195 * The associated constraints (13.5.2) are the conjunction of the
30196 associated constraints of g and a constraint that is satisfied if and only
30197 if the arguments of A are deducible (see below) from the return type.
30199 * If f is a copy deduction candidate (12.4.1.8), then f' is considered to
30200 be so as well.
30202 * If f was generated from a deduction-guide (12.4.1.8), then f' is
30203 considered to be so as well.
30205 * The explicit-specifier of f' is the explicit-specifier of g (if
30206 any). */
30208 enum { alias, inherited } ctad_kind;
30209 tree atype, fullatparms, utype;
30210 if (TREE_CODE (tmpl) == TEMPLATE_DECL)
30212 ctad_kind = alias;
30213 atype = TREE_TYPE (tmpl);
30214 fullatparms = DECL_TEMPLATE_PARMS (tmpl);
30215 utype = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30217 else
30219 ctad_kind = inherited;
30220 atype = NULL_TREE;
30221 fullatparms = TREE_PURPOSE (tmpl);
30222 utype = TREE_VALUE (tmpl);
30225 tsubst_flags_t complain = tf_warning_or_error;
30226 tree aguides = NULL_TREE;
30227 tree atparms = INNERMOST_TEMPLATE_PARMS (fullatparms);
30228 unsigned natparms = TREE_VEC_LENGTH (atparms);
30229 for (ovl_iterator iter (uguides); iter; ++iter)
30231 tree f = *iter;
30232 tree in_decl = f;
30233 location_t loc = DECL_SOURCE_LOCATION (f);
30234 tree ret = TREE_TYPE (TREE_TYPE (f));
30235 tree fprime = f;
30236 if (TREE_CODE (f) == TEMPLATE_DECL)
30238 processing_template_decl_sentinel ptds (/*reset*/false);
30239 ++processing_template_decl;
30241 /* Deduce template arguments for f from the type-id of A. */
30242 tree ftparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (f));
30243 unsigned len = TREE_VEC_LENGTH (ftparms);
30244 tree targs = make_tree_vec (len);
30245 int err = unify (ftparms, targs, ret, utype, UNIFY_ALLOW_NONE, false);
30246 if (err)
30247 /* CWG2664: Discard any deductions, still build the guide. */
30248 for (unsigned i = 0; i < len; ++i)
30249 TREE_VEC_ELT (targs, i) = NULL_TREE;
30251 /* The number of parms for f' is the number of parms of A used in
30252 the deduced arguments plus non-deduced parms of f. */
30253 unsigned ndlen = 0;
30254 unsigned j;
30255 for (unsigned i = 0; i < len; ++i)
30256 if (TREE_VEC_ELT (targs, i) == NULL_TREE)
30257 ++ndlen;
30258 find_template_parameter_info ftpi (fullatparms);
30259 ftpi.find_in_recursive (targs);
30260 unsigned nusedatparms = ftpi.num_found ();
30261 unsigned nfparms = nusedatparms + ndlen;
30262 tree gtparms = make_tree_vec (nfparms);
30264 /* Set current_template_parms as in build_deduction_guide. */
30265 auto ctp = make_temp_override (current_template_parms);
30266 current_template_parms = copy_node (fullatparms);
30267 TREE_VALUE (current_template_parms) = gtparms;
30269 j = 0;
30270 unsigned level = 1;
30272 /* First copy over the used parms of A. */
30273 tree atargs = make_tree_vec (natparms);
30274 for (unsigned i = 0; i < natparms; ++i)
30276 tree elt = TREE_VEC_ELT (atparms, i);
30277 if (ftpi.found (elt))
30279 unsigned index = j++;
30280 tree nelt = rewrite_tparm_list (elt, index, level,
30281 atargs, i, complain);
30282 TREE_VEC_ELT (gtparms, index) = nelt;
30285 gcc_checking_assert (j == nusedatparms);
30287 /* Adjust the deduced template args for f to refer to the A parms
30288 with their new indexes. */
30289 if (nusedatparms && nusedatparms != natparms)
30290 targs = tsubst_template_args (targs, atargs, complain, in_decl);
30292 /* Now rewrite the non-deduced parms of f. */
30293 for (unsigned i = 0; ndlen && i < len; ++i)
30294 if (TREE_VEC_ELT (targs, i) == NULL_TREE)
30296 --ndlen;
30297 unsigned index = j++;
30298 tree oldlist = TREE_VEC_ELT (ftparms, i);
30299 tree list = rewrite_tparm_list (oldlist, index, level,
30300 targs, i, complain);
30301 TREE_VEC_ELT (gtparms, index) = list;
30303 gtparms = build_tree_list (size_one_node, gtparms);
30305 /* Substitute the deduced arguments plus the rewritten template
30306 parameters into f to get g. This covers the type, copyness,
30307 guideness, and explicit-specifier. */
30308 tree g;
30310 /* Parms are to have DECL_CHAIN tsubsted, which would be skipped
30311 if cp_unevaluated_operand. */
30312 cp_evaluated ev;
30313 g = tsubst_decl (DECL_TEMPLATE_RESULT (f), targs, complain,
30314 /*use_spec_table=*/false);
30316 if (g == error_mark_node)
30317 continue;
30318 if (nfparms == 0)
30320 /* The targs are all non-dependent, so g isn't a template. */
30321 fprime = g;
30322 ret = TREE_TYPE (TREE_TYPE (fprime));
30323 goto non_template;
30325 DECL_USE_TEMPLATE (g) = 0;
30326 fprime = build_template_decl (g, gtparms, false);
30327 DECL_TEMPLATE_RESULT (fprime) = g;
30328 TREE_TYPE (fprime) = TREE_TYPE (g);
30329 tree gtargs = template_parms_to_args (gtparms);
30330 DECL_TEMPLATE_INFO (g) = build_template_info (fprime, gtargs);
30331 DECL_PRIMARY_TEMPLATE (fprime) = fprime;
30333 /* Substitute the associated constraints. */
30334 tree ci = get_constraints (f);
30335 if (ci)
30336 ci = tsubst_constraint_info (ci, targs, complain, in_decl);
30337 if (ci == error_mark_node)
30338 continue;
30340 /* Add a constraint that the return type matches the instantiation of
30341 A with the same template arguments. */
30342 ret = TREE_TYPE (TREE_TYPE (fprime));
30343 if (ctad_kind == alias
30344 && (!same_type_p (atype, ret)
30345 /* FIXME this should mean they don't compare as equivalent. */
30346 || dependent_alias_template_spec_p (atype, nt_opaque)))
30348 tree same = finish_trait_expr (loc, CPTK_IS_DEDUCIBLE, tmpl, ret);
30349 ci = append_constraint (ci, same);
30352 if (ci)
30354 remove_constraints (fprime);
30355 set_constraints (fprime, ci);
30358 else
30360 /* For a non-template deduction guide, if the arguments of A aren't
30361 deducible from the return type, don't add the candidate. */
30362 non_template:
30363 if (ctad_kind == alias
30364 && !type_targs_deducible_from (tmpl, ret))
30365 continue;
30368 /* Rewrite the return type of the inherited guide in terms of the
30369 derived class. This is specified as replacing the return type R
30370 with typename CC<R>::type where the partially specialized CC maps a
30371 base class specialization to a specialization of the derived class
30372 having such a base (inducing substitution failure if no such derived
30373 class exists).
30375 As specified this mapping would be done at instantiation time using
30376 non-dependent template arguments, but we do it ahead of time using
30377 the generic arguments. This seems to be good enough since generic
30378 deduction should succeed only if concrete deduction would. */
30379 if (ctad_kind == inherited)
30381 processing_template_decl_sentinel ptds (/*reset*/false);
30382 if (TREE_CODE (fprime) == TEMPLATE_DECL)
30383 ++processing_template_decl;
30385 tree targs = type_targs_deducible_from (tmpl, ret);
30386 if (!targs)
30387 continue;
30389 if (TREE_CODE (f) != TEMPLATE_DECL)
30390 fprime = copy_decl (fprime);
30391 tree fntype = TREE_TYPE (fprime);
30392 ret = lookup_template_class (TPARMS_PRIMARY_TEMPLATE (atparms), targs,
30393 in_decl, NULL_TREE, false, complain);
30394 fntype = build_function_type (ret, TYPE_ARG_TYPES (fntype));
30395 TREE_TYPE (fprime) = fntype;
30396 if (TREE_CODE (fprime) == TEMPLATE_DECL)
30397 TREE_TYPE (DECL_TEMPLATE_RESULT (fprime)) = fntype;
30400 aguides = lookup_add (fprime, aguides);
30403 return aguides;
30406 /* CTOR is a using-decl inheriting the constructors of some base of the class
30407 template TMPL; adjust the base's guides be deduction guides for TMPL. */
30409 static tree
30410 inherited_ctad_tweaks (tree tmpl, tree ctor, tsubst_flags_t complain)
30412 /* [over.match.class.deduct]: In addition, if C is defined and inherits
30413 constructors ([namespace.udecl]) from a direct base class denoted in the
30414 base-specifier-list by a class-or-decltype B, let A be an alias template
30415 whose template parameter list is that of C and whose defining-type-id is
30416 B. If A is a deducible template ([dcl.type.simple]), the set contains the
30417 guides of A with the return type R of each guide replaced with typename
30418 CC::type given a class template
30420 template <typename> class CC;
30422 whose primary template is not defined and with a single partial
30423 specialization whose template parameter list is that of A and whose
30424 template argument list is a specialization of A with the template argument
30425 list of A ([temp.dep.type]) having a member typedef type designating a
30426 template specialization with the template argument list of A but with C as
30427 the template. */
30429 /* FIXME: Also recognize inherited constructors of the form 'using C::B::B',
30430 which seem to be represented with TYPENAME_TYPE C::B as USING_DECL_SCOPE?
30431 And recognize constructors inherited from a non-dependent base class, which
30432 seem to be missing from the overload set entirely? */
30433 tree scope = USING_DECL_SCOPE (ctor);
30434 if (!CLASS_TYPE_P (scope)
30435 || !CLASSTYPE_TEMPLATE_INFO (scope)
30436 || !PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (scope)))
30437 return NULL_TREE;
30439 tree t = build_tree_list (DECL_TEMPLATE_PARMS (tmpl), scope);
30440 bool any_dguides_p;
30441 tree uguides = deduction_guides_for (CLASSTYPE_TI_TEMPLATE (scope),
30442 any_dguides_p, complain);
30443 return alias_ctad_tweaks (t, uguides);
30446 /* If template arguments for TMPL can be deduced from TYPE, return
30447 the deduced arguments, otherwise return NULL_TREE.
30448 Used to implement CPTK_IS_DEDUCIBLE for alias CTAD according to
30449 [over.match.class.deduct].
30451 This check is specified in terms of partial specialization, so the behavior
30452 should be parallel to that of get_partial_spec_bindings. */
30454 tree
30455 type_targs_deducible_from (tree tmpl, tree type)
30457 tree tparms, ttype;
30458 if (TREE_CODE (tmpl) == TEMPLATE_DECL)
30460 /* If tmpl is a class template, this is trivial: it's deducible if
30461 TYPE is a specialization of TMPL. */
30462 if (DECL_CLASS_TEMPLATE_P (tmpl))
30464 if (CLASS_TYPE_P (type)
30465 && CLASSTYPE_TEMPLATE_INFO (type)
30466 && CLASSTYPE_TI_TEMPLATE (type) == tmpl)
30467 return INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
30468 else
30469 return NULL_TREE;
30472 /* Otherwise it's an alias template. */
30473 tparms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
30474 ttype = TREE_TYPE (tmpl);
30476 else
30478 /* TMPL is a synthetic alias template represented as a TREE_LIST as
30479 per alias_ctad_tweaks. */
30480 tparms = INNERMOST_TEMPLATE_PARMS (TREE_PURPOSE (tmpl));
30481 ttype = TREE_VALUE (tmpl);
30482 tmpl = TI_TEMPLATE (TYPE_TEMPLATE_INFO_MAYBE_ALIAS (ttype));
30485 int len = TREE_VEC_LENGTH (tparms);
30486 tree targs = make_tree_vec (len);
30487 bool tried_array_deduction = (cxx_dialect < cxx17);
30489 again:
30490 if (unify (tparms, targs, ttype, type,
30491 UNIFY_ALLOW_NONE, false))
30492 return NULL_TREE;
30494 /* We don't fail on an undeduced targ the second time through (like
30495 get_partial_spec_bindings) because we're going to try defaults. */
30496 for (int i = 0; i < len; ++i)
30497 if (! TREE_VEC_ELT (targs, i))
30499 tree tparm = TREE_VEC_ELT (tparms, i);
30500 tparm = TREE_VALUE (tparm);
30502 if (!tried_array_deduction
30503 && TREE_CODE (tparm) == TYPE_DECL)
30505 try_array_deduction (tparms, targs, ttype);
30506 tried_array_deduction = true;
30507 if (TREE_VEC_ELT (targs, i))
30508 goto again;
30510 /* If the type parameter is a parameter pack, then it will be deduced
30511 to an empty parameter pack. This is another case that doesn't model
30512 well as partial specialization. */
30513 if (template_parameter_pack_p (tparm))
30515 tree arg;
30516 if (TREE_CODE (tparm) == PARM_DECL)
30518 arg = make_node (NONTYPE_ARGUMENT_PACK);
30519 TREE_CONSTANT (arg) = 1;
30521 else
30522 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
30523 ARGUMENT_PACK_ARGS (arg) = make_tree_vec (0);
30524 TREE_VEC_ELT (targs, i) = arg;
30528 /* Maybe add in default template args. This seems like a flaw in the
30529 specification in terms of partial specialization, since it says the
30530 partial specialization has the the template parameter list of A, but a
30531 partial specialization can't have default targs. */
30532 targs = coerce_template_parms (tparms, targs, tmpl, tf_none);
30533 if (targs == error_mark_node)
30534 return NULL_TREE;
30536 /* I believe we don't need the template_template_parm_bindings_ok_p call
30537 because coerce_template_parms did coerce_template_template_parms. */
30539 if (!constraints_satisfied_p (tmpl, targs))
30540 return NULL_TREE;
30542 return targs;
30545 /* Return artificial deduction guides built from the constructors of class
30546 template TMPL. */
30548 static tree
30549 ctor_deduction_guides_for (tree tmpl, tsubst_flags_t complain)
30551 tree outer_args = outer_template_args (tmpl);
30552 tree type = TREE_TYPE (most_general_template (tmpl));
30554 tree cands = NULL_TREE;
30556 for (ovl_iterator iter (CLASSTYPE_CONSTRUCTORS (type)); iter; ++iter)
30558 /* We handle C++23 inherited CTAD below. */
30559 if (iter.using_p ())
30560 continue;
30562 tree guide = build_deduction_guide (type, *iter, outer_args, complain);
30563 cands = lookup_add (guide, cands);
30566 if (cxx_dialect >= cxx23)
30567 for (tree ctor : ovl_range (CLASSTYPE_CONSTRUCTORS (type)))
30568 if (TREE_CODE (ctor) == USING_DECL)
30570 tree uguides = inherited_ctad_tweaks (tmpl, ctor, complain);
30571 if (uguides)
30572 cands = lookup_add (uguides, cands);
30575 /* Add implicit default constructor deduction guide. */
30576 if (!TYPE_HAS_USER_CONSTRUCTOR (type))
30578 tree guide = build_deduction_guide (type, type, outer_args,
30579 complain);
30580 cands = lookup_add (guide, cands);
30583 /* Add copy guide. */
30585 tree gtype = build_reference_type (type);
30586 tree guide = build_deduction_guide (type, gtype, outer_args,
30587 complain);
30588 cands = lookup_add (guide, cands);
30591 return cands;
30594 static GTY((deletable)) hash_map<tree, tree_pair_p> *dguide_cache;
30596 /* Return the non-aggregate deduction guides for deducible template TMPL. The
30597 aggregate candidate is added separately because it depends on the
30598 initializer. Set ANY_DGUIDES_P if we find a non-implicit deduction
30599 guide. */
30601 static tree
30602 deduction_guides_for (tree tmpl, bool &any_dguides_p, tsubst_flags_t complain)
30604 tree guides = NULL_TREE;
30605 if (DECL_ALIAS_TEMPLATE_P (tmpl))
30607 tree under = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30608 tree tinfo = get_template_info (under);
30609 guides = deduction_guides_for (TI_TEMPLATE (tinfo), any_dguides_p,
30610 complain);
30612 else
30614 guides = lookup_qualified_name (CP_DECL_CONTEXT (tmpl),
30615 dguide_name (tmpl),
30616 LOOK_want::NORMAL, /*complain*/false);
30617 if (guides == error_mark_node)
30618 guides = NULL_TREE;
30619 else
30620 any_dguides_p = true;
30623 /* Cache the deduction guides for a template. We also remember the result of
30624 lookup, and rebuild everything if it changes; should be very rare. */
30625 /* FIXME: Also rebuild if this is a class template that inherits guides from a
30626 base class, and lookup for the latter changed. */
30627 tree_pair_p cache = NULL;
30628 if (tree_pair_p &r
30629 = hash_map_safe_get_or_insert<hm_ggc> (dguide_cache, tmpl))
30631 cache = r;
30632 if (cache->purpose == guides)
30633 return cache->value;
30635 else
30637 r = cache = ggc_cleared_alloc<tree_pair_s> ();
30638 cache->purpose = guides;
30641 tree cands = NULL_TREE;
30642 if (DECL_ALIAS_TEMPLATE_P (tmpl))
30643 cands = alias_ctad_tweaks (tmpl, guides);
30644 else
30646 cands = ctor_deduction_guides_for (tmpl, complain);
30647 for (ovl_iterator it (guides); it; ++it)
30648 cands = lookup_add (*it, cands);
30651 cache->value = cands;
30652 return cands;
30655 /* Return whether TMPL is a (class template argument-) deducible template. */
30657 bool
30658 ctad_template_p (tree tmpl)
30660 /* A deducible template is either a class template or is an alias template
30661 whose defining-type-id is of the form
30663 typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
30665 where the nested-name-specifier (if any) is non-dependent and the
30666 template-name of the simple-template-id names a deducible template. */
30668 if (DECL_CLASS_TEMPLATE_P (tmpl)
30669 || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
30670 return true;
30671 if (!DECL_ALIAS_TEMPLATE_P (tmpl))
30672 return false;
30673 tree orig = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30674 if (tree tinfo = get_template_info (orig))
30675 return ctad_template_p (TI_TEMPLATE (tinfo));
30676 return false;
30679 /* Deduce template arguments for the class template placeholder PTYPE for
30680 template TMPL based on the initializer INIT, and return the resulting
30681 type. */
30683 static tree
30684 do_class_deduction (tree ptype, tree tmpl, tree init,
30685 int flags, tsubst_flags_t complain)
30687 /* We should have handled this in the caller. */
30688 if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
30689 return ptype;
30691 /* If the class was erroneous, don't try to deduce, because that
30692 can generate a lot of diagnostic. */
30693 if (TREE_TYPE (tmpl)
30694 && TYPE_LANG_SPECIFIC (TREE_TYPE (tmpl))
30695 && CLASSTYPE_ERRONEOUS (TREE_TYPE (tmpl)))
30696 return ptype;
30698 /* Wait until the enclosing scope is non-dependent. */
30699 if (DECL_CLASS_SCOPE_P (tmpl)
30700 && dependent_type_p (DECL_CONTEXT (tmpl)))
30701 return ptype;
30703 /* Initializing one placeholder from another. */
30704 if (init
30705 && (TREE_CODE (init) == TEMPLATE_PARM_INDEX
30706 || (TREE_CODE (init) == EXPR_PACK_EXPANSION
30707 && (TREE_CODE (PACK_EXPANSION_PATTERN (init))
30708 == TEMPLATE_PARM_INDEX)))
30709 && is_auto (TREE_TYPE (init))
30710 && CLASS_PLACEHOLDER_TEMPLATE (TREE_TYPE (init)) == tmpl)
30711 return cp_build_qualified_type (TREE_TYPE (init), cp_type_quals (ptype));
30713 if (!ctad_template_p (tmpl))
30715 if (complain & tf_error)
30716 error ("non-deducible template %qT used without template arguments", tmpl);
30717 return error_mark_node;
30719 else if (cxx_dialect < cxx20 && DECL_ALIAS_TEMPLATE_P (tmpl))
30721 if (complain & tf_error)
30723 /* Be permissive with equivalent alias templates. */
30724 tree u = get_underlying_template (tmpl);
30725 diagnostic_t dk = (u == tmpl) ? DK_ERROR : DK_PEDWARN;
30726 bool complained
30727 = emit_diagnostic (dk, input_location, 0,
30728 "alias template deduction only available "
30729 "with %<-std=c++20%> or %<-std=gnu++20%>");
30730 if (u == tmpl)
30731 return error_mark_node;
30732 else if (complained)
30734 inform (input_location, "use %qD directly instead", u);
30735 tmpl = u;
30738 else
30739 return error_mark_node;
30742 /* Wait until the initializer is non-dependent. */
30743 if (type_dependent_expression_p (init))
30744 return ptype;
30746 /* Don't bother with the alias rules for an equivalent template. */
30747 tmpl = get_underlying_template (tmpl);
30749 tree type = TREE_TYPE (tmpl);
30751 bool try_list_cand = false;
30752 bool list_init_p = false;
30754 releasing_vec rv_args = NULL;
30755 vec<tree,va_gc> *&args = *&rv_args;
30756 if (init == NULL_TREE)
30757 args = make_tree_vector ();
30758 else if (BRACE_ENCLOSED_INITIALIZER_P (init))
30760 list_init_p = true;
30761 try_list_cand = true;
30762 if (CONSTRUCTOR_NELTS (init) == 1
30763 && !CONSTRUCTOR_IS_DESIGNATED_INIT (init))
30765 /* As an exception, the first phase in 16.3.1.7 (considering the
30766 initializer list as a single argument) is omitted if the
30767 initializer list consists of a single expression of type cv U,
30768 where U is a specialization of C or a class derived from a
30769 specialization of C. */
30770 tree elt = CONSTRUCTOR_ELT (init, 0)->value;
30771 if (is_spec_or_derived (TREE_TYPE (elt), tmpl))
30772 try_list_cand = false;
30774 if (try_list_cand || is_std_init_list (type))
30775 args = make_tree_vector_single (init);
30776 else
30777 args = make_tree_vector_from_ctor (init);
30779 else if (TREE_CODE (init) == TREE_LIST)
30780 args = make_tree_vector_from_list (init);
30781 else
30782 args = make_tree_vector_single (init);
30784 /* Do this now to avoid problems with erroneous args later on. */
30785 args = resolve_args (args, complain);
30786 if (args == NULL)
30787 return error_mark_node;
30789 bool any_dguides_p = false;
30790 tree cands = deduction_guides_for (tmpl, any_dguides_p, complain);
30791 if (cands == error_mark_node)
30792 return error_mark_node;
30794 /* Prune explicit deduction guides in copy-initialization context (but
30795 not copy-list-initialization). */
30796 bool elided = false;
30797 if (!list_init_p && (flags & LOOKUP_ONLYCONVERTING))
30799 for (lkp_iterator iter (cands); !elided && iter; ++iter)
30800 if (DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
30801 elided = true;
30803 if (elided)
30805 /* Found a nonconverting guide, prune the candidates. */
30806 tree pruned = NULL_TREE;
30807 for (lkp_iterator iter (cands); iter; ++iter)
30808 if (!DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
30809 pruned = lookup_add (*iter, pruned);
30811 cands = pruned;
30815 if (!any_dguides_p)
30816 if (tree guide = maybe_aggr_guide (tmpl, init, args))
30817 cands = lookup_add (guide, cands);
30819 tree fndecl = error_mark_node;
30821 /* If this is list-initialization and the class has a list guide, first
30822 try deducing from the list as a single argument, as [over.match.list]. */
30823 if (try_list_cand)
30825 tree list_cands = NULL_TREE;
30826 for (tree dg : lkp_range (cands))
30827 if (is_list_ctor (dg))
30828 list_cands = lookup_add (dg, list_cands);
30829 if (list_cands)
30830 fndecl = perform_dguide_overload_resolution (list_cands, args, tf_none);
30831 if (fndecl == error_mark_node)
30833 /* That didn't work, now try treating the list as a sequence of
30834 arguments. */
30835 release_tree_vector (args);
30836 args = make_tree_vector_from_ctor (init);
30837 args = resolve_args (args, complain);
30838 if (args == NULL)
30839 return error_mark_node;
30843 if (elided && !cands)
30845 error ("cannot deduce template arguments for copy-initialization"
30846 " of %qT, as it has no non-explicit deduction guides or "
30847 "user-declared constructors", type);
30848 return error_mark_node;
30850 else if (!cands && fndecl == error_mark_node)
30852 error ("cannot deduce template arguments of %qT, as it has no viable "
30853 "deduction guides", type);
30854 return error_mark_node;
30857 if (fndecl == error_mark_node)
30858 fndecl = perform_dguide_overload_resolution (cands, args, tf_none);
30860 if (fndecl == error_mark_node)
30862 if (complain & tf_warning_or_error)
30864 error ("class template argument deduction failed:");
30865 perform_dguide_overload_resolution (cands, args, complain);
30866 if (elided)
30867 inform (input_location, "explicit deduction guides not considered "
30868 "for copy-initialization");
30870 return error_mark_node;
30872 /* [over.match.list]/1: In copy-list-initialization, if an explicit
30873 constructor is chosen, the initialization is ill-formed. */
30874 else if (flags & LOOKUP_ONLYCONVERTING)
30876 if (DECL_NONCONVERTING_P (fndecl))
30878 if (complain & tf_warning_or_error)
30880 // TODO: Pass down location from cp_finish_decl.
30881 error ("class template argument deduction for %qT failed: "
30882 "explicit deduction guide selected in "
30883 "copy-list-initialization", type);
30884 inform (DECL_SOURCE_LOCATION (fndecl),
30885 "explicit deduction guide declared here");
30888 return error_mark_node;
30892 /* If CTAD succeeded but the type doesn't have any explicit deduction
30893 guides, this deduction might not be what the user intended. */
30894 if (fndecl != error_mark_node && !any_dguides_p && (complain & tf_warning))
30896 if ((!DECL_IN_SYSTEM_HEADER (fndecl)
30897 || global_dc->m_warn_system_headers)
30898 && warning (OPT_Wctad_maybe_unsupported,
30899 "%qT may not intend to support class template argument "
30900 "deduction", type))
30901 inform (input_location, "add a deduction guide to suppress this "
30902 "warning");
30905 return cp_build_qualified_type (TREE_TYPE (TREE_TYPE (fndecl)),
30906 cp_type_quals (ptype));
30909 /* Return true if INIT is an unparenthesized id-expression or an
30910 unparenthesized class member access. Used for the argument of
30911 decltype(auto). */
30913 bool
30914 unparenthesized_id_or_class_member_access_p (tree init)
30916 STRIP_ANY_LOCATION_WRAPPER (init);
30918 /* We need to be able to tell '(r)' and 'r' apart (when it's of
30919 reference type). Only the latter is an id-expression. */
30920 if (REFERENCE_REF_P (init)
30921 && !REF_PARENTHESIZED_P (init))
30922 init = TREE_OPERAND (init, 0);
30923 return (DECL_P (init)
30924 || ((TREE_CODE (init) == COMPONENT_REF
30925 || TREE_CODE (init) == SCOPE_REF)
30926 && !REF_PARENTHESIZED_P (init)));
30929 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
30930 from INIT. AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.
30931 The CONTEXT determines the context in which auto deduction is performed
30932 and is used to control error diagnostics. FLAGS are the LOOKUP_* flags.
30934 OUTER_TARGS is used during template argument deduction (context == adc_unify)
30935 to properly substitute the result. It's also used in the adc_unify and
30936 adc_requirement contexts to communicate the necessary template arguments
30937 to satisfaction. OUTER_TARGS is ignored in other contexts.
30939 Additionally for adc_unify contexts TMPL is the template for which TYPE
30940 is a template parameter type.
30942 For partial-concept-ids, extra args from OUTER_TARGS, TMPL and the current
30943 scope may be appended to the list of deduced template arguments prior to
30944 determining constraint satisfaction as appropriate. */
30946 tree
30947 do_auto_deduction (tree type, tree init, tree auto_node,
30948 tsubst_flags_t complain /* = tf_warning_or_error */,
30949 auto_deduction_context context /* = adc_unspecified */,
30950 tree outer_targs /* = NULL_TREE */,
30951 int flags /* = LOOKUP_NORMAL */,
30952 tree tmpl /* = NULL_TREE */)
30954 if (type == error_mark_node || init == error_mark_node)
30955 return error_mark_node;
30957 if (init && type_dependent_expression_p (init)
30958 && context != adc_unify)
30959 /* Defining a subset of type-dependent expressions that we can deduce
30960 from ahead of time isn't worth the trouble. */
30961 return type;
30963 /* Similarly, we can't deduce from another undeduced decl. */
30964 if (init && undeduced_auto_decl (init))
30965 return type;
30967 /* We may be doing a partial substitution, but we still want to replace
30968 auto_node. */
30969 complain &= ~tf_partial;
30971 if (init && BRACE_ENCLOSED_INITIALIZER_P (init))
30973 /* We don't recurse here because we can't deduce from a nested
30974 initializer_list. */
30975 if (CONSTRUCTOR_ELTS (init))
30976 for (constructor_elt &elt : CONSTRUCTOR_ELTS (init))
30977 elt.value = resolve_nondeduced_context (elt.value, complain);
30979 else if (init)
30980 init = resolve_nondeduced_context (init, complain);
30982 /* In C++23, we must deduce the type to int&& for code like
30983 decltype(auto) f(int&& x) { return (x); }
30985 auto&& f(int x) { return x; }
30986 so we use treat_lvalue_as_rvalue_p. But don't do it for
30987 decltype(auto) f(int x) { return x; }
30988 where we should deduce 'int' rather than 'int&&'; transmogrifying
30989 INIT to an rvalue would break that. */
30990 tree r;
30991 if (cxx_dialect >= cxx23
30992 && context == adc_return_type
30993 && (!AUTO_IS_DECLTYPE (auto_node)
30994 || !unparenthesized_id_or_class_member_access_p (init))
30995 && (r = treat_lvalue_as_rvalue_p (maybe_undo_parenthesized_ref (init),
30996 /*return*/true)))
30997 init = r;
30999 if (tree ctmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node))
31000 /* C++17 class template argument deduction. */
31001 return do_class_deduction (type, ctmpl, init, flags, complain);
31003 if (init == NULL_TREE || TREE_TYPE (init) == NULL_TREE)
31004 /* Nothing we can do with this, even in deduction context. */
31005 return type;
31007 location_t loc = cp_expr_loc_or_input_loc (init);
31009 /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
31010 with either a new invented type template parameter U or, if the
31011 initializer is a braced-init-list (8.5.4), with
31012 std::initializer_list<U>. */
31013 if (BRACE_ENCLOSED_INITIALIZER_P (init))
31015 if (!DIRECT_LIST_INIT_P (init))
31016 type = listify_autos (type, auto_node);
31017 else if (CONSTRUCTOR_NELTS (init) == 1)
31018 init = CONSTRUCTOR_ELT (init, 0)->value;
31019 else
31021 if (complain & tf_warning_or_error)
31023 if (permerror (loc, "direct-list-initialization of "
31024 "%<auto%> requires exactly one element"))
31025 inform (loc,
31026 "for deduction to %<std::initializer_list%>, use copy-"
31027 "list-initialization (i.e. add %<=%> before the %<{%>)");
31029 type = listify_autos (type, auto_node);
31033 if (type == error_mark_node || init == error_mark_node)
31034 return error_mark_node;
31036 tree targs;
31037 if (context == adc_decomp_type
31038 && auto_node == type
31039 && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
31041 /* [dcl.struct.bind]/1 - if decomposition declaration has no ref-qualifiers
31042 and initializer has array type, deduce cv-qualified array type. */
31043 targs = make_tree_vec (1);
31044 TREE_VEC_ELT (targs, 0) = TREE_TYPE (init);
31046 else if (AUTO_IS_DECLTYPE (auto_node))
31048 const bool id = unparenthesized_id_or_class_member_access_p (init);
31049 tree deduced = finish_decltype_type (init, id, complain);
31050 deduced = canonicalize_type_argument (deduced, complain);
31051 if (deduced == error_mark_node)
31052 return error_mark_node;
31053 targs = make_tree_vec (1);
31054 TREE_VEC_ELT (targs, 0) = deduced;
31056 else
31058 if (error_operand_p (init))
31059 return error_mark_node;
31061 tree parms = build_tree_list (NULL_TREE, type);
31062 tree tparms;
31064 if (flag_concepts_ts)
31065 tparms = extract_autos (type);
31066 else
31068 tparms = make_tree_vec (1);
31069 TREE_VEC_ELT (tparms, 0)
31070 = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
31073 targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
31074 int val = type_unification_real (tparms, targs, parms, &init, 1, 0,
31075 DEDUCE_CALL,
31076 NULL, /*explain_p=*/false);
31077 if (val > 0)
31079 if (processing_template_decl)
31080 /* Try again at instantiation time. */
31081 return type;
31082 if (type && type != error_mark_node
31083 && (complain & tf_error))
31084 /* If type is error_mark_node a diagnostic must have been
31085 emitted by now. Also, having a mention to '<type error>'
31086 in the diagnostic is not really useful to the user. */
31088 if (cfun
31089 && FNDECL_USED_AUTO (current_function_decl)
31090 && (auto_node
31091 == DECL_SAVED_AUTO_RETURN_TYPE (current_function_decl))
31092 && LAMBDA_FUNCTION_P (current_function_decl))
31093 error_at (loc, "unable to deduce lambda return type from %qE",
31094 init);
31095 else
31096 error_at (loc, "unable to deduce %qT from %qE", type, init);
31097 type_unification_real (tparms, targs, parms, &init, 1, 0,
31098 DEDUCE_CALL,
31099 NULL, /*explain_p=*/true);
31101 return error_mark_node;
31105 /* Check any placeholder constraints against the deduced type. */
31106 if (processing_template_decl && context == adc_unify)
31107 /* Constraints will be checked after deduction. */;
31108 else if (tree constr = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (auto_node)))
31110 if (processing_template_decl)
31112 gcc_checking_assert (context == adc_variable_type
31113 || context == adc_return_type
31114 || context == adc_decomp_type);
31115 gcc_checking_assert (!type_dependent_expression_p (init));
31116 /* If the constraint is dependent, we need to wait until
31117 instantiation time to resolve the placeholder. */
31118 if (placeholder_type_constraint_dependent_p (constr))
31119 return type;
31122 if (context == adc_return_type
31123 || context == adc_variable_type
31124 || context == adc_decomp_type)
31125 if (tree fn = current_function_decl)
31126 if (DECL_TEMPLATE_INFO (fn) || LAMBDA_FUNCTION_P (fn))
31128 outer_targs = DECL_TEMPLATE_INFO (fn)
31129 ? DECL_TI_ARGS (fn) : NULL_TREE;
31130 if (LAMBDA_FUNCTION_P (fn))
31132 /* As in satisfy_declaration_constraints. */
31133 tree regen_args = lambda_regenerating_args (fn);
31134 if (outer_targs)
31135 outer_targs = add_to_template_args (regen_args, outer_targs);
31136 else
31137 outer_targs = regen_args;
31141 tree full_targs = outer_targs;
31142 if (context == adc_unify && tmpl)
31143 full_targs = add_outermost_template_args (tmpl, full_targs);
31144 full_targs = add_to_template_args (full_targs, targs);
31146 /* HACK: Compensate for callers not always communicating all levels of
31147 outer template arguments by filling in the outermost missing levels
31148 with dummy levels before checking satisfaction. We'll still crash
31149 if the constraint depends on a template argument belonging to one of
31150 these missing levels, but this hack otherwise allows us to handle a
31151 large subset of possible constraints (including all non-dependent
31152 constraints). */
31153 if (int missing_levels = (TEMPLATE_TYPE_ORIG_LEVEL (auto_node)
31154 - TMPL_ARGS_DEPTH (full_targs)))
31156 tree dummy_levels = make_tree_vec (missing_levels);
31157 for (int i = 0; i < missing_levels; ++i)
31158 TREE_VEC_ELT (dummy_levels, i) = make_tree_vec (0);
31159 full_targs = add_to_template_args (dummy_levels, full_targs);
31162 if (!constraints_satisfied_p (auto_node, full_targs))
31164 if (complain & tf_warning_or_error)
31166 auto_diagnostic_group d;
31167 switch (context)
31169 case adc_unspecified:
31170 case adc_unify:
31171 error_at (loc, "placeholder constraints not satisfied");
31172 break;
31173 case adc_variable_type:
31174 case adc_decomp_type:
31175 error_at (loc, "deduced initializer does not satisfy "
31176 "placeholder constraints");
31177 break;
31178 case adc_return_type:
31179 error_at (loc, "deduced return type does not satisfy "
31180 "placeholder constraints");
31181 break;
31182 case adc_requirement:
31183 error_at (loc, "deduced expression type does not satisfy "
31184 "placeholder constraints");
31185 break;
31187 diagnose_constraints (loc, auto_node, full_targs);
31189 return error_mark_node;
31193 if (TEMPLATE_TYPE_LEVEL (auto_node) == 1)
31194 /* The outer template arguments are already substituted into type
31195 (but we still may have used them for constraint checking above). */;
31196 else if (context == adc_unify)
31197 targs = add_to_template_args (outer_targs, targs);
31198 else if (processing_template_decl)
31199 targs = add_to_template_args (current_template_args (), targs);
31200 return tsubst (type, targs, complain, NULL_TREE);
31203 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
31204 result. */
31206 tree
31207 splice_late_return_type (tree type, tree late_return_type)
31209 if (late_return_type)
31211 gcc_assert (is_auto (type) || seen_error ());
31212 return late_return_type;
31215 if (tree auto_node = find_type_usage (type, is_auto))
31216 if (TEMPLATE_TYPE_LEVEL (auto_node) <= current_template_depth)
31218 /* In an abbreviated function template we didn't know we were dealing
31219 with a function template when we saw the auto return type, so rebuild
31220 the return type using an auto with the correct level. */
31221 tree new_auto = make_auto_1 (TYPE_IDENTIFIER (auto_node), false);
31222 tree auto_vec = make_tree_vec (1);
31223 TREE_VEC_ELT (auto_vec, 0) = new_auto;
31224 tree targs = add_outermost_template_args (current_template_args (),
31225 auto_vec);
31226 /* Also rebuild the constraint info in terms of the new auto. */
31227 if (tree ci = PLACEHOLDER_TYPE_CONSTRAINTS_INFO (auto_node))
31228 PLACEHOLDER_TYPE_CONSTRAINTS_INFO (new_auto)
31229 = build_tree_list (current_template_parms,
31230 tsubst_constraint (TREE_VALUE (ci), targs,
31231 tf_none, NULL_TREE));
31232 TYPE_CANONICAL (new_auto) = canonical_type_parameter (new_auto);
31233 return tsubst (type, targs, tf_none, NULL_TREE);
31235 return type;
31238 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto' or
31239 'decltype(auto)' or a deduced class template. */
31241 bool
31242 is_auto (const_tree type)
31244 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
31245 && (TYPE_IDENTIFIER (type) == auto_identifier
31246 || TYPE_IDENTIFIER (type) == decltype_auto_identifier))
31247 return true;
31248 else
31249 return false;
31252 /* for_each_template_parm callback for type_uses_auto. */
31255 is_auto_r (tree tp, void */*data*/)
31257 return is_auto (tp);
31260 /* Returns the TEMPLATE_TYPE_PARM in TYPE representing `auto' iff TYPE contains
31261 a use of `auto'. Returns NULL_TREE otherwise. */
31263 tree
31264 type_uses_auto (tree type)
31266 if (type == NULL_TREE)
31267 return NULL_TREE;
31269 /* For parameter packs, check the contents of the pack. */
31270 if (PACK_EXPANSION_P (type))
31271 type = PACK_EXPANSION_PATTERN (type);
31273 if (flag_concepts_ts)
31275 /* The Concepts TS allows multiple autos in one type-specifier; just
31276 return the first one we find, do_auto_deduction will collect all of
31277 them. */
31278 if (uses_template_parms (type))
31279 return for_each_template_parm (type, is_auto_r, /*data*/NULL,
31280 /*visited*/NULL, /*nondeduced*/false);
31281 else
31282 return NULL_TREE;
31284 else
31285 return find_type_usage (type, is_auto);
31288 /* Report ill-formed occurrences of auto types in ARGUMENTS. If
31289 concepts are enabled, auto is acceptable in template arguments, but
31290 only when TEMPL identifies a template class. Return TRUE if any
31291 such errors were reported. */
31293 bool
31294 check_auto_in_tmpl_args (tree tmpl, tree args)
31296 if (!flag_concepts_ts)
31297 /* Only the concepts TS allows 'auto' as a type-id; it'd otherwise
31298 have already been rejected by the parser more generally. */
31299 return false;
31301 /* If there were previous errors, nevermind. */
31302 if (!args || TREE_CODE (args) != TREE_VEC)
31303 return false;
31305 /* If TMPL is an identifier, we're parsing and we can't tell yet
31306 whether TMPL is supposed to be a type, a function or a variable.
31307 We'll only be able to tell during template substitution, so we
31308 expect to be called again then. If concepts are enabled and we
31309 know we have a type, we're ok. */
31310 if (identifier_p (tmpl)
31311 || (DECL_P (tmpl)
31312 && (DECL_TYPE_TEMPLATE_P (tmpl)
31313 || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))))
31314 return false;
31316 /* Quickly search for any occurrences of auto; usually there won't
31317 be any, and then we'll avoid allocating the vector. */
31318 if (!type_uses_auto (args))
31319 return false;
31321 bool errors = false;
31323 tree vec = extract_autos (args);
31324 for (int i = 0; i < TREE_VEC_LENGTH (vec); i++)
31326 tree xauto = TREE_VALUE (TREE_VEC_ELT (vec, i));
31327 error_at (DECL_SOURCE_LOCATION (xauto),
31328 "invalid use of %qT in template argument", xauto);
31329 errors = true;
31332 return errors;
31335 /* Recursively walk over && expressions searching for EXPR. Return a reference
31336 to that expression. */
31338 static tree *find_template_requirement (tree *t, tree key)
31340 if (*t == key)
31341 return t;
31342 if (TREE_CODE (*t) == TRUTH_ANDIF_EXPR)
31344 if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 0), key))
31345 return p;
31346 if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 1), key))
31347 return p;
31349 return 0;
31352 /* Convert the generic type parameters in PARM that match the types given in the
31353 range [START_IDX, END_IDX) from the current_template_parms into generic type
31354 packs. */
31356 tree
31357 convert_generic_types_to_packs (tree parm, int start_idx, int end_idx)
31359 tree current = current_template_parms;
31360 int depth = TMPL_PARMS_DEPTH (current);
31361 current = INNERMOST_TEMPLATE_PARMS (current);
31362 tree replacement = make_tree_vec (TREE_VEC_LENGTH (current));
31364 for (int i = 0; i < start_idx; ++i)
31365 TREE_VEC_ELT (replacement, i)
31366 = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
31368 for (int i = start_idx; i < end_idx; ++i)
31370 /* Create a distinct parameter pack type from the current parm and add it
31371 to the replacement args to tsubst below into the generic function
31372 parameter. */
31373 tree node = TREE_VEC_ELT (current, i);
31374 tree o = TREE_TYPE (TREE_VALUE (node));
31375 tree t = copy_type (o);
31376 TEMPLATE_TYPE_PARM_INDEX (t)
31377 = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (o),
31378 t, 0, 0, tf_none);
31379 TREE_TYPE (TEMPLATE_TYPE_DECL (t)) = t;
31380 TYPE_STUB_DECL (t) = TYPE_NAME (t) = TEMPLATE_TYPE_DECL (t);
31381 TYPE_MAIN_VARIANT (t) = t;
31382 TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
31383 TYPE_CANONICAL (t) = canonical_type_parameter (t);
31384 TREE_VEC_ELT (replacement, i) = t;
31386 /* Replace the current template parameter with new pack. */
31387 TREE_VALUE (node) = TREE_CHAIN (t);
31389 /* Surgically adjust the associated constraint of adjusted parameter
31390 and it's corresponding contribution to the current template
31391 requirements. */
31392 if (tree constr = TEMPLATE_PARM_CONSTRAINTS (node))
31394 tree id = unpack_concept_check (constr);
31395 TREE_VEC_ELT (TREE_OPERAND (id, 1), 0) = t;
31396 /* Use UNKNOWN_LOCATION so write_template_args can tell the
31397 difference between this and a fold the user wrote. */
31398 location_t loc = UNKNOWN_LOCATION;
31399 tree fold = finish_left_unary_fold_expr (loc, constr,
31400 TRUTH_ANDIF_EXPR);
31401 TEMPLATE_PARM_CONSTRAINTS (node) = fold;
31403 /* If there was a constraint, we also need to replace that in
31404 the template requirements, which we've already built. */
31405 tree *reqs = &TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
31406 reqs = find_template_requirement (reqs, constr);
31407 *reqs = fold;
31411 for (int i = end_idx, e = TREE_VEC_LENGTH (current); i < e; ++i)
31412 TREE_VEC_ELT (replacement, i)
31413 = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
31415 /* If there are more levels then build up the replacement with the outer
31416 template parms. */
31417 if (depth > 1)
31418 replacement = add_to_template_args (template_parms_to_args
31419 (TREE_CHAIN (current_template_parms)),
31420 replacement);
31422 return tsubst (parm, replacement, tf_none, NULL_TREE);
31425 /* __integer_pack(N) in a pack expansion expands to a sequence of numbers from
31426 0..N-1. */
31428 void
31429 declare_integer_pack (void)
31431 tree ipfn = push_library_fn (get_identifier ("__integer_pack"),
31432 build_function_type_list (integer_type_node,
31433 integer_type_node,
31434 NULL_TREE),
31435 NULL_TREE, ECF_CONST);
31436 DECL_DECLARED_CONSTEXPR_P (ipfn) = true;
31437 set_decl_built_in_function (ipfn, BUILT_IN_FRONTEND,
31438 CP_BUILT_IN_INTEGER_PACK);
31441 /* Walk the decl or type specialization table calling FN on each
31442 entry. */
31444 void
31445 walk_specializations (bool decls_p,
31446 void (*fn) (bool decls_p, spec_entry *entry, void *data),
31447 void *data)
31449 spec_hash_table *table = decls_p ? decl_specializations
31450 : type_specializations;
31451 spec_hash_table::iterator end (table->end ());
31452 for (spec_hash_table::iterator iter (table->begin ()); iter != end; ++iter)
31453 fn (decls_p, *iter, data);
31456 /* Lookup the specialization of *ELT, in the decl or type
31457 specialization table. Return the SPEC that's already there, or
31458 NULL if nothing. */
31460 tree
31461 match_mergeable_specialization (bool decl_p, spec_entry *elt)
31463 hash_table<spec_hasher> *specializations
31464 = decl_p ? decl_specializations : type_specializations;
31465 hashval_t hash = spec_hasher::hash (elt);
31466 auto *slot = specializations->find_slot_with_hash (elt, hash, NO_INSERT);
31468 if (slot)
31469 return (*slot)->spec;
31471 return NULL_TREE;
31474 /* Return flags encoding whether SPEC is on the instantiation and/or
31475 specialization lists of TMPL. */
31477 unsigned
31478 get_mergeable_specialization_flags (tree tmpl, tree decl)
31480 unsigned flags = 0;
31482 for (tree inst = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
31483 inst; inst = TREE_CHAIN (inst))
31484 if (TREE_VALUE (inst) == decl)
31486 flags |= 1;
31487 break;
31490 if (CLASS_TYPE_P (TREE_TYPE (decl))
31491 && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl))
31492 && CLASSTYPE_USE_TEMPLATE (TREE_TYPE (decl)) == 2)
31493 /* Only need to search if DECL is a partial specialization. */
31494 for (tree part = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
31495 part; part = TREE_CHAIN (part))
31496 if (TREE_VALUE (part) == decl)
31498 flags |= 2;
31499 break;
31502 return flags;
31505 /* Add a new specialization described by SPEC. DECL is the
31506 maybe-template decl and FLAGS is as returned from
31507 get_mergeable_specialization_flags. */
31509 void
31510 add_mergeable_specialization (bool decl_p, bool alias_p, spec_entry *elt,
31511 tree decl, unsigned flags)
31513 hashval_t hash = spec_hasher::hash (elt);
31514 if (decl_p)
31516 auto *slot = decl_specializations->find_slot_with_hash (elt, hash, INSERT);
31518 gcc_checking_assert (!*slot);
31519 auto entry = ggc_alloc<spec_entry> ();
31520 *entry = *elt;
31521 *slot = entry;
31523 if (alias_p)
31525 elt->spec = TREE_TYPE (elt->spec);
31526 gcc_checking_assert (elt->spec);
31530 if (!decl_p || alias_p)
31532 auto *slot = type_specializations->find_slot_with_hash (elt, hash, INSERT);
31534 /* We don't distinguish different constrained partial type
31535 specializations, so there could be duplicates. Everything else
31536 must be new. */
31537 if (!(flags & 2 && *slot))
31539 gcc_checking_assert (!*slot);
31541 auto entry = ggc_alloc<spec_entry> ();
31542 *entry = *elt;
31543 *slot = entry;
31547 if (flags & 1)
31548 DECL_TEMPLATE_INSTANTIATIONS (elt->tmpl)
31549 = tree_cons (elt->args, decl, DECL_TEMPLATE_INSTANTIATIONS (elt->tmpl));
31551 if (flags & 2)
31553 /* A partial specialization. */
31554 tree cons = tree_cons (elt->args, decl,
31555 DECL_TEMPLATE_SPECIALIZATIONS (elt->tmpl));
31556 TREE_TYPE (cons) = decl_p ? TREE_TYPE (elt->spec) : elt->spec;
31557 DECL_TEMPLATE_SPECIALIZATIONS (elt->tmpl) = cons;
31561 /* Set up the hash tables for template instantiations. */
31563 void
31564 init_template_processing (void)
31566 decl_specializations = hash_table<spec_hasher>::create_ggc (37);
31567 type_specializations = hash_table<spec_hasher>::create_ggc (37);
31569 if (cxx_dialect >= cxx11)
31570 declare_integer_pack ();
31573 /* Print stats about the template hash tables for -fstats. */
31575 void
31576 print_template_statistics (void)
31578 fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
31579 "%f collisions\n", (long) decl_specializations->size (),
31580 (long) decl_specializations->elements (),
31581 decl_specializations->collisions ());
31582 fprintf (stderr, "type_specializations: size %ld, %ld elements, "
31583 "%f collisions\n", (long) type_specializations->size (),
31584 (long) type_specializations->elements (),
31585 type_specializations->collisions ());
31588 #if CHECKING_P
31590 namespace selftest {
31592 /* Verify that type_dependent_expression_p () works correctly, even
31593 in the presence of location wrapper nodes. */
31595 static void
31596 test_type_dependent_expression_p ()
31598 location_t loc = BUILTINS_LOCATION;
31600 tree name = get_identifier ("foo");
31602 /* If no templates are involved, nothing is type-dependent. */
31603 gcc_assert (!processing_template_decl);
31604 ASSERT_FALSE (type_dependent_expression_p (name));
31606 ++processing_template_decl;
31608 /* Within a template, an unresolved name is always type-dependent. */
31609 ASSERT_TRUE (type_dependent_expression_p (name));
31611 /* Ensure it copes with NULL_TREE and errors. */
31612 ASSERT_FALSE (type_dependent_expression_p (NULL_TREE));
31613 ASSERT_FALSE (type_dependent_expression_p (error_mark_node));
31615 /* A USING_DECL in a template should be type-dependent, even if wrapped
31616 with a location wrapper (PR c++/83799). */
31617 tree using_decl = build_lang_decl (USING_DECL, name, NULL_TREE);
31618 TREE_TYPE (using_decl) = integer_type_node;
31619 ASSERT_TRUE (type_dependent_expression_p (using_decl));
31620 tree wrapped_using_decl = maybe_wrap_with_location (using_decl, loc);
31621 ASSERT_TRUE (location_wrapper_p (wrapped_using_decl));
31622 ASSERT_TRUE (type_dependent_expression_p (wrapped_using_decl));
31624 --processing_template_decl;
31627 /* Run all of the selftests within this file. */
31629 void
31630 cp_pt_cc_tests ()
31632 test_type_dependent_expression_p ();
31635 } // namespace selftest
31637 #endif /* #if CHECKING_P */
31639 #include "gt-cp-pt.h"