libcpp, c, middle-end: Optimize initializers using #embed in C
[official-gcc.git] / gcc / cp / pt.cc
blob0141c53b617c87e7ac3afac1fa7e7a5bfca1a474
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"
51 #include "pretty-print-markup.h"
53 /* The type of functions taking a tree, and some additional data, and
54 returning an int. */
55 typedef int (*tree_fn_t) (tree, void*);
57 /* The PENDING_TEMPLATES is a list of templates whose instantiations
58 have been deferred, either because their definitions were not yet
59 available, or because we were putting off doing the work. */
60 struct GTY ((chain_next ("%h.next"))) pending_template
62 struct pending_template *next;
63 struct tinst_level *tinst;
66 static GTY(()) struct pending_template *pending_templates;
67 static GTY(()) struct pending_template *last_pending_template;
69 int processing_template_parmlist;
70 static int template_header_count;
72 static vec<int> inline_parm_levels;
74 static GTY(()) struct tinst_level *current_tinst_level;
76 static GTY(()) vec<tree, va_gc> *saved_access_scope;
78 /* Live only within one (recursive) call to tsubst_expr. We use
79 this to pass the statement expression node from the STMT_EXPR
80 to the EXPR_STMT that is its result. */
81 static tree cur_stmt_expr;
83 // -------------------------------------------------------------------------- //
84 // Local Specialization Stack
86 // Implementation of the RAII helper for creating new local
87 // specializations.
88 local_specialization_stack::local_specialization_stack (lss_policy policy)
89 : saved (local_specializations)
91 if (policy == lss_nop)
93 else if (policy == lss_blank || !saved)
94 local_specializations = new hash_map<tree, tree>;
95 else
96 local_specializations = new hash_map<tree, tree>(*saved);
99 local_specialization_stack::~local_specialization_stack ()
101 if (local_specializations != saved)
103 delete local_specializations;
104 local_specializations = saved;
108 /* True if we've recursed into fn_type_unification too many times. */
109 static bool excessive_deduction_depth;
111 struct spec_hasher : ggc_ptr_hash<spec_entry>
113 static hashval_t hash (tree, tree);
114 static hashval_t hash (spec_entry *);
115 static bool equal (spec_entry *, spec_entry *);
118 /* The general template is not in these tables. */
119 typedef hash_table<spec_hasher> spec_hash_table;
120 static GTY (()) spec_hash_table *decl_specializations;
121 static GTY (()) spec_hash_table *type_specializations;
123 /* Contains canonical template parameter types. The vector is indexed by
124 the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
125 TREE_LIST, whose TREE_VALUEs contain the canonical template
126 parameters of various types and levels. */
127 static GTY(()) vec<tree, va_gc> *canonical_template_parms;
129 #define UNIFY_ALLOW_NONE 0
130 #define UNIFY_ALLOW_MORE_CV_QUAL 1
131 #define UNIFY_ALLOW_LESS_CV_QUAL 2
132 #define UNIFY_ALLOW_DERIVED 4
133 #define UNIFY_ALLOW_INTEGER 8
134 #define UNIFY_ALLOW_OUTER_LEVEL 16
135 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
136 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
138 enum template_base_result {
139 tbr_incomplete_type,
140 tbr_ambiguous_baseclass,
141 tbr_success
144 static bool resolve_overloaded_unification (tree, tree, tree, tree,
145 unification_kind_t, int,
146 bool);
147 static int try_one_overload (tree, tree, tree, tree, tree,
148 unification_kind_t, int, bool, bool);
149 static int unify (tree, tree, tree, tree, int, bool);
150 static void add_pending_template (tree);
151 static tree reopen_tinst_level (struct tinst_level *);
152 static tree tsubst_initializer_list (tree, tree);
153 static tree get_partial_spec_bindings (tree, tree, tree);
154 static void tsubst_enum (tree, tree, tree);
155 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
156 static int check_non_deducible_conversion (tree, tree, unification_kind_t, int,
157 struct conversion **, bool, bool);
158 static int maybe_adjust_types_for_deduction (tree, unification_kind_t,
159 tree*, tree*, tree);
160 static int type_unification_real (tree, tree, tree, const tree *,
161 unsigned int, int, unification_kind_t,
162 vec<deferred_access_check, va_gc> **,
163 bool);
164 static void note_template_header (int);
165 static tree convert_nontype_argument_function (tree, tree, tsubst_flags_t);
166 static tree convert_nontype_argument (tree, tree, tsubst_flags_t);
167 static tree convert_template_argument (tree, tree, tree,
168 tsubst_flags_t, int, tree);
169 static tree for_each_template_parm (tree, tree_fn_t, void*,
170 hash_set<tree> *, bool, tree_fn_t = NULL);
171 static tree expand_template_argument_pack (tree);
172 static tree build_template_parm_index (int, int, int, tree, tree);
173 static bool inline_needs_template_parms (tree, bool);
174 static void push_inline_template_parms_recursive (tree, int);
175 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
176 static int mark_template_parm (tree, void *);
177 static int template_parm_this_level_p (tree, void *);
178 static tree tsubst_friend_function (tree, tree);
179 static tree tsubst_friend_class (tree, tree);
180 static int can_complete_type_without_circularity (tree);
181 static tree get_bindings (tree, tree, tree, bool);
182 static int template_decl_level (tree);
183 static int check_cv_quals_for_unify (int, tree, tree);
184 static int unify_pack_expansion (tree, tree, tree,
185 tree, unification_kind_t, bool, bool);
186 static tree copy_template_args (tree);
187 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
188 static void tsubst_each_template_parm_constraints (tree, tree, tsubst_flags_t);
189 static tree tsubst_arg_types (tree, tree, tree, tsubst_flags_t, tree);
190 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
191 static bool check_specialization_scope (void);
192 static tree process_partial_specialization (tree);
193 static enum template_base_result get_template_base (tree, tree, tree, tree,
194 bool , tree *);
195 static tree try_class_unification (tree, tree, tree, tree, bool);
196 static bool class_nttp_const_wrapper_p (tree t);
197 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
198 tree, tree);
199 static bool template_template_parm_bindings_ok_p (tree, tree);
200 static void tsubst_default_arguments (tree, tsubst_flags_t);
201 static tree for_each_template_parm_r (tree *, int *, void *);
202 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
203 static void copy_default_args_to_explicit_spec (tree);
204 static bool invalid_nontype_parm_type_p (tree, tsubst_flags_t);
205 static bool dependent_template_arg_p (tree);
206 static bool dependent_type_p_r (tree);
207 static tree tsubst_stmt (tree, tree, tsubst_flags_t, tree);
208 static tree tsubst_decl (tree, tree, tsubst_flags_t, bool = true);
209 static tree tsubst_scope (tree, tree, tsubst_flags_t, tree);
210 static tree tsubst_name (tree, tree, tsubst_flags_t, tree);
211 static void perform_instantiation_time_access_checks (tree, tree);
212 static tree listify (tree);
213 static tree listify_autos (tree, tree);
214 static tree tsubst_template_parm (tree, tree, tsubst_flags_t);
215 static tree instantiate_alias_template (tree, tree, tsubst_flags_t);
216 static tree get_underlying_template (tree);
217 static tree tsubst_attributes (tree, tree, tsubst_flags_t, tree);
218 static tree canonicalize_expr_argument (tree, tsubst_flags_t);
219 static tree make_argument_pack (tree);
220 static tree enclosing_instantiation_of (tree tctx);
221 static void instantiate_body (tree pattern, tree args, tree d, bool nested);
222 static tree maybe_dependent_member_ref (tree, tree, tsubst_flags_t, tree);
223 static void mark_template_arguments_used (tree, tree);
224 static bool uses_outer_template_parms (tree);
225 static tree alias_ctad_tweaks (tree, tree);
226 static tree inherited_ctad_tweaks (tree, tree, tsubst_flags_t);
227 static tree deduction_guides_for (tree, bool&, tsubst_flags_t);
229 /* Make the current scope suitable for access checking when we are
230 processing T. T can be FUNCTION_DECL for instantiated function
231 template, VAR_DECL for static member variable, or TYPE_DECL for
232 for a class or alias template (needed by instantiate_decl). */
234 void
235 push_access_scope (tree t)
237 gcc_assert (VAR_OR_FUNCTION_DECL_P (t)
238 || TREE_CODE (t) == TYPE_DECL);
240 if (DECL_FRIEND_CONTEXT (t))
241 push_nested_class (DECL_FRIEND_CONTEXT (t));
242 else if (DECL_IMPLICIT_TYPEDEF_P (t)
243 && CLASS_TYPE_P (TREE_TYPE (t)))
244 push_nested_class (TREE_TYPE (t));
245 else if (DECL_CLASS_SCOPE_P (t))
246 push_nested_class (DECL_CONTEXT (t));
247 else if (deduction_guide_p (t) && DECL_ARTIFICIAL (t))
248 /* An artificial deduction guide should have the same access as
249 the constructor. */
250 push_nested_class (TREE_TYPE (TREE_TYPE (t)));
251 else
252 push_to_top_level ();
254 if (TREE_CODE (t) == FUNCTION_DECL)
256 vec_safe_push (saved_access_scope, current_function_decl);
257 current_function_decl = t;
261 /* Restore the scope set up by push_access_scope. T is the node we
262 are processing. */
264 void
265 pop_access_scope (tree t)
267 if (TREE_CODE (t) == FUNCTION_DECL)
268 current_function_decl = saved_access_scope->pop();
270 if (DECL_FRIEND_CONTEXT (t)
271 || (DECL_IMPLICIT_TYPEDEF_P (t)
272 && CLASS_TYPE_P (TREE_TYPE (t)))
273 || DECL_CLASS_SCOPE_P (t)
274 || (deduction_guide_p (t) && DECL_ARTIFICIAL (t)))
275 pop_nested_class ();
276 else
277 pop_from_top_level ();
280 /* Do any processing required when DECL (a member template
281 declaration) is finished. Returns the TEMPLATE_DECL corresponding
282 to DECL, unless it is a specialization, in which case the DECL
283 itself is returned. */
285 tree
286 finish_member_template_decl (tree decl)
288 if (decl == error_mark_node)
289 return error_mark_node;
291 gcc_assert (DECL_P (decl));
293 if (TREE_CODE (decl) == TYPE_DECL)
295 tree type;
297 type = TREE_TYPE (decl);
298 if (type == error_mark_node)
299 return error_mark_node;
300 if (MAYBE_CLASS_TYPE_P (type)
301 && CLASSTYPE_TEMPLATE_INFO (type)
302 && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
304 tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
305 check_member_template (tmpl);
306 return tmpl;
308 return NULL_TREE;
310 else if (TREE_CODE (decl) == FIELD_DECL)
311 error_at (DECL_SOURCE_LOCATION (decl),
312 "data member %qD cannot be a member template", decl);
313 else if (DECL_TEMPLATE_INFO (decl))
315 if (!DECL_TEMPLATE_SPECIALIZATION (decl))
317 check_member_template (DECL_TI_TEMPLATE (decl));
318 return DECL_TI_TEMPLATE (decl);
320 else
321 return NULL_TREE;
323 else
324 error_at (DECL_SOURCE_LOCATION (decl),
325 "invalid member template declaration %qD", decl);
327 return error_mark_node;
330 /* Create a template info node. */
332 tree
333 build_template_info (tree template_decl, tree template_args)
335 tree result = make_node (TEMPLATE_INFO);
336 TI_TEMPLATE (result) = template_decl;
337 TI_ARGS (result) = template_args;
338 return result;
341 /* DECL_TEMPLATE_INFO, if applicable, or NULL_TREE. */
343 static tree
344 decl_template_info (const_tree decl)
346 /* This needs to match template_info_decl_check. */
347 if (DECL_LANG_SPECIFIC (decl))
348 switch (TREE_CODE (decl))
350 case FUNCTION_DECL:
351 if (DECL_THUNK_P (decl))
352 break;
353 gcc_fallthrough ();
354 case VAR_DECL:
355 case FIELD_DECL:
356 case TYPE_DECL:
357 case CONCEPT_DECL:
358 case TEMPLATE_DECL:
359 return DECL_TEMPLATE_INFO (decl);
361 default:
362 break;
364 return NULL_TREE;
367 /* Return the template info node corresponding to T, whatever T is. */
369 tree
370 get_template_info (const_tree t)
372 tree tinfo = NULL_TREE;
374 if (!t || t == error_mark_node)
375 return NULL;
377 if (TREE_CODE (t) == NAMESPACE_DECL
378 || TREE_CODE (t) == PARM_DECL)
379 return NULL;
381 if (DECL_P (t))
382 tinfo = decl_template_info (t);
384 if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
385 t = TREE_TYPE (t);
387 if (OVERLOAD_TYPE_P (t))
388 tinfo = TYPE_TEMPLATE_INFO (t);
389 else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
390 tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
392 return tinfo;
395 /* Returns the template nesting level of the indicated class TYPE.
397 For example, in:
398 template <class T>
399 struct A
401 template <class U>
402 struct B {};
405 A<T>::B<U> has depth two, while A<T> has depth one.
406 Both A<T>::B<int> and A<int>::B<U> have depth one, if
407 they are instantiations, not specializations.
409 This function is guaranteed to return 0 if passed NULL_TREE so
410 that, for example, `template_class_depth (current_class_type)' is
411 always safe. */
414 template_class_depth (tree type)
416 int depth;
418 for (depth = 0; type && TREE_CODE (type) != NAMESPACE_DECL; )
420 tree tinfo = get_template_info (type);
422 if (tinfo
423 && TREE_CODE (TI_TEMPLATE (tinfo)) == TEMPLATE_DECL
424 && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
425 && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
426 ++depth;
428 if (DECL_P (type))
430 if (tree fctx = DECL_FRIEND_CONTEXT (type))
431 type = fctx;
432 else
433 type = CP_DECL_CONTEXT (type);
435 else if (LAMBDA_TYPE_P (type) && LAMBDA_TYPE_EXTRA_SCOPE (type))
436 type = LAMBDA_TYPE_EXTRA_SCOPE (type);
437 else
438 type = CP_TYPE_CONTEXT (type);
441 return depth;
444 /* Return TRUE if NODE instantiates a template that has arguments of
445 its own, be it directly a primary template or indirectly through a
446 partial specializations. */
447 static bool
448 instantiates_primary_template_p (tree node)
450 tree tinfo = get_template_info (node);
451 if (!tinfo)
452 return false;
454 tree tmpl = TI_TEMPLATE (tinfo);
455 if (PRIMARY_TEMPLATE_P (tmpl))
456 return true;
458 if (!DECL_TEMPLATE_SPECIALIZATION (tmpl))
459 return false;
461 /* So now we know we have a specialization, but it could be a full
462 or a partial specialization. To tell which, compare the depth of
463 its template arguments with those of its context. */
465 tree ctxt = DECL_CONTEXT (tmpl);
466 tree ctinfo = get_template_info (ctxt);
467 if (!ctinfo)
468 return true;
470 return (TMPL_ARGS_DEPTH (TI_ARGS (tinfo))
471 > TMPL_ARGS_DEPTH (TI_ARGS (ctinfo)));
474 /* Subroutine of maybe_begin_member_template_processing.
475 Returns true if processing DECL needs us to push template parms. */
477 static bool
478 inline_needs_template_parms (tree decl, bool nsdmi)
480 if (!decl || (!nsdmi && ! DECL_TEMPLATE_INFO (decl)))
481 return false;
483 return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
484 > (current_template_depth + DECL_TEMPLATE_SPECIALIZATION (decl)));
487 /* Subroutine of maybe_begin_member_template_processing.
488 Push the template parms in PARMS, starting from LEVELS steps into the
489 chain, and ending at the beginning, since template parms are listed
490 innermost first. */
492 static void
493 push_inline_template_parms_recursive (tree parmlist, int levels)
495 tree parms = TREE_VALUE (parmlist);
496 int i;
498 if (levels > 1)
499 push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
501 ++processing_template_decl;
502 current_template_parms
503 = tree_cons (size_int (current_template_depth + 1),
504 parms, current_template_parms);
505 TEMPLATE_PARMS_CONSTRAINTS (current_template_parms)
506 = TEMPLATE_PARMS_CONSTRAINTS (parmlist);
507 TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
509 begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
510 NULL);
511 for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
513 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
515 if (error_operand_p (parm))
516 continue;
518 gcc_assert (DECL_P (parm));
520 switch (TREE_CODE (parm))
522 case TYPE_DECL:
523 case TEMPLATE_DECL:
524 pushdecl (parm);
525 break;
527 case PARM_DECL:
528 /* Push the CONST_DECL. */
529 pushdecl (TEMPLATE_PARM_DECL (DECL_INITIAL (parm)));
530 break;
532 default:
533 gcc_unreachable ();
538 /* Restore the template parameter context for a member template, a
539 friend template defined in a class definition, or a non-template
540 member of template class. */
542 void
543 maybe_begin_member_template_processing (tree decl)
545 tree parms;
546 int levels = 0;
547 bool nsdmi = TREE_CODE (decl) == FIELD_DECL;
549 if (nsdmi)
551 tree ctx = DECL_CONTEXT (decl);
552 decl = (CLASSTYPE_TEMPLATE_INFO (ctx)
553 /* Disregard full specializations (c++/60999). */
554 && uses_template_parms (ctx)
555 ? CLASSTYPE_TI_TEMPLATE (ctx) : NULL_TREE);
558 if (inline_needs_template_parms (decl, nsdmi))
560 parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
561 levels = TMPL_PARMS_DEPTH (parms) - current_template_depth;
563 if (DECL_TEMPLATE_SPECIALIZATION (decl))
565 --levels;
566 parms = TREE_CHAIN (parms);
569 push_inline_template_parms_recursive (parms, levels);
572 /* Remember how many levels of template parameters we pushed so that
573 we can pop them later. */
574 inline_parm_levels.safe_push (levels);
577 /* Undo the effects of maybe_begin_member_template_processing. */
579 void
580 maybe_end_member_template_processing (void)
582 int i;
583 int last;
585 if (inline_parm_levels.length () == 0)
586 return;
588 last = inline_parm_levels.pop ();
589 for (i = 0; i < last; ++i)
591 --processing_template_decl;
592 current_template_parms = TREE_CHAIN (current_template_parms);
593 poplevel (0, 0, 0);
597 /* Return a new template argument vector which contains all of ARGS,
598 but has as its innermost set of arguments the EXTRA_ARGS. */
600 tree
601 add_to_template_args (tree args, tree extra_args)
603 tree new_args;
604 int extra_depth;
605 int i;
606 int j;
608 if (args == NULL_TREE || extra_args == error_mark_node)
609 return extra_args;
611 extra_depth = TMPL_ARGS_DEPTH (extra_args);
612 new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
614 for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
615 SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
617 for (j = 1; j <= extra_depth; ++j, ++i)
618 SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
620 return new_args;
623 /* Like add_to_template_args, but only the outermost ARGS are added to
624 the EXTRA_ARGS. In particular, all but TMPL_ARGS_DEPTH
625 (EXTRA_ARGS) levels are added. This function is used to combine
626 the template arguments from a partial instantiation with the
627 template arguments used to attain the full instantiation from the
628 partial instantiation.
630 If ARGS is a TEMPLATE_DECL, use its parameters as args. */
632 tree
633 add_outermost_template_args (tree args, tree extra_args)
635 tree new_args;
637 if (!args)
638 return extra_args;
639 if (TREE_CODE (args) == TEMPLATE_DECL)
641 tree ti = get_template_info (DECL_TEMPLATE_RESULT (args));
642 args = TI_ARGS (ti);
645 /* If there are more levels of EXTRA_ARGS than there are ARGS,
646 something very fishy is going on. */
647 gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
649 /* If *all* the new arguments will be the EXTRA_ARGS, just return
650 them. */
651 if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
652 return extra_args;
654 /* For the moment, we make ARGS look like it contains fewer levels. */
655 TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
657 new_args = add_to_template_args (args, extra_args);
659 /* Now, we restore ARGS to its full dimensions. */
660 TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
662 return new_args;
665 /* Return the N levels of innermost template arguments from the ARGS. */
667 tree
668 get_innermost_template_args (tree args, int n)
670 tree new_args;
671 int extra_levels;
672 int i;
674 gcc_assert (n >= 0);
676 /* If N is 1, just return the innermost set of template arguments. */
677 if (n == 1)
678 return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
680 /* If we're not removing anything, just return the arguments we were
681 given. */
682 extra_levels = TMPL_ARGS_DEPTH (args) - n;
683 gcc_assert (extra_levels >= 0);
684 if (extra_levels == 0)
685 return args;
687 /* Make a new set of arguments, not containing the outer arguments. */
688 new_args = make_tree_vec (n);
689 for (i = 1; i <= n; ++i)
690 SET_TMPL_ARGS_LEVEL (new_args, i,
691 TMPL_ARGS_LEVEL (args, i + extra_levels));
693 return new_args;
696 /* The inverse of get_innermost_template_args: Return all but the innermost
697 EXTRA_LEVELS levels of template arguments from the ARGS. */
699 static tree
700 strip_innermost_template_args (tree args, int extra_levels)
702 tree new_args;
703 int n = TMPL_ARGS_DEPTH (args) - extra_levels;
704 int i;
706 gcc_assert (n >= 0);
708 /* If N is 1, just return the outermost set of template arguments. */
709 if (n == 1)
710 return TMPL_ARGS_LEVEL (args, 1);
712 /* If we're not removing anything, just return the arguments we were
713 given. */
714 gcc_assert (extra_levels >= 0);
715 if (extra_levels == 0)
716 return args;
718 /* Make a new set of arguments, not containing the inner arguments. */
719 new_args = make_tree_vec (n);
720 for (i = 1; i <= n; ++i)
721 SET_TMPL_ARGS_LEVEL (new_args, i,
722 TMPL_ARGS_LEVEL (args, i));
724 return new_args;
727 /* We've got a template header coming up; push to a new level for storing
728 the parms. */
730 void
731 begin_template_parm_list (void)
733 /* We use a non-tag-transparent scope here, which causes pushtag to
734 put tags in this scope, rather than in the enclosing class or
735 namespace scope. This is the right thing, since we want
736 TEMPLATE_DECLS, and not TYPE_DECLS for template classes. For a
737 global template class, push_template_decl handles putting the
738 TEMPLATE_DECL into top-level scope. For a nested template class,
739 e.g.:
741 template <class T> struct S1 {
742 template <class T> struct S2 {};
745 pushtag contains special code to insert the TEMPLATE_DECL for S2
746 at the right scope. */
747 begin_scope (sk_template_parms, NULL);
748 ++processing_template_decl;
749 ++processing_template_parmlist;
750 note_template_header (0);
752 /* Add a dummy parameter level while we process the parameter list. */
753 current_template_parms
754 = tree_cons (size_int (current_template_depth + 1),
755 make_tree_vec (0),
756 current_template_parms);
759 /* This routine is called when a specialization is declared. If it is
760 invalid to declare a specialization here, an error is reported and
761 false is returned, otherwise this routine will return true. */
763 static bool
764 check_specialization_scope (void)
766 tree scope = current_scope ();
768 /* [temp.expl.spec]
770 An explicit specialization shall be declared in the namespace of
771 which the template is a member, or, for member templates, in the
772 namespace of which the enclosing class or enclosing class
773 template is a member. An explicit specialization of a member
774 function, member class or static data member of a class template
775 shall be declared in the namespace of which the class template
776 is a member. */
777 if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
779 error ("explicit specialization in non-namespace scope %qD", scope);
780 return false;
783 /* [temp.expl.spec]
785 In an explicit specialization declaration for a member of a class
786 template or a member template that appears in namespace scope,
787 the member template and some of its enclosing class templates may
788 remain unspecialized, except that the declaration shall not
789 explicitly specialize a class member template if its enclosing
790 class templates are not explicitly specialized as well. */
791 if (current_template_parms)
793 error ("enclosing class templates are not explicitly specialized");
794 return false;
797 return true;
800 /* We've just seen template <>. */
802 bool
803 begin_specialization (void)
805 begin_scope (sk_template_spec, NULL);
806 note_template_header (1);
807 return check_specialization_scope ();
810 /* Called at then end of processing a declaration preceded by
811 template<>. */
813 void
814 end_specialization (void)
816 finish_scope ();
817 reset_specialization ();
820 /* Any template <>'s that we have seen thus far are not referring to a
821 function specialization. */
823 void
824 reset_specialization (void)
826 processing_specialization = 0;
827 template_header_count = 0;
830 /* We've just seen a template header. If SPECIALIZATION is nonzero,
831 it was of the form template <>. */
833 static void
834 note_template_header (int specialization)
836 processing_specialization = specialization;
837 template_header_count++;
840 /* We're beginning an explicit instantiation. */
842 void
843 begin_explicit_instantiation (void)
845 gcc_assert (!processing_explicit_instantiation);
846 processing_explicit_instantiation = true;
850 void
851 end_explicit_instantiation (void)
853 gcc_assert (processing_explicit_instantiation);
854 processing_explicit_instantiation = false;
857 /* An explicit specialization or partial specialization of TMPL is being
858 declared. Check that the namespace in which the specialization is
859 occurring is permissible. Returns false iff it is invalid to
860 specialize TMPL in the current namespace. */
862 static bool
863 check_specialization_namespace (tree tmpl)
865 tree tpl_ns = decl_namespace_context (tmpl);
867 /* [tmpl.expl.spec]
869 An explicit specialization shall be declared in a namespace enclosing the
870 specialized template. An explicit specialization whose declarator-id is
871 not qualified shall be declared in the nearest enclosing namespace of the
872 template, or, if the namespace is inline (7.3.1), any namespace from its
873 enclosing namespace set. */
874 if (current_scope() != DECL_CONTEXT (tmpl)
875 && !at_namespace_scope_p ())
877 error ("specialization of %qD must appear at namespace scope", tmpl);
878 return false;
881 if (is_nested_namespace (current_namespace, tpl_ns, cxx_dialect < cxx11))
882 /* Same or enclosing namespace. */
883 return true;
884 else
886 auto_diagnostic_group d;
887 if (permerror (input_location,
888 "specialization of %qD in different namespace", tmpl))
889 inform (DECL_SOURCE_LOCATION (tmpl),
890 " from definition of %q#D", tmpl);
891 return false;
895 /* SPEC is an explicit instantiation. Check that it is valid to
896 perform this explicit instantiation in the current namespace. */
898 static void
899 check_explicit_instantiation_namespace (tree spec)
901 tree ns;
903 /* DR 275: An explicit instantiation shall appear in an enclosing
904 namespace of its template. */
905 ns = decl_namespace_context (spec);
906 if (!is_nested_namespace (current_namespace, ns))
907 permerror (input_location, "explicit instantiation of %qD in namespace %qD "
908 "(which does not enclose namespace %qD)",
909 spec, current_namespace, ns);
912 /* Returns true if TYPE is a new partial specialization that needs to be
913 set up. This may also modify TYPE to point to the correct (new or
914 existing) constrained partial specialization. */
916 static bool
917 maybe_new_partial_specialization (tree& type)
919 /* An implicit instantiation of an incomplete type implies
920 the definition of a new class template.
922 template<typename T>
923 struct S;
925 template<typename T>
926 struct S<T*>;
928 Here, S<T*> is an implicit instantiation of S whose type
929 is incomplete. */
930 if (CLASSTYPE_IMPLICIT_INSTANTIATION (type) && !COMPLETE_TYPE_P (type))
931 return true;
933 /* It can also be the case that TYPE is a completed specialization.
934 Continuing the previous example, suppose we also declare:
936 template<typename T>
937 requires Integral<T>
938 struct S<T*>;
940 Here, S<T*> refers to the specialization S<T*> defined
941 above. However, we need to differentiate definitions because
942 we intend to define a new partial specialization. In this case,
943 we rely on the fact that the constraints are different for
944 this declaration than that above.
946 Note that we also get here for injected class names and
947 late-parsed template definitions. We must ensure that we
948 do not create new type declarations for those cases. */
949 if (flag_concepts && CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
951 tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
952 tree args = CLASSTYPE_TI_ARGS (type);
954 /* If there are no template parameters, this cannot be a new
955 partial template specialization? */
956 if (!current_template_parms)
957 return false;
959 /* The injected-class-name is not a new partial specialization. */
960 if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
961 return false;
963 /* If the constraints are not the same as those of the primary
964 then, we can probably create a new specialization. */
965 tree type_constr = current_template_constraints ();
967 if (type == TREE_TYPE (tmpl))
969 tree main_constr = get_constraints (tmpl);
970 if (equivalent_constraints (type_constr, main_constr))
971 return false;
974 /* Also, if there's a pre-existing specialization with matching
975 constraints, then this also isn't new. */
976 tree specs = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
977 while (specs)
979 tree spec_tmpl = TREE_VALUE (specs);
980 tree spec_args = TREE_PURPOSE (specs);
981 tree spec_constr = get_constraints (spec_tmpl);
982 if (comp_template_args (args, spec_args)
983 && equivalent_constraints (type_constr, spec_constr))
985 type = TREE_TYPE (spec_tmpl);
986 return false;
988 specs = TREE_CHAIN (specs);
991 /* Create a new type node (and corresponding type decl)
992 for the newly declared specialization. */
993 tree t = make_class_type (TREE_CODE (type));
994 CLASSTYPE_DECLARED_CLASS (t) = CLASSTYPE_DECLARED_CLASS (type);
995 SET_TYPE_TEMPLATE_INFO (t, build_template_info (tmpl, args));
996 TYPE_CONTEXT (t) = TYPE_CONTEXT (type);
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 auto_diagnostic_group d;
1129 if (permerror (input_location,
1130 "specialization of %qD in different namespace",
1131 type))
1132 inform (DECL_SOURCE_LOCATION (tmpl),
1133 "from definition of %q#D", tmpl);
1136 /* Check for invalid specialization after instantiation:
1138 template <> template <> class C<int>::D<int>;
1139 template <> template <class U> class C<int>::D; */
1141 for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
1142 t; t = TREE_CHAIN (t))
1144 tree inst = TREE_VALUE (t);
1145 if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst)
1146 || !COMPLETE_OR_OPEN_TYPE_P (inst))
1148 /* We already have a full specialization of this partial
1149 instantiation, or a full specialization has been
1150 looked up but not instantiated. Reassign it to the
1151 new member specialization template. */
1152 spec_entry elt;
1153 spec_entry *entry;
1155 elt.tmpl = most_general_template (tmpl);
1156 elt.args = CLASSTYPE_TI_ARGS (inst);
1157 elt.spec = inst;
1159 type_specializations->remove_elt (&elt);
1161 elt.tmpl = tmpl;
1162 CLASSTYPE_TI_ARGS (inst)
1163 = elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
1164 elt.hash = 0; /* Recalculate after changing tmpl/args. */
1166 spec_entry **slot
1167 = type_specializations->find_slot (&elt, INSERT);
1168 entry = ggc_alloc<spec_entry> ();
1169 *entry = elt;
1170 *slot = entry;
1172 else
1173 /* But if we've had an implicit instantiation, that's a
1174 problem ([temp.expl.spec]/6). */
1175 error ("specialization %qT after instantiation %qT",
1176 type, inst);
1179 /* Make sure that the specialization is valid. */
1180 if (!redeclare_class_template (type, current_template_parms,
1181 current_template_constraints ()))
1182 return error_mark_node;
1184 /* Mark TYPE as a specialization. And as a result, we only
1185 have one level of template argument for the innermost
1186 class template. */
1187 SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
1188 DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
1189 CLASSTYPE_TI_ARGS (type)
1190 = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
1193 else if (processing_specialization)
1195 /* Someday C++0x may allow for enum template specialization. */
1196 if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
1197 && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
1198 pedwarn (input_location, OPT_Wpedantic, "template specialization "
1199 "of %qD not allowed by ISO C++", type);
1200 else
1202 error ("explicit specialization of non-template %qT", type);
1203 return error_mark_node;
1207 return type;
1210 /* Make sure ARGS doesn't use any inappropriate typedefs; we should have
1211 gone through coerce_template_parms by now. */
1213 static void
1214 verify_unstripped_args_1 (tree inner)
1216 for (int i = 0; i < TREE_VEC_LENGTH (inner); ++i)
1218 tree arg = TREE_VEC_ELT (inner, i);
1219 if (TREE_CODE (arg) == TEMPLATE_DECL)
1220 /* OK */;
1221 else if (TYPE_P (arg))
1222 gcc_assert (strip_typedefs (arg, NULL) == arg);
1223 else if (ARGUMENT_PACK_P (arg))
1224 verify_unstripped_args_1 (ARGUMENT_PACK_ARGS (arg));
1225 else if (strip_typedefs (TREE_TYPE (arg), NULL) != TREE_TYPE (arg))
1226 /* Allow typedefs on the type of a non-type argument, since a
1227 parameter can have them. */;
1228 else
1229 gcc_assert (strip_typedefs_expr (arg, NULL) == arg);
1233 static void
1234 verify_unstripped_args (tree args)
1236 ++processing_template_decl;
1237 if (!any_dependent_template_arguments_p (args))
1238 verify_unstripped_args_1 (INNERMOST_TEMPLATE_ARGS (args));
1239 --processing_template_decl;
1242 /* Retrieve the specialization (in the sense of [temp.spec] - a
1243 specialization is either an instantiation or an explicit
1244 specialization) of TMPL for the given template ARGS. If there is
1245 no such specialization, return NULL_TREE. The ARGS are a vector of
1246 arguments, or a vector of vectors of arguments, in the case of
1247 templates with more than one level of parameters.
1249 If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
1250 then we search for a partial specialization matching ARGS. This
1251 parameter is ignored if TMPL is not a class template.
1253 We can also look up a FIELD_DECL, if it is a lambda capture pack; the
1254 result is a NONTYPE_ARGUMENT_PACK. */
1256 static tree
1257 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
1259 if (tmpl == NULL_TREE)
1260 return NULL_TREE;
1262 if (args == error_mark_node)
1263 return NULL_TREE;
1265 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL
1266 || TREE_CODE (tmpl) == FIELD_DECL);
1268 /* There should be as many levels of arguments as there are
1269 levels of parameters. */
1270 gcc_assert (TMPL_ARGS_DEPTH (args)
1271 == (TREE_CODE (tmpl) == TEMPLATE_DECL
1272 ? TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl))
1273 : template_class_depth (DECL_CONTEXT (tmpl))));
1275 if (flag_checking)
1276 verify_unstripped_args (args);
1278 /* Lambda functions in templates aren't instantiated normally, but through
1279 tsubst_lambda_expr. */
1280 if (lambda_fn_in_template_p (tmpl))
1281 return NULL_TREE;
1283 spec_entry elt;
1284 elt.tmpl = tmpl;
1285 elt.args = args;
1286 elt.hash = hash;
1288 spec_hash_table *specializations;
1289 if (DECL_CLASS_TEMPLATE_P (tmpl))
1290 specializations = type_specializations;
1291 else
1292 specializations = decl_specializations;
1294 if (spec_entry *found = specializations->find (&elt))
1295 return found->spec;
1297 return NULL_TREE;
1300 /* Like retrieve_specialization, but for local declarations. */
1302 tree
1303 retrieve_local_specialization (tree tmpl)
1305 if (local_specializations == NULL)
1306 return NULL_TREE;
1308 tree *slot = local_specializations->get (tmpl);
1309 return slot ? *slot : NULL_TREE;
1312 /* Returns nonzero iff DECL is a specialization of TMPL. */
1315 is_specialization_of (tree decl, tree tmpl)
1317 tree t;
1319 if (TREE_CODE (decl) == FUNCTION_DECL)
1321 for (t = decl;
1322 t != NULL_TREE;
1323 t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1324 if (t == tmpl)
1325 return 1;
1327 else
1329 gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1331 for (t = TREE_TYPE (decl);
1332 t != NULL_TREE;
1333 t = CLASSTYPE_USE_TEMPLATE (t)
1334 ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1335 if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1336 return 1;
1339 return 0;
1342 /* Returns nonzero iff DECL is a specialization of friend declaration
1343 FRIEND_DECL according to [temp.friend]. */
1345 bool
1346 is_specialization_of_friend (tree decl, tree friend_decl)
1348 bool need_template = true;
1349 int template_depth;
1351 gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1352 || TREE_CODE (decl) == TYPE_DECL);
1354 /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1355 of a template class, we want to check if DECL is a specialization
1356 if this. */
1357 if (TREE_CODE (friend_decl) == FUNCTION_DECL
1358 && DECL_CLASS_SCOPE_P (friend_decl)
1359 && DECL_TEMPLATE_INFO (friend_decl)
1360 && !DECL_USE_TEMPLATE (friend_decl))
1362 /* We want a TEMPLATE_DECL for `is_specialization_of'. */
1363 friend_decl = DECL_TI_TEMPLATE (friend_decl);
1364 need_template = false;
1366 else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1367 && !PRIMARY_TEMPLATE_P (friend_decl))
1368 need_template = false;
1370 /* There is nothing to do if this is not a template friend. */
1371 if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1372 return false;
1374 if (is_specialization_of (decl, friend_decl))
1375 return true;
1377 /* [temp.friend/6]
1378 A member of a class template may be declared to be a friend of a
1379 non-template class. In this case, the corresponding member of
1380 every specialization of the class template is a friend of the
1381 class granting friendship.
1383 For example, given a template friend declaration
1385 template <class T> friend void A<T>::f();
1387 the member function below is considered a friend
1389 template <> struct A<int> {
1390 void f();
1393 For this type of template friend, TEMPLATE_DEPTH below will be
1394 nonzero. To determine if DECL is a friend of FRIEND, we first
1395 check if the enclosing class is a specialization of another. */
1397 template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1398 if (template_depth
1399 && DECL_CLASS_SCOPE_P (decl)
1400 && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1401 CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1403 /* Next, we check the members themselves. In order to handle
1404 a few tricky cases, such as when FRIEND_DECL's are
1406 template <class T> friend void A<T>::g(T t);
1407 template <class T> template <T t> friend void A<T>::h();
1409 and DECL's are
1411 void A<int>::g(int);
1412 template <int> void A<int>::h();
1414 we need to figure out ARGS, the template arguments from
1415 the context of DECL. This is required for template substitution
1416 of `T' in the function parameter of `g' and template parameter
1417 of `h' in the above examples. Here ARGS corresponds to `int'. */
1419 tree context = DECL_CONTEXT (decl);
1420 tree args = NULL_TREE;
1421 int current_depth = 0;
1423 while (current_depth < template_depth)
1425 if (CLASSTYPE_TEMPLATE_INFO (context))
1427 if (current_depth == 0)
1428 args = TYPE_TI_ARGS (context);
1429 else
1430 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1431 current_depth++;
1433 context = TYPE_CONTEXT (context);
1436 if (TREE_CODE (decl) == FUNCTION_DECL)
1438 bool is_template;
1439 tree friend_type;
1440 tree decl_type;
1441 tree friend_args_type;
1442 tree decl_args_type;
1444 /* Make sure that both DECL and FRIEND_DECL are templates or
1445 non-templates. */
1446 is_template = DECL_TEMPLATE_INFO (decl)
1447 && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1448 if (need_template ^ is_template)
1449 return false;
1450 else if (is_template)
1452 /* If both are templates, check template parameter list. */
1453 tree friend_parms
1454 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1455 args, tf_none);
1456 if (!comp_template_parms
1457 (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1458 friend_parms))
1459 return false;
1461 decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1463 else
1464 decl_type = TREE_TYPE (decl);
1466 friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1467 tf_none, NULL_TREE);
1468 if (friend_type == error_mark_node)
1469 return false;
1471 /* Check if return types match. */
1472 if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1473 return false;
1475 /* Check if function parameter types match, ignoring the
1476 `this' parameter. */
1477 friend_args_type = TYPE_ARG_TYPES (friend_type);
1478 decl_args_type = TYPE_ARG_TYPES (decl_type);
1479 if (DECL_IOBJ_MEMBER_FUNCTION_P (friend_decl))
1480 friend_args_type = TREE_CHAIN (friend_args_type);
1481 if (DECL_IOBJ_MEMBER_FUNCTION_P (decl))
1482 decl_args_type = TREE_CHAIN (decl_args_type);
1484 return compparms (decl_args_type, friend_args_type);
1486 else
1488 /* DECL is a TYPE_DECL */
1489 bool is_template;
1490 tree decl_type = TREE_TYPE (decl);
1492 /* Make sure that both DECL and FRIEND_DECL are templates or
1493 non-templates. */
1494 is_template
1495 = CLASSTYPE_TEMPLATE_INFO (decl_type)
1496 && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1498 if (need_template ^ is_template)
1499 return false;
1500 else if (is_template)
1502 tree friend_parms;
1503 /* If both are templates, check the name of the two
1504 TEMPLATE_DECL's first because is_friend didn't. */
1505 if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1506 != DECL_NAME (friend_decl))
1507 return false;
1509 /* Now check template parameter list. */
1510 friend_parms
1511 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1512 args, tf_none);
1513 return comp_template_parms
1514 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1515 friend_parms);
1517 else
1518 return (DECL_NAME (decl)
1519 == DECL_NAME (friend_decl));
1522 return false;
1525 /* Register the specialization SPEC as a specialization of TMPL with
1526 the indicated ARGS. IS_FRIEND indicates whether the specialization
1527 is actually just a friend declaration. ATTRLIST is the list of
1528 attributes that the specialization is declared with or NULL when
1529 it isn't. Returns SPEC, or an equivalent prior declaration, if
1530 available.
1532 We also store instantiations of field packs in the hash table, even
1533 though they are not themselves templates, to make lookup easier. */
1535 static tree
1536 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1537 hashval_t hash)
1539 tree fn;
1541 gcc_assert ((TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec))
1542 || (TREE_CODE (tmpl) == FIELD_DECL
1543 && TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK));
1545 spec_entry elt;
1546 elt.tmpl = tmpl;
1547 elt.args = args;
1548 elt.spec = spec;
1550 if (hash == 0)
1551 hash = spec_hasher::hash (&elt);
1553 spec_entry **slot = decl_specializations->find_slot (&elt, INSERT);
1554 if (*slot)
1555 fn = (*slot)->spec;
1556 else
1557 fn = NULL_TREE;
1559 /* We can sometimes try to re-register a specialization that we've
1560 already got. In particular, regenerate_decl_from_template calls
1561 duplicate_decls which will update the specialization list. But,
1562 we'll still get called again here anyhow. It's more convenient
1563 to simply allow this than to try to prevent it. */
1564 if (fn == spec)
1565 return spec;
1566 else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1568 if (DECL_TEMPLATE_INSTANTIATION (fn))
1570 if (DECL_ODR_USED (fn)
1571 || DECL_EXPLICIT_INSTANTIATION (fn))
1573 error ("specialization of %qD after instantiation",
1574 fn);
1575 return error_mark_node;
1577 else
1579 tree clone;
1580 /* This situation should occur only if the first
1581 specialization is an implicit instantiation, the
1582 second is an explicit specialization, and the
1583 implicit instantiation has not yet been used. That
1584 situation can occur if we have implicitly
1585 instantiated a member function and then specialized
1586 it later.
1588 We can also wind up here if a friend declaration that
1589 looked like an instantiation turns out to be a
1590 specialization:
1592 template <class T> void foo(T);
1593 class S { friend void foo<>(int) };
1594 template <> void foo(int);
1596 We transform the existing DECL in place so that any
1597 pointers to it become pointers to the updated
1598 declaration.
1600 If there was a definition for the template, but not
1601 for the specialization, we want this to look as if
1602 there were no definition, and vice versa. */
1603 DECL_INITIAL (fn) = NULL_TREE;
1604 duplicate_decls (spec, fn, /*hiding=*/is_friend);
1606 /* The call to duplicate_decls will have applied
1607 [temp.expl.spec]:
1609 An explicit specialization of a function template
1610 is inline only if it is explicitly declared to be,
1611 and independently of whether its function template
1614 to the primary function; now copy the inline bits to
1615 the various clones. */
1616 FOR_EACH_CLONE (clone, fn)
1618 DECL_DECLARED_INLINE_P (clone)
1619 = DECL_DECLARED_INLINE_P (fn);
1620 DECL_SOURCE_LOCATION (clone)
1621 = DECL_SOURCE_LOCATION (fn);
1622 DECL_DELETED_FN (clone)
1623 = DECL_DELETED_FN (fn);
1625 check_specialization_namespace (tmpl);
1627 return fn;
1630 else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1632 tree dd = duplicate_decls (spec, fn, /*hiding=*/is_friend);
1633 if (dd == error_mark_node)
1634 /* We've already complained in duplicate_decls. */
1635 return error_mark_node;
1637 if (dd == NULL_TREE && DECL_INITIAL (spec))
1638 /* Dup decl failed, but this is a new definition. Set the
1639 line number so any errors match this new
1640 definition. */
1641 DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1643 return fn;
1646 else if (fn)
1647 return duplicate_decls (spec, fn, /*hiding=*/is_friend);
1649 /* A specialization must be declared in the same namespace as the
1650 template it is specializing. */
1651 if (DECL_P (spec) && DECL_TEMPLATE_SPECIALIZATION (spec)
1652 && !check_specialization_namespace (tmpl))
1653 DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1655 spec_entry *entry = ggc_alloc<spec_entry> ();
1656 gcc_assert (tmpl && args && spec);
1657 *entry = elt;
1658 *slot = entry;
1659 if ((TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1660 && PRIMARY_TEMPLATE_P (tmpl)
1661 && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1662 || variable_template_p (tmpl))
1663 /* If TMPL is a forward declaration of a template function, keep a list
1664 of all specializations in case we need to reassign them to a friend
1665 template later in tsubst_friend_function.
1667 Also keep a list of all variable template instantiations so that
1668 process_partial_specialization can check whether a later partial
1669 specialization would have used it. */
1670 DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1671 = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1673 return spec;
1676 /* Restricts tree and type comparisons. */
1677 int comparing_specializations;
1678 int comparing_dependent_aliases;
1680 /* Whether we are comparing template arguments during partial ordering
1681 (and therefore want the comparison to look through dependent alias
1682 template specializations). */
1684 static int comparing_for_partial_ordering;
1686 /* Returns true iff two spec_entry nodes are equivalent. */
1688 bool
1689 spec_hasher::equal (spec_entry *e1, spec_entry *e2)
1691 int equal;
1693 ++comparing_specializations;
1694 ++comparing_dependent_aliases;
1695 ++processing_template_decl;
1696 equal = (e1->tmpl == e2->tmpl
1697 && comp_template_args (e1->args, e2->args));
1698 if (equal && flag_concepts
1699 /* tmpl could be a FIELD_DECL for a capture pack. */
1700 && TREE_CODE (e1->tmpl) == TEMPLATE_DECL
1701 && VAR_P (DECL_TEMPLATE_RESULT (e1->tmpl))
1702 && uses_template_parms (e1->args))
1704 /* Partial specializations of a variable template can be distinguished by
1705 constraints. */
1706 tree c1 = e1->spec ? get_constraints (e1->spec) : NULL_TREE;
1707 tree c2 = e2->spec ? get_constraints (e2->spec) : NULL_TREE;
1708 equal = equivalent_constraints (c1, c2);
1710 --processing_template_decl;
1711 --comparing_dependent_aliases;
1712 --comparing_specializations;
1714 return equal;
1717 /* Returns a hash for a template TMPL and template arguments ARGS. */
1719 static hashval_t
1720 hash_tmpl_and_args (tree tmpl, tree args)
1722 hashval_t val = iterative_hash_object (DECL_UID (tmpl), 0);
1723 return iterative_hash_template_arg (args, val);
1726 hashval_t
1727 spec_hasher::hash (tree tmpl, tree args)
1729 ++comparing_specializations;
1730 hashval_t val = hash_tmpl_and_args (tmpl, args);
1731 --comparing_specializations;
1732 return val;
1735 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1736 ignoring SPEC. */
1738 hashval_t
1739 spec_hasher::hash (spec_entry *e)
1741 if (e->hash == 0)
1742 e->hash = hash (e->tmpl, e->args);
1743 return e->hash;
1746 /* Recursively calculate a hash value for a template argument ARG, for use
1747 in the hash tables of template specializations. We must be
1748 careful to (at least) skip the same entities template_args_equal
1749 does. */
1751 hashval_t
1752 iterative_hash_template_arg (tree arg, hashval_t val)
1754 if (arg == NULL_TREE)
1755 return iterative_hash_hashval_t (0, val);
1757 if (!TYPE_P (arg))
1758 /* Strip nop-like things, but not the same as STRIP_NOPS. */
1759 while (CONVERT_EXPR_P (arg)
1760 || TREE_CODE (arg) == NON_LVALUE_EXPR
1761 || class_nttp_const_wrapper_p (arg))
1762 arg = TREE_OPERAND (arg, 0);
1764 enum tree_code code = TREE_CODE (arg);
1766 val = iterative_hash_hashval_t (code, val);
1768 switch (code)
1770 case ARGUMENT_PACK_SELECT:
1771 /* Getting here with an ARGUMENT_PACK_SELECT means we're probably
1772 preserving it in a hash table, which is bad because it will change
1773 meaning when gen_elem_of_pack_expansion_instantiation changes the
1774 ARGUMENT_PACK_SELECT_INDEX. */
1775 gcc_unreachable ();
1777 case ERROR_MARK:
1778 return val;
1780 case IDENTIFIER_NODE:
1781 return iterative_hash_hashval_t (IDENTIFIER_HASH_VALUE (arg), val);
1783 case TREE_VEC:
1784 for (tree elt : tree_vec_range (arg))
1785 val = iterative_hash_template_arg (elt, val);
1786 return val;
1788 case TYPE_PACK_EXPANSION:
1789 case EXPR_PACK_EXPANSION:
1790 val = iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1791 return iterative_hash_template_arg (PACK_EXPANSION_EXTRA_ARGS (arg), val);
1793 case TYPE_ARGUMENT_PACK:
1794 case NONTYPE_ARGUMENT_PACK:
1795 return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1797 case TREE_LIST:
1798 for (; arg; arg = TREE_CHAIN (arg))
1799 val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1800 return val;
1802 case OVERLOAD:
1803 for (lkp_iterator iter (arg); iter; ++iter)
1804 val = iterative_hash_template_arg (*iter, val);
1805 return val;
1807 case CONSTRUCTOR:
1809 iterative_hash_template_arg (TREE_TYPE (arg), val);
1810 for (auto &e: CONSTRUCTOR_ELTS (arg))
1812 val = iterative_hash_template_arg (e.index, val);
1813 val = iterative_hash_template_arg (e.value, val);
1815 return val;
1818 case PARM_DECL:
1819 if (!DECL_ARTIFICIAL (arg))
1821 val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1822 val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
1824 return iterative_hash_template_arg (TREE_TYPE (arg), val);
1826 case TEMPLATE_DECL:
1827 if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg))
1828 return iterative_hash_template_arg (TREE_TYPE (arg), val);
1829 break;
1831 case TARGET_EXPR:
1832 return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1834 case PTRMEM_CST:
1835 val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1836 return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1838 case TEMPLATE_PARM_INDEX:
1839 val = iterative_hash_template_arg
1840 (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1841 val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1842 return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1844 case TRAIT_EXPR:
1845 val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1846 val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1847 return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1849 case BASELINK:
1850 val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1851 val);
1852 return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1853 val);
1855 case MODOP_EXPR:
1856 val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1857 code = TREE_CODE (TREE_OPERAND (arg, 1));
1858 val = iterative_hash_object (code, val);
1859 return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1861 case LAMBDA_EXPR:
1862 /* [temp.over.link] Two lambda-expressions are never considered
1863 equivalent.
1865 So just hash the closure type. */
1866 return iterative_hash_template_arg (TREE_TYPE (arg), val);
1868 case CAST_EXPR:
1869 case IMPLICIT_CONV_EXPR:
1870 case STATIC_CAST_EXPR:
1871 case REINTERPRET_CAST_EXPR:
1872 case CONST_CAST_EXPR:
1873 case DYNAMIC_CAST_EXPR:
1874 case NEW_EXPR:
1875 val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1876 /* Now hash operands as usual. */
1877 break;
1879 case CALL_EXPR:
1881 tree fn = CALL_EXPR_FN (arg);
1882 if (tree name = call_expr_dependent_name (arg))
1884 if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
1885 val = iterative_hash_template_arg (TREE_OPERAND (fn, 1), val);
1886 fn = name;
1888 val = iterative_hash_template_arg (fn, val);
1889 call_expr_arg_iterator ai;
1890 for (tree x = first_call_expr_arg (arg, &ai); x;
1891 x = next_call_expr_arg (&ai))
1892 val = iterative_hash_template_arg (x, val);
1893 return val;
1896 default:
1897 break;
1900 char tclass = TREE_CODE_CLASS (code);
1901 switch (tclass)
1903 case tcc_type:
1904 if (tree ats = alias_template_specialization_p (arg, nt_transparent))
1906 // We want an alias specialization that survived strip_typedefs
1907 // to hash differently from its TYPE_CANONICAL, to avoid hash
1908 // collisions that compare as different in template_args_equal.
1909 // These could be dependent specializations that strip_typedefs
1910 // left alone, or untouched specializations because
1911 // coerce_template_parms returns the unconverted template
1912 // arguments if it sees incomplete argument packs.
1913 tree ti = TYPE_ALIAS_TEMPLATE_INFO (ats);
1914 return hash_tmpl_and_args (TI_TEMPLATE (ti), TI_ARGS (ti));
1917 switch (code)
1919 case DECLTYPE_TYPE:
1920 val = iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1921 break;
1923 case TYPENAME_TYPE:
1924 if (comparing_specializations)
1926 /* Hash the components that are relevant to TYPENAME_TYPE
1927 equivalence as determined by structural_comptypes. We
1928 can only coherently do this when comparing_specializations
1929 is set, because otherwise structural_comptypes tries
1930 resolving TYPENAME_TYPE via the current instantiation. */
1931 tree context = TYPE_MAIN_VARIANT (TYPE_CONTEXT (arg));
1932 tree fullname = TYPENAME_TYPE_FULLNAME (arg);
1933 val = iterative_hash_template_arg (context, val);
1934 val = iterative_hash_template_arg (fullname, val);
1936 break;
1938 default:
1939 if (tree canonical = TYPE_CANONICAL (arg))
1940 val = iterative_hash_hashval_t (TYPE_HASH (canonical), val);
1941 else if (tree ti = TYPE_TEMPLATE_INFO (arg))
1943 val = iterative_hash_template_arg (TI_TEMPLATE (ti), val);
1944 val = iterative_hash_template_arg (TI_ARGS (ti), val);
1946 break;
1949 return val;
1951 case tcc_declaration:
1952 case tcc_constant:
1953 return iterative_hash_expr (arg, val);
1955 default:
1956 gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1957 for (int i = 0, n = cp_tree_operand_length (arg); i < n; ++i)
1958 val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1959 return val;
1963 /* Unregister the specialization SPEC as a specialization of TMPL.
1964 Replace it with NEW_SPEC, if NEW_SPEC is non-NULL. Returns true
1965 if the SPEC was listed as a specialization of TMPL.
1967 Note that SPEC has been ggc_freed, so we can't look inside it. */
1969 bool
1970 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1972 spec_entry *entry;
1973 spec_entry elt;
1975 elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1976 elt.args = TI_ARGS (tinfo);
1978 entry = decl_specializations->find (&elt);
1979 if (entry != NULL)
1981 gcc_assert (entry->spec == spec || entry->spec == new_spec);
1982 gcc_assert (new_spec != NULL_TREE);
1983 entry->spec = new_spec;
1984 return 1;
1987 return 0;
1990 /* Like register_specialization, but for local declarations. We are
1991 registering SPEC, an instantiation of TMPL. */
1993 void
1994 register_local_specialization (tree spec, tree tmpl)
1996 gcc_assert (tmpl != spec);
1997 local_specializations->put (tmpl, spec);
2000 /* Registers T as a specialization of itself. This is used to preserve
2001 the references to already-parsed parameters when instantiating
2002 postconditions. */
2004 void
2005 register_local_identity (tree t)
2007 local_specializations->put (t, t);
2010 /* TYPE is a class type. Returns true if TYPE is an explicitly
2011 specialized class. */
2013 bool
2014 explicit_class_specialization_p (tree type)
2016 if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
2017 return false;
2018 return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
2021 /* Print the list of functions at FNS, going through all the overloads
2022 for each element of the list. Alternatively, FNS cannot be a
2023 TREE_LIST, in which case it will be printed together with all the
2024 overloads.
2026 MORE and *STR should respectively be FALSE and NULL when the function
2027 is called from the outside. They are used internally on recursive
2028 calls. print_candidates manages the two parameters and leaves NULL
2029 in *STR when it ends. */
2031 static void
2032 print_candidates_1 (tree fns, char **str, bool more = false)
2034 if (TREE_CODE (fns) == TREE_LIST)
2035 for (; fns; fns = TREE_CHAIN (fns))
2036 print_candidates_1 (TREE_VALUE (fns), str, more || TREE_CHAIN (fns));
2037 else
2038 for (lkp_iterator iter (fns); iter;)
2040 tree cand = *iter;
2041 ++iter;
2043 const char *pfx = *str;
2044 if (!pfx)
2046 if (more || iter)
2047 pfx = _("candidates are:");
2048 else
2049 pfx = _("candidate is:");
2050 *str = get_spaces (pfx);
2052 inform (DECL_SOURCE_LOCATION (cand), "%s %#qD", pfx, cand);
2056 /* Print the list of candidate FNS in an error message. FNS can also
2057 be a TREE_LIST of non-functions in the case of an ambiguous lookup. */
2059 void
2060 print_candidates (tree fns)
2062 char *str = NULL;
2063 print_candidates_1 (fns, &str);
2064 free (str);
2067 /* Get a (possibly) constrained template declaration for the
2068 purpose of ordering candidates. */
2069 static tree
2070 get_template_for_ordering (tree list)
2072 gcc_assert (TREE_CODE (list) == TREE_LIST);
2073 tree f = TREE_VALUE (list);
2074 if (f == NULL_TREE)
2075 /* Also handle a list from resolve_address_of_overloaded_function with the
2076 function in TREE_PURPOSE. */
2077 f = TREE_PURPOSE (list);
2078 if (tree ti = DECL_TEMPLATE_INFO (f))
2079 return TI_TEMPLATE (ti);
2080 return f;
2083 /* Among candidates having the same signature, return the
2084 most constrained or NULL_TREE if there is no best candidate.
2085 If the signatures of candidates vary (e.g., template
2086 specialization vs. member function), then there can be no
2087 most constrained.
2089 Note that we don't compare constraints on the functions
2090 themselves, but rather those of their templates. */
2091 tree
2092 most_constrained_function (tree candidates)
2094 // Try to find the best candidate in a first pass.
2095 tree champ = candidates;
2096 for (tree c = TREE_CHAIN (champ); c; c = TREE_CHAIN (c))
2098 int winner = more_constrained (get_template_for_ordering (champ),
2099 get_template_for_ordering (c));
2100 if (winner == -1)
2101 champ = c; // The candidate is more constrained
2102 else if (winner == 0)
2103 return NULL_TREE; // Neither is more constrained
2106 // Verify that the champ is better than previous candidates.
2107 for (tree c = candidates; c != champ; c = TREE_CHAIN (c)) {
2108 if (!more_constrained (get_template_for_ordering (champ),
2109 get_template_for_ordering (c)))
2110 return NULL_TREE;
2113 return champ;
2117 /* Returns the template (one of the functions given by TEMPLATE_ID)
2118 which can be specialized to match the indicated DECL with the
2119 explicit template args given in TEMPLATE_ID. The DECL may be
2120 NULL_TREE if none is available. In that case, the functions in
2121 TEMPLATE_ID are non-members.
2123 If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
2124 specialization of a member template.
2126 The TEMPLATE_COUNT is the number of references to qualifying
2127 template classes that appeared in the name of the function. See
2128 check_explicit_specialization for a more accurate description.
2130 TSK indicates what kind of template declaration (if any) is being
2131 declared. TSK_TEMPLATE indicates that the declaration given by
2132 DECL, though a FUNCTION_DECL, has template parameters, and is
2133 therefore a template function.
2135 The template args (those explicitly specified and those deduced)
2136 are output in a newly created vector *TARGS_OUT.
2138 If it is impossible to determine the result, an error message is
2139 issued. The error_mark_node is returned to indicate failure. */
2141 static tree
2142 determine_specialization (tree template_id,
2143 tree decl,
2144 tree* targs_out,
2145 int need_member_template,
2146 int template_count,
2147 tmpl_spec_kind tsk)
2149 tree fns;
2150 tree targs;
2151 tree explicit_targs;
2152 tree candidates = NULL_TREE;
2154 /* A TREE_LIST of templates of which DECL may be a specialization.
2155 The TREE_VALUE of each node is a TEMPLATE_DECL. The
2156 corresponding TREE_PURPOSE is the set of template arguments that,
2157 when used to instantiate the template, would produce a function
2158 with the signature of DECL. */
2159 tree templates = NULL_TREE;
2160 int header_count;
2161 cp_binding_level *b;
2163 *targs_out = NULL_TREE;
2165 if (template_id == error_mark_node || decl == error_mark_node)
2166 return error_mark_node;
2168 /* We shouldn't be specializing a member template of an
2169 unspecialized class template; we already gave an error in
2170 check_specialization_scope, now avoid crashing. */
2171 if (!VAR_P (decl)
2172 && template_count && DECL_CLASS_SCOPE_P (decl)
2173 && template_class_depth (DECL_CONTEXT (decl)) > 0)
2175 gcc_assert (errorcount);
2176 return error_mark_node;
2179 fns = TREE_OPERAND (template_id, 0);
2180 explicit_targs = TREE_OPERAND (template_id, 1);
2182 if (fns == error_mark_node)
2183 return error_mark_node;
2185 /* Check for baselinks. */
2186 if (BASELINK_P (fns))
2187 fns = BASELINK_FUNCTIONS (fns);
2189 if (TREE_CODE (decl) == FUNCTION_DECL && !is_overloaded_fn (fns))
2191 error_at (DECL_SOURCE_LOCATION (decl),
2192 "%qD is not a function template", fns);
2193 return error_mark_node;
2195 else if (VAR_P (decl) && !variable_template_p (fns))
2197 error ("%qD is not a variable template", fns);
2198 return error_mark_node;
2201 /* Count the number of template headers specified for this
2202 specialization. */
2203 header_count = 0;
2204 for (b = current_binding_level;
2205 b->kind == sk_template_parms;
2206 b = b->level_chain)
2207 ++header_count;
2209 tree orig_fns = fns;
2210 bool header_mismatch = false;
2212 if (variable_template_p (fns))
2214 tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (fns));
2215 targs = coerce_template_parms (parms, explicit_targs, fns,
2216 tf_warning_or_error);
2217 if (targs != error_mark_node
2218 && constraints_satisfied_p (fns, targs))
2219 templates = tree_cons (targs, fns, templates);
2221 else for (lkp_iterator iter (fns); iter; ++iter)
2223 tree fn = *iter;
2225 if (TREE_CODE (fn) == TEMPLATE_DECL)
2227 tree decl_arg_types;
2228 tree fn_arg_types;
2230 /* In case of explicit specialization, we need to check if
2231 the number of template headers appearing in the specialization
2232 is correct. This is usually done in check_explicit_specialization,
2233 but the check done there cannot be exhaustive when specializing
2234 member functions. Consider the following code:
2236 template <> void A<int>::f(int);
2237 template <> template <> void A<int>::f(int);
2239 Assuming that A<int> is not itself an explicit specialization
2240 already, the first line specializes "f" which is a non-template
2241 member function, whilst the second line specializes "f" which
2242 is a template member function. So both lines are syntactically
2243 correct, and check_explicit_specialization does not reject
2244 them.
2246 Here, we can do better, as we are matching the specialization
2247 against the declarations. We count the number of template
2248 headers, and we check if they match TEMPLATE_COUNT + 1
2249 (TEMPLATE_COUNT is the number of qualifying template classes,
2250 plus there must be another header for the member template
2251 itself).
2253 Notice that if header_count is zero, this is not a
2254 specialization but rather a template instantiation, so there
2255 is no check we can perform here. */
2256 if (header_count && header_count != template_count + 1)
2258 header_mismatch = true;
2259 continue;
2262 /* Check that the number of template arguments at the
2263 innermost level for DECL is the same as for FN. */
2264 if (current_binding_level->kind == sk_template_parms
2265 && !current_binding_level->explicit_spec_p
2266 && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
2267 != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
2268 (current_template_parms))))
2269 continue;
2271 /* DECL might be a specialization of FN. */
2272 decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2273 fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
2275 /* For a non-static member function, we need to make sure
2276 that the const qualification is the same. Since
2277 get_bindings does not try to merge the "this" parameter,
2278 we must do the comparison explicitly. */
2279 if (DECL_IOBJ_MEMBER_FUNCTION_P (fn))
2281 if (!same_type_p (TREE_VALUE (fn_arg_types),
2282 TREE_VALUE (decl_arg_types)))
2283 continue;
2285 /* And the ref-qualification. */
2286 if (type_memfn_rqual (TREE_TYPE (decl))
2287 != type_memfn_rqual (TREE_TYPE (fn)))
2288 continue;
2291 /* Skip the "this" parameter and, for constructors of
2292 classes with virtual bases, the VTT parameter. A
2293 full specialization of a constructor will have a VTT
2294 parameter, but a template never will. */
2295 decl_arg_types
2296 = skip_artificial_parms_for (decl, decl_arg_types);
2297 fn_arg_types
2298 = skip_artificial_parms_for (fn, fn_arg_types);
2300 /* Function templates cannot be specializations; there are
2301 no partial specializations of functions. Therefore, if
2302 the type of DECL does not match FN, there is no
2303 match.
2305 Note that it should never be the case that we have both
2306 candidates added here, and for regular member functions
2307 below. */
2308 if (tsk == tsk_template)
2310 if (!comp_template_parms (DECL_TEMPLATE_PARMS (fn),
2311 current_template_parms))
2312 continue;
2313 if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2314 TREE_TYPE (TREE_TYPE (fn))))
2315 continue;
2316 if (!compparms (fn_arg_types, decl_arg_types))
2317 continue;
2319 tree freq = get_constraints (fn);
2320 tree dreq = get_constraints (decl);
2321 if (!freq != !dreq)
2322 continue;
2323 if (freq)
2325 /* C++20 CA104: Substitute directly into the
2326 constraint-expression. */
2327 tree fargs = DECL_TI_ARGS (fn);
2328 tsubst_flags_t complain = tf_none;
2329 freq = tsubst_constraint_info (freq, fargs, complain, fn);
2330 if (!cp_tree_equal (freq, dreq))
2331 continue;
2334 candidates = tree_cons (NULL_TREE, fn, candidates);
2335 continue;
2338 /* See whether this function might be a specialization of this
2339 template. Suppress access control because we might be trying
2340 to make this specialization a friend, and we have already done
2341 access control for the declaration of the specialization. */
2342 push_deferring_access_checks (dk_no_check);
2343 targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
2344 pop_deferring_access_checks ();
2346 if (!targs)
2347 /* We cannot deduce template arguments that when used to
2348 specialize TMPL will produce DECL. */
2349 continue;
2351 if (uses_template_parms (targs))
2352 /* We deduced something involving 'auto', which isn't a valid
2353 template argument. */
2354 continue;
2356 /* Save this template, and the arguments deduced. */
2357 templates = tree_cons (targs, fn, templates);
2359 else if (need_member_template)
2360 /* FN is an ordinary member function, and we need a
2361 specialization of a member template. */
2363 else if (TREE_CODE (fn) != FUNCTION_DECL)
2364 /* We can get IDENTIFIER_NODEs here in certain erroneous
2365 cases. */
2367 else if (!DECL_FUNCTION_MEMBER_P (fn))
2368 /* This is just an ordinary non-member function. Nothing can
2369 be a specialization of that. */
2371 else if (DECL_ARTIFICIAL (fn))
2372 /* Cannot specialize functions that are created implicitly. */
2374 else
2376 tree decl_arg_types;
2378 /* This is an ordinary member function. However, since
2379 we're here, we can assume its enclosing class is a
2380 template class. For example,
2382 template <typename T> struct S { void f(); };
2383 template <> void S<int>::f() {}
2385 Here, S<int>::f is a non-template, but S<int> is a
2386 template class. If FN has the same type as DECL, we
2387 might be in business. */
2389 if (!DECL_TEMPLATE_INFO (fn))
2390 /* Its enclosing class is an explicit specialization
2391 of a template class. This is not a candidate. */
2392 continue;
2394 if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2395 TREE_TYPE (TREE_TYPE (fn))))
2396 /* The return types differ. */
2397 continue;
2399 /* Adjust the type of DECL in case FN is a static member. */
2400 decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2401 if (DECL_STATIC_FUNCTION_P (fn)
2402 && DECL_IOBJ_MEMBER_FUNCTION_P (decl))
2403 decl_arg_types = TREE_CHAIN (decl_arg_types);
2405 if (!compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
2406 decl_arg_types))
2407 continue;
2409 if (DECL_IOBJ_MEMBER_FUNCTION_P (fn)
2410 && (type_memfn_rqual (TREE_TYPE (decl))
2411 != type_memfn_rqual (TREE_TYPE (fn))))
2412 continue;
2414 // If the deduced arguments do not satisfy the constraints,
2415 // this is not a candidate.
2416 if (flag_concepts && !constraints_satisfied_p (fn))
2417 continue;
2419 // Add the candidate.
2420 candidates = tree_cons (NULL_TREE, fn, candidates);
2424 if (templates && TREE_CHAIN (templates))
2426 /* We have:
2428 [temp.expl.spec]
2430 It is possible for a specialization with a given function
2431 signature to be instantiated from more than one function
2432 template. In such cases, explicit specification of the
2433 template arguments must be used to uniquely identify the
2434 function template specialization being specialized.
2436 Note that here, there's no suggestion that we're supposed to
2437 determine which of the candidate templates is most
2438 specialized. However, we, also have:
2440 [temp.func.order]
2442 Partial ordering of overloaded function template
2443 declarations is used in the following contexts to select
2444 the function template to which a function template
2445 specialization refers:
2447 -- when an explicit specialization refers to a function
2448 template.
2450 So, we do use the partial ordering rules, at least for now.
2451 This extension can only serve to make invalid programs valid,
2452 so it's safe. And, there is strong anecdotal evidence that
2453 the committee intended the partial ordering rules to apply;
2454 the EDG front end has that behavior, and John Spicer claims
2455 that the committee simply forgot to delete the wording in
2456 [temp.expl.spec]. */
2457 tree tmpl = most_specialized_instantiation (templates);
2458 if (tmpl != error_mark_node)
2460 templates = tmpl;
2461 TREE_CHAIN (templates) = NULL_TREE;
2465 // Concepts allows multiple declarations of member functions
2466 // with the same signature. Like above, we need to rely on
2467 // on the partial ordering of those candidates to determine which
2468 // is the best.
2469 if (flag_concepts && candidates && TREE_CHAIN (candidates))
2471 if (tree cand = most_constrained_function (candidates))
2473 candidates = cand;
2474 TREE_CHAIN (cand) = NULL_TREE;
2478 if (templates == NULL_TREE && candidates == NULL_TREE)
2480 auto_diagnostic_group d;
2481 error ("template-id %qD for %q+D does not match any template "
2482 "declaration", template_id, decl);
2483 if (header_mismatch)
2484 inform (DECL_SOURCE_LOCATION (decl),
2485 "saw %d %<template<>%>, need %d for "
2486 "specializing a member function template",
2487 header_count, template_count + 1);
2488 print_candidates (orig_fns);
2489 return error_mark_node;
2491 else if ((templates && TREE_CHAIN (templates))
2492 || (candidates && TREE_CHAIN (candidates))
2493 || (templates && candidates))
2495 auto_diagnostic_group d;
2496 error ("ambiguous template specialization %qD for %q+D",
2497 template_id, decl);
2498 candidates = chainon (candidates, templates);
2499 print_candidates (candidates);
2500 return error_mark_node;
2503 /* We have one, and exactly one, match. */
2504 if (candidates)
2506 tree fn = TREE_VALUE (candidates);
2507 *targs_out = copy_node (DECL_TI_ARGS (fn));
2509 /* Propagate the candidate's constraints to the declaration. */
2510 if (tsk != tsk_template)
2511 set_constraints (decl, get_constraints (fn));
2513 /* DECL is a re-declaration or partial instantiation of a template
2514 function. */
2515 if (TREE_CODE (fn) == TEMPLATE_DECL)
2516 return fn;
2517 /* It was a specialization of an ordinary member function in a
2518 template class. */
2519 return DECL_TI_TEMPLATE (fn);
2522 /* It was a specialization of a template. */
2523 tree tmpl = TREE_VALUE (templates);
2524 *targs_out = add_outermost_template_args (tmpl, TREE_PURPOSE (templates));
2526 /* Propagate the template's constraints to the declaration. */
2527 if (tsk != tsk_template)
2528 set_constraints (decl, get_constraints (tmpl));
2530 return tmpl;
2533 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2534 but with the default argument values filled in from those in the
2535 TMPL_TYPES. */
2537 static tree
2538 copy_default_args_to_explicit_spec_1 (tree spec_types,
2539 tree tmpl_types)
2541 tree new_spec_types;
2543 if (!spec_types)
2544 return NULL_TREE;
2546 if (spec_types == void_list_node)
2547 return void_list_node;
2549 /* Substitute into the rest of the list. */
2550 new_spec_types =
2551 copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2552 TREE_CHAIN (tmpl_types));
2554 /* Add the default argument for this parameter. */
2555 return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2556 TREE_VALUE (spec_types),
2557 new_spec_types);
2560 /* DECL is an explicit specialization. Replicate default arguments
2561 from the template it specializes. (That way, code like:
2563 template <class T> void f(T = 3);
2564 template <> void f(double);
2565 void g () { f (); }
2567 works, as required.) An alternative approach would be to look up
2568 the correct default arguments at the call-site, but this approach
2569 is consistent with how implicit instantiations are handled. */
2571 static void
2572 copy_default_args_to_explicit_spec (tree decl)
2574 tree tmpl;
2575 tree spec_types;
2576 tree tmpl_types;
2577 tree new_spec_types;
2578 tree old_type;
2579 tree new_type;
2580 tree t;
2581 tree object_type = NULL_TREE;
2582 tree in_charge = NULL_TREE;
2583 tree vtt = NULL_TREE;
2585 /* See if there's anything we need to do. */
2586 tmpl = DECL_TI_TEMPLATE (decl);
2587 tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2588 for (t = tmpl_types; t; t = TREE_CHAIN (t))
2589 if (TREE_PURPOSE (t))
2590 break;
2591 if (!t)
2592 return;
2594 old_type = TREE_TYPE (decl);
2595 spec_types = TYPE_ARG_TYPES (old_type);
2597 if (DECL_IOBJ_MEMBER_FUNCTION_P (decl))
2599 /* Remove the this pointer, but remember the object's type for
2600 CV quals. */
2601 object_type = TREE_TYPE (TREE_VALUE (spec_types));
2602 spec_types = TREE_CHAIN (spec_types);
2603 tmpl_types = TREE_CHAIN (tmpl_types);
2605 if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2607 /* DECL may contain more parameters than TMPL due to the extra
2608 in-charge parameter in constructors and destructors. */
2609 in_charge = spec_types;
2610 spec_types = TREE_CHAIN (spec_types);
2612 if (DECL_HAS_VTT_PARM_P (decl))
2614 vtt = spec_types;
2615 spec_types = TREE_CHAIN (spec_types);
2619 /* Compute the merged default arguments. */
2620 new_spec_types =
2621 copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2623 /* Compute the new FUNCTION_TYPE. */
2624 if (object_type)
2626 if (vtt)
2627 new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2628 TREE_VALUE (vtt),
2629 new_spec_types);
2631 if (in_charge)
2632 /* Put the in-charge parameter back. */
2633 new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2634 TREE_VALUE (in_charge),
2635 new_spec_types);
2637 new_type = build_method_type_directly (object_type,
2638 TREE_TYPE (old_type),
2639 new_spec_types);
2641 else
2642 new_type = build_function_type (TREE_TYPE (old_type),
2643 new_spec_types);
2644 new_type = cp_build_type_attribute_variant (new_type,
2645 TYPE_ATTRIBUTES (old_type));
2646 new_type = cxx_copy_lang_qualifiers (new_type, old_type);
2648 TREE_TYPE (decl) = new_type;
2651 /* Return the number of template headers we expect to see for a definition
2652 or specialization of CTYPE or one of its non-template members. */
2655 num_template_headers_for_class (tree ctype)
2657 int num_templates = 0;
2659 while (ctype && CLASS_TYPE_P (ctype))
2661 /* You're supposed to have one `template <...>' for every
2662 template class, but you don't need one for a full
2663 specialization. For example:
2665 template <class T> struct S{};
2666 template <> struct S<int> { void f(); };
2667 void S<int>::f () {}
2669 is correct; there shouldn't be a `template <>' for the
2670 definition of `S<int>::f'. */
2671 if (!CLASSTYPE_TEMPLATE_INFO (ctype))
2672 /* If CTYPE does not have template information of any
2673 kind, then it is not a template, nor is it nested
2674 within a template. */
2675 break;
2676 if (explicit_class_specialization_p (ctype))
2677 break;
2678 if (PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (ctype)))
2679 ++num_templates;
2681 ctype = TYPE_CONTEXT (ctype);
2684 return num_templates;
2687 /* Do a simple sanity check on the template headers that precede the
2688 variable declaration DECL. */
2690 void
2691 check_template_variable (tree decl)
2693 tree ctx = CP_DECL_CONTEXT (decl);
2694 int wanted = num_template_headers_for_class (ctx);
2695 if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)
2696 && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl)))
2698 if (cxx_dialect < cxx14)
2699 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wc__14_extensions,
2700 "variable templates only available with "
2701 "%<-std=c++14%> or %<-std=gnu++14%>");
2703 // Namespace-scope variable templates should have a template header.
2704 ++wanted;
2706 if (template_header_count > wanted)
2708 auto_diagnostic_group d;
2709 bool warned = pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2710 "too many template headers for %qD "
2711 "(should be %d)",
2712 decl, wanted);
2713 if (warned && CLASS_TYPE_P (ctx)
2714 && CLASSTYPE_TEMPLATE_SPECIALIZATION (ctx))
2715 inform (DECL_SOURCE_LOCATION (decl),
2716 "members of an explicitly specialized class are defined "
2717 "without a template header");
2721 /* An explicit specialization whose declarator-id or class-head-name is not
2722 qualified shall be declared in the nearest enclosing namespace of the
2723 template, or, if the namespace is inline (7.3.1), any namespace from its
2724 enclosing namespace set.
2726 If the name declared in the explicit instantiation is an unqualified name,
2727 the explicit instantiation shall appear in the namespace where its template
2728 is declared or, if that namespace is inline (7.3.1), any namespace from its
2729 enclosing namespace set. */
2731 void
2732 check_unqualified_spec_or_inst (tree t, location_t loc)
2734 tree tmpl = most_general_template (t);
2735 if (DECL_NAMESPACE_SCOPE_P (tmpl)
2736 && !is_nested_namespace (current_namespace,
2737 CP_DECL_CONTEXT (tmpl), true))
2739 if (processing_specialization)
2740 permerror (loc, "explicit specialization of %qD outside its "
2741 "namespace must use a nested-name-specifier", tmpl);
2742 else if (processing_explicit_instantiation
2743 && cxx_dialect >= cxx11)
2744 /* This was allowed in C++98, so only pedwarn. */
2745 pedwarn (loc, OPT_Wpedantic, "explicit instantiation of %qD "
2746 "outside its namespace must use a nested-name-"
2747 "specifier", tmpl);
2751 /* Warn for a template specialization SPEC that is missing some of a set
2752 of function or type attributes that the template TEMPL is declared with.
2753 ATTRLIST is a list of additional attributes that SPEC should be taken
2754 to ultimately be declared with. */
2756 static void
2757 warn_spec_missing_attributes (tree tmpl, tree spec, tree attrlist)
2759 if (DECL_FUNCTION_TEMPLATE_P (tmpl))
2760 tmpl = DECL_TEMPLATE_RESULT (tmpl);
2762 /* Avoid warning if the difference between the primary and
2763 the specialization is not in one of the attributes below. */
2764 const char* const blacklist[] = {
2765 "alloc_align", "alloc_size", "assume_aligned", "format",
2766 "format_arg", "malloc", "nonnull", NULL
2769 /* Put together a list of the black listed attributes that the primary
2770 template is declared with that the specialization is not, in case
2771 it's not apparent from the most recent declaration of the primary. */
2772 auto_vec<const char *> mismatches;
2773 unsigned nattrs = decls_mismatched_attributes (tmpl, spec, attrlist,
2774 blacklist, mismatches);
2776 if (!nattrs)
2777 return;
2779 auto_diagnostic_group d;
2780 if (warning_at (DECL_SOURCE_LOCATION (spec), OPT_Wmissing_attributes,
2781 "explicit specialization %q#D may be missing attributes",
2782 spec))
2784 pp_markup::comma_separated_quoted_strings e (mismatches);
2785 inform (DECL_SOURCE_LOCATION (tmpl),
2786 nattrs > 1
2787 ? G_("missing primary template attributes %e")
2788 : G_("missing primary template attribute %e"),
2789 &e);
2793 /* Check to see if the function just declared, as indicated in
2794 DECLARATOR, and in DECL, is a specialization of a function
2795 template. We may also discover that the declaration is an explicit
2796 instantiation at this point.
2798 Returns DECL, or an equivalent declaration that should be used
2799 instead if all goes well. Issues an error message if something is
2800 amiss. Returns error_mark_node if the error is not easily
2801 recoverable.
2803 FLAGS is a bitmask consisting of the following flags:
2805 2: The function has a definition.
2806 4: The function is a friend.
2808 The TEMPLATE_COUNT is the number of references to qualifying
2809 template classes that appeared in the name of the function. For
2810 example, in
2812 template <class T> struct S { void f(); };
2813 void S<int>::f();
2815 the TEMPLATE_COUNT would be 1. However, explicitly specialized
2816 classes are not counted in the TEMPLATE_COUNT, so that in
2818 template <class T> struct S {};
2819 template <> struct S<int> { void f(); }
2820 template <> void S<int>::f();
2822 the TEMPLATE_COUNT would be 0. (Note that this declaration is
2823 invalid; there should be no template <>.)
2825 If the function is a specialization, it is marked as such via
2826 DECL_TEMPLATE_SPECIALIZATION. Furthermore, its DECL_TEMPLATE_INFO
2827 is set up correctly, and it is added to the list of specializations
2828 for that template. */
2830 tree
2831 check_explicit_specialization (tree declarator,
2832 tree decl,
2833 int template_count,
2834 int flags,
2835 tree attrlist)
2837 int have_def = flags & 2;
2838 int is_friend = flags & 4;
2839 bool is_concept = flags & 8;
2840 int specialization = 0;
2841 int explicit_instantiation = 0;
2842 int member_specialization = 0;
2843 tree ctype = DECL_CLASS_CONTEXT (decl);
2844 tree dname = DECL_NAME (decl);
2845 tmpl_spec_kind tsk;
2847 if (is_friend)
2849 if (!processing_specialization)
2850 tsk = tsk_none;
2851 else
2852 tsk = tsk_excessive_parms;
2854 else
2855 tsk = current_tmpl_spec_kind (template_count);
2857 switch (tsk)
2859 case tsk_none:
2860 if (processing_specialization && !VAR_P (decl))
2862 specialization = 1;
2863 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2865 else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR
2866 || (DECL_LANG_SPECIFIC (decl)
2867 && DECL_IMPLICIT_INSTANTIATION (decl)))
2869 if (is_friend)
2870 /* This could be something like:
2872 template <class T> void f(T);
2873 class S { friend void f<>(int); } */
2874 specialization = 1;
2875 else
2877 /* This case handles bogus declarations like template <>
2878 template <class T> void f<int>(); */
2880 error_at (cp_expr_loc_or_input_loc (declarator),
2881 "template-id %qE in declaration of primary template",
2882 declarator);
2883 return decl;
2886 break;
2888 case tsk_invalid_member_spec:
2889 /* The error has already been reported in
2890 check_specialization_scope. */
2891 return error_mark_node;
2893 case tsk_invalid_expl_inst:
2894 error ("template parameter list used in explicit instantiation");
2896 /* Fall through. */
2898 case tsk_expl_inst:
2899 if (have_def)
2900 error ("definition provided for explicit instantiation");
2902 explicit_instantiation = 1;
2903 break;
2905 case tsk_excessive_parms:
2906 case tsk_insufficient_parms:
2907 if (tsk == tsk_excessive_parms)
2908 error ("too many template parameter lists in declaration of %qD",
2909 decl);
2910 else if (template_header_count)
2911 error("too few template parameter lists in declaration of %qD", decl);
2912 else
2913 error("explicit specialization of %qD must be introduced by "
2914 "%<template <>%>", decl);
2916 /* Fall through. */
2917 case tsk_expl_spec:
2918 if (is_concept)
2919 error ("explicit specialization declared %<concept%>");
2921 if (VAR_P (decl) && TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2922 /* In cases like template<> constexpr bool v = true;
2923 We'll give an error in check_template_variable. */
2924 break;
2926 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2927 if (ctype)
2928 member_specialization = 1;
2929 else
2930 specialization = 1;
2931 break;
2933 case tsk_template:
2934 if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2936 /* This case handles bogus declarations like template <>
2937 template <class T> void f<int>(); */
2939 if (!uses_template_parms (TREE_OPERAND (declarator, 1)))
2940 error_at (cp_expr_loc_or_input_loc (declarator),
2941 "template-id %qE in declaration of primary template",
2942 declarator);
2943 else if (variable_template_p (TREE_OPERAND (declarator, 0)))
2945 /* Partial specialization of variable template. */
2946 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2947 specialization = 1;
2948 goto ok;
2950 else if (cxx_dialect < cxx14)
2951 error_at (cp_expr_loc_or_input_loc (declarator),
2952 "non-type partial specialization %qE "
2953 "is not allowed", declarator);
2954 else
2955 error_at (cp_expr_loc_or_input_loc (declarator),
2956 "non-class, non-variable partial specialization %qE "
2957 "is not allowed", declarator);
2958 return decl;
2959 ok:;
2962 if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2963 /* This is a specialization of a member template, without
2964 specialization the containing class. Something like:
2966 template <class T> struct S {
2967 template <class U> void f (U);
2969 template <> template <class U> void S<int>::f(U) {}
2971 That's a specialization -- but of the entire template. */
2972 specialization = 1;
2973 break;
2975 default:
2976 gcc_unreachable ();
2979 if ((specialization || member_specialization)
2980 /* This doesn't apply to variable templates. */
2981 && FUNC_OR_METHOD_TYPE_P (TREE_TYPE (decl)))
2983 tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2984 for (; t; t = TREE_CHAIN (t))
2985 if (TREE_PURPOSE (t))
2987 permerror (input_location,
2988 "default argument specified in explicit specialization");
2989 break;
2993 if (specialization || member_specialization || explicit_instantiation)
2995 tree tmpl = NULL_TREE;
2996 tree targs = NULL_TREE;
2997 bool was_template_id = (TREE_CODE (declarator) == TEMPLATE_ID_EXPR);
2998 bool found_hidden = false;
3000 /* Make sure that the declarator is a TEMPLATE_ID_EXPR. */
3001 if (!was_template_id)
3003 tree fns;
3005 gcc_assert (identifier_p (declarator));
3006 if (ctype)
3007 fns = dname;
3008 else
3010 /* If there is no class context, the explicit instantiation
3011 must be at namespace scope. */
3012 gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
3014 /* Find the namespace binding, using the declaration
3015 context. */
3016 fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
3017 LOOK_want::NORMAL, true);
3018 if (fns == error_mark_node)
3020 /* If lookup fails, look for a friend declaration so we can
3021 give a better diagnostic. */
3022 fns = (lookup_qualified_name
3023 (CP_DECL_CONTEXT (decl), dname,
3024 LOOK_want::NORMAL | LOOK_want::HIDDEN_FRIEND,
3025 /*complain*/true));
3026 found_hidden = true;
3029 if (fns == error_mark_node || !is_overloaded_fn (fns))
3031 error ("%qD is not a template function", dname);
3032 fns = error_mark_node;
3036 declarator = lookup_template_function (fns, NULL_TREE);
3039 if (declarator == error_mark_node)
3040 return error_mark_node;
3042 if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
3044 if (!explicit_instantiation)
3045 /* A specialization in class scope. This is invalid,
3046 but the error will already have been flagged by
3047 check_specialization_scope. */
3048 return error_mark_node;
3049 else
3051 /* It's not valid to write an explicit instantiation in
3052 class scope, e.g.:
3054 class C { template void f(); }
3056 This case is caught by the parser. However, on
3057 something like:
3059 template class C { void f(); };
3061 (which is invalid) we can get here. The error will be
3062 issued later. */
3066 return decl;
3068 else if (ctype != NULL_TREE
3069 && (identifier_p (TREE_OPERAND (declarator, 0))))
3071 // We'll match variable templates in start_decl.
3072 if (VAR_P (decl))
3073 return decl;
3075 /* Find the list of functions in ctype that have the same
3076 name as the declared function. */
3077 tree name = TREE_OPERAND (declarator, 0);
3079 if (constructor_name_p (name, ctype))
3081 if (DECL_CONSTRUCTOR_P (decl)
3082 ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
3083 : !CLASSTYPE_DESTRUCTOR (ctype))
3085 /* From [temp.expl.spec]:
3087 If such an explicit specialization for the member
3088 of a class template names an implicitly-declared
3089 special member function (clause _special_), the
3090 program is ill-formed.
3092 Similar language is found in [temp.explicit]. */
3093 error ("specialization of implicitly-declared special member function");
3094 return error_mark_node;
3097 name = DECL_NAME (decl);
3100 /* For a type-conversion operator, We might be looking for
3101 `operator int' which will be a specialization of
3102 `operator T'. Grab all the conversion operators, and
3103 then select from them. */
3104 tree fns = get_class_binding (ctype, IDENTIFIER_CONV_OP_P (name)
3105 ? conv_op_identifier : name);
3107 if (fns == NULL_TREE)
3109 error ("no member function %qD declared in %qT", name, ctype);
3110 return error_mark_node;
3112 else
3113 TREE_OPERAND (declarator, 0) = fns;
3116 /* Figure out what exactly is being specialized at this point.
3117 Note that for an explicit instantiation, even one for a
3118 member function, we cannot tell a priori whether the
3119 instantiation is for a member template, or just a member
3120 function of a template class. Even if a member template is
3121 being instantiated, the member template arguments may be
3122 elided if they can be deduced from the rest of the
3123 declaration. */
3124 tmpl = determine_specialization (declarator, decl,
3125 &targs,
3126 member_specialization,
3127 template_count,
3128 tsk);
3130 if (!tmpl || tmpl == error_mark_node)
3131 /* We couldn't figure out what this declaration was
3132 specializing. */
3133 return error_mark_node;
3134 else
3136 if (found_hidden && TREE_CODE (decl) == FUNCTION_DECL)
3138 auto_diagnostic_group d;
3139 if (pedwarn (DECL_SOURCE_LOCATION (decl), 0,
3140 "friend declaration %qD is not visible to "
3141 "explicit specialization", tmpl))
3142 inform (DECL_SOURCE_LOCATION (tmpl),
3143 "friend declaration here");
3146 if (!ctype && !is_friend
3147 && CP_DECL_CONTEXT (decl) == current_namespace)
3148 check_unqualified_spec_or_inst (tmpl, DECL_SOURCE_LOCATION (decl));
3150 tree gen_tmpl = most_general_template (tmpl);
3152 if (explicit_instantiation)
3154 /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
3155 is done by do_decl_instantiation later. */
3157 int arg_depth = TMPL_ARGS_DEPTH (targs);
3158 int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
3160 if (arg_depth > parm_depth)
3162 /* If TMPL is not the most general template (for
3163 example, if TMPL is a friend template that is
3164 injected into namespace scope), then there will
3165 be too many levels of TARGS. Remove some of them
3166 here. */
3167 int i;
3168 tree new_targs;
3170 new_targs = make_tree_vec (parm_depth);
3171 for (i = arg_depth - parm_depth; i < arg_depth; ++i)
3172 TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
3173 = TREE_VEC_ELT (targs, i);
3174 targs = new_targs;
3177 return instantiate_template (tmpl, targs, tf_error);
3180 /* If we thought that the DECL was a member function, but it
3181 turns out to be specializing a static member function,
3182 make DECL a static member function as well. */
3183 if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3184 && DECL_STATIC_FUNCTION_P (tmpl)
3185 && DECL_IOBJ_MEMBER_FUNCTION_P (decl))
3186 revert_static_member_fn (decl);
3188 /* If this is a specialization of a member template of a
3189 template class, we want to return the TEMPLATE_DECL, not
3190 the specialization of it. */
3191 if (tsk == tsk_template && !was_template_id)
3193 tree result = DECL_TEMPLATE_RESULT (tmpl);
3194 SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3195 DECL_INITIAL (result) = NULL_TREE;
3196 if (have_def)
3198 tree parm;
3199 DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
3200 DECL_SOURCE_LOCATION (result)
3201 = DECL_SOURCE_LOCATION (decl);
3202 /* We want to use the argument list specified in the
3203 definition, not in the original declaration. */
3204 DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
3205 for (parm = DECL_ARGUMENTS (result); parm;
3206 parm = DECL_CHAIN (parm))
3207 DECL_CONTEXT (parm) = result;
3209 decl = register_specialization (tmpl, gen_tmpl, targs,
3210 is_friend, 0);
3211 remove_contract_attributes (result);
3212 return decl;
3215 /* Set up the DECL_TEMPLATE_INFO for DECL. */
3216 DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
3218 if (was_template_id)
3219 TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl)) = true;
3221 /* Inherit default function arguments from the template
3222 DECL is specializing. */
3223 if (DECL_FUNCTION_TEMPLATE_P (tmpl))
3224 copy_default_args_to_explicit_spec (decl);
3226 /* This specialization has the same protection as the
3227 template it specializes. */
3228 TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
3229 TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
3231 /* 7.1.1-1 [dcl.stc]
3233 A storage-class-specifier shall not be specified in an
3234 explicit specialization...
3236 The parser rejects these, so unless action is taken here,
3237 explicit function specializations will always appear with
3238 global linkage.
3240 The action recommended by the C++ CWG in response to C++
3241 defect report 605 is to make the storage class and linkage
3242 of the explicit specialization match the templated function:
3244 http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
3246 if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
3248 tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
3249 gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
3251 /* This specialization has the same linkage and visibility as
3252 the function template it specializes. */
3253 TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
3254 if (! TREE_PUBLIC (decl))
3256 DECL_INTERFACE_KNOWN (decl) = 1;
3257 DECL_NOT_REALLY_EXTERN (decl) = 1;
3259 DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
3260 if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
3262 DECL_VISIBILITY_SPECIFIED (decl) = 1;
3263 DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
3267 /* If DECL is a friend declaration, declared using an
3268 unqualified name, the namespace associated with DECL may
3269 have been set incorrectly. For example, in:
3271 template <typename T> void f(T);
3272 namespace N {
3273 struct S { friend void f<int>(int); }
3276 we will have set the DECL_CONTEXT for the friend
3277 declaration to N, rather than to the global namespace. */
3278 if (DECL_NAMESPACE_SCOPE_P (decl))
3279 DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
3281 if (is_friend && !have_def)
3282 /* This is not really a declaration of a specialization.
3283 It's just the name of an instantiation. But, it's not
3284 a request for an instantiation, either. */
3285 SET_DECL_IMPLICIT_INSTANTIATION (decl);
3286 else if (TREE_CODE (decl) == FUNCTION_DECL)
3287 /* A specialization is not necessarily COMDAT. */
3288 DECL_COMDAT (decl) = (TREE_PUBLIC (decl)
3289 && DECL_DECLARED_INLINE_P (decl));
3290 else if (VAR_P (decl))
3291 DECL_COMDAT (decl) = false;
3293 /* If this is a full specialization, register it so that we can find
3294 it again. Partial specializations will be registered in
3295 process_partial_specialization. */
3296 if (!processing_template_decl)
3298 warn_spec_missing_attributes (gen_tmpl, decl, attrlist);
3300 decl = register_specialization (decl, gen_tmpl, targs,
3301 is_friend, 0);
3304 /* If this is a specialization, splice any contracts that may have
3305 been inherited from the template, removing them. */
3306 if (decl != error_mark_node && DECL_TEMPLATE_SPECIALIZATION (decl))
3307 remove_contract_attributes (decl);
3309 /* A 'structor should already have clones. */
3310 gcc_assert (decl == error_mark_node
3311 || variable_template_p (tmpl)
3312 || !(DECL_CONSTRUCTOR_P (decl)
3313 || DECL_DESTRUCTOR_P (decl))
3314 || DECL_CLONED_FUNCTION_P (DECL_CHAIN (decl)));
3318 return decl;
3321 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
3322 parameters. These are represented in the same format used for
3323 DECL_TEMPLATE_PARMS. */
3326 comp_template_parms (const_tree parms1, const_tree parms2)
3328 if (parms1 == parms2)
3329 return 1;
3331 tree t1 = TREE_VALUE (parms1);
3332 tree t2 = TREE_VALUE (parms2);
3333 int i;
3335 gcc_assert (TREE_CODE (t1) == TREE_VEC);
3336 gcc_assert (TREE_CODE (t2) == TREE_VEC);
3338 if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
3339 return 0;
3341 for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
3343 tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
3344 tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
3346 /* If either of the template parameters are invalid, assume
3347 they match for the sake of error recovery. */
3348 if (error_operand_p (parm1) || error_operand_p (parm2))
3349 return 1;
3351 if (TREE_CODE (parm1) != TREE_CODE (parm2))
3352 return 0;
3354 if (TREE_CODE (parm1) == TYPE_DECL
3355 && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm1))
3356 == TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm2))))
3357 continue;
3358 else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
3359 return 0;
3362 return 1;
3365 /* Returns true if two template parameters are declared with
3366 equivalent constraints. */
3368 static bool
3369 template_parameter_constraints_equivalent_p (const_tree parm1, const_tree parm2)
3371 tree req1 = TREE_TYPE (parm1);
3372 tree req2 = TREE_TYPE (parm2);
3373 if (!req1 != !req2)
3374 return false;
3375 if (req1)
3376 return cp_tree_equal (req1, req2);
3377 return true;
3380 /* Returns true when two template parameters are equivalent. */
3382 static bool
3383 template_parameters_equivalent_p (const_tree parm1, const_tree parm2)
3385 tree decl1 = TREE_VALUE (parm1);
3386 tree decl2 = TREE_VALUE (parm2);
3388 /* If either of the template parameters are invalid, assume
3389 they match for the sake of error recovery. */
3390 if (error_operand_p (decl1) || error_operand_p (decl2))
3391 return true;
3393 /* ... they declare parameters of the same kind. */
3394 if (TREE_CODE (decl1) != TREE_CODE (decl2))
3395 return false;
3397 /* ... one parameter was introduced by a parameter declaration, then
3398 both are. This case arises as a result of eagerly rewriting declarations
3399 during parsing. */
3400 if (DECL_IMPLICIT_TEMPLATE_PARM_P (decl1)
3401 != DECL_IMPLICIT_TEMPLATE_PARM_P (decl2))
3402 return false;
3404 /* ... if either declares a pack, they both do. */
3405 if (template_parameter_pack_p (decl1) != template_parameter_pack_p (decl2))
3406 return false;
3408 if (TREE_CODE (decl1) == PARM_DECL)
3410 /* ... if they declare non-type parameters, the types are equivalent. */
3411 if (!same_type_p (TREE_TYPE (decl1), TREE_TYPE (decl2)))
3412 return false;
3414 else if (TREE_CODE (decl2) == TEMPLATE_DECL)
3416 /* ... if they declare template template parameters, their template
3417 parameter lists are equivalent. */
3418 if (!template_heads_equivalent_p (decl1, decl2))
3419 return false;
3422 /* ... if they are declared with a qualified-concept name, they both
3423 are, and those names are equivalent. */
3424 return template_parameter_constraints_equivalent_p (parm1, parm2);
3427 /* Returns true if two template parameters lists are equivalent.
3428 Two template parameter lists are equivalent if they have the
3429 same length and their corresponding parameters are equivalent.
3431 PARMS1 and PARMS2 are TREE_LISTs containing TREE_VECs: the
3432 data structure returned by DECL_TEMPLATE_PARMS.
3434 This is generally the same implementation as comp_template_parms
3435 except that it also the concept names and arguments used to
3436 introduce parameters. */
3438 static bool
3439 template_parameter_lists_equivalent_p (const_tree parms1, const_tree parms2)
3441 if (parms1 == parms2)
3442 return true;
3444 tree list1 = TREE_VALUE (parms1);
3445 tree list2 = TREE_VALUE (parms2);
3447 if (TREE_VEC_LENGTH (list1) != TREE_VEC_LENGTH (list2))
3448 return 0;
3450 for (int i = 0; i < TREE_VEC_LENGTH (list2); ++i)
3452 tree parm1 = TREE_VEC_ELT (list1, i);
3453 tree parm2 = TREE_VEC_ELT (list2, i);
3454 if (!template_parameters_equivalent_p (parm1, parm2))
3455 return false;
3458 return true;
3461 /* Return true if the requires-clause of the template parameter lists are
3462 equivalent and false otherwise. */
3463 static bool
3464 template_requirements_equivalent_p (const_tree parms1, const_tree parms2)
3466 tree req1 = TEMPLATE_PARMS_CONSTRAINTS (parms1);
3467 tree req2 = TEMPLATE_PARMS_CONSTRAINTS (parms2);
3468 if ((req1 != NULL_TREE) != (req2 != NULL_TREE))
3469 return false;
3470 if (!cp_tree_equal (req1, req2))
3471 return false;
3472 return true;
3475 /* Returns true if two template heads are equivalent. 17.6.6.1p6:
3476 Two template heads are equivalent if their template parameter
3477 lists are equivalent and their requires clauses are equivalent.
3479 In pre-C++20, this is equivalent to calling comp_template_parms
3480 for the template parameters of TMPL1 and TMPL2. */
3482 bool
3483 template_heads_equivalent_p (const_tree tmpl1, const_tree tmpl2)
3485 tree parms1 = DECL_TEMPLATE_PARMS (tmpl1);
3486 tree parms2 = DECL_TEMPLATE_PARMS (tmpl2);
3488 /* ... have the same number of template parameters, and their
3489 corresponding parameters are equivalent. */
3490 if (!template_parameter_lists_equivalent_p (parms1, parms2))
3491 return false;
3493 /* ... if either has a requires-clause, they both do and their
3494 corresponding constraint-expressions are equivalent. */
3495 return template_requirements_equivalent_p (parms1, parms2);
3498 /* Determine whether PARM is a parameter pack. */
3500 bool
3501 template_parameter_pack_p (const_tree parm)
3503 /* Determine if we have a non-type template parameter pack. */
3504 if (TREE_CODE (parm) == PARM_DECL)
3505 return (DECL_TEMPLATE_PARM_P (parm)
3506 && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
3507 if (TREE_CODE (parm) == TEMPLATE_PARM_INDEX)
3508 return TEMPLATE_PARM_PARAMETER_PACK (parm);
3510 /* If this is a list of template parameters, we could get a
3511 TYPE_DECL or a TEMPLATE_DECL. */
3512 if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
3513 parm = TREE_TYPE (parm);
3515 /* Otherwise it must be a type template parameter. */
3516 return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
3517 || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
3518 && TEMPLATE_TYPE_PARAMETER_PACK (parm));
3521 /* Determine if T is a function parameter pack. */
3523 bool
3524 function_parameter_pack_p (const_tree t)
3526 if (t && TREE_CODE (t) == PARM_DECL)
3527 return DECL_PACK_P (t);
3528 return false;
3531 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
3532 PRIMARY_FUNC_TMPL_INST is a primary function template instantiation. */
3534 tree
3535 get_function_template_decl (const_tree primary_func_tmpl_inst)
3537 if (! primary_func_tmpl_inst
3538 || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
3539 || ! primary_template_specialization_p (primary_func_tmpl_inst))
3540 return NULL;
3542 return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
3545 /* Return true iff the function parameter PARAM_DECL was expanded
3546 from the function parameter pack PACK. */
3548 bool
3549 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
3551 if (DECL_ARTIFICIAL (param_decl)
3552 || !function_parameter_pack_p (pack))
3553 return false;
3555 /* The parameter pack and its pack arguments have the same
3556 DECL_PARM_INDEX. */
3557 return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
3560 /* Determine whether ARGS describes a variadic template args list,
3561 i.e., one that is terminated by a template argument pack. */
3563 static bool
3564 template_args_variadic_p (tree args)
3566 int nargs;
3567 tree last_parm;
3569 if (args == NULL_TREE)
3570 return false;
3572 args = INNERMOST_TEMPLATE_ARGS (args);
3573 nargs = TREE_VEC_LENGTH (args);
3575 if (nargs == 0)
3576 return false;
3578 last_parm = TREE_VEC_ELT (args, nargs - 1);
3580 return ARGUMENT_PACK_P (last_parm);
3583 /* Generate a new name for the parameter pack name NAME (an
3584 IDENTIFIER_NODE) that incorporates its */
3586 static tree
3587 make_ith_pack_parameter_name (tree name, int i)
3589 /* Munge the name to include the parameter index. */
3590 #define NUMBUF_LEN 128
3591 char numbuf[NUMBUF_LEN];
3592 char* newname;
3593 int newname_len;
3595 if (name == NULL_TREE)
3596 return name;
3597 snprintf (numbuf, NUMBUF_LEN, "%i", i);
3598 newname_len = IDENTIFIER_LENGTH (name)
3599 + strlen (numbuf) + 2;
3600 newname = (char*)alloca (newname_len);
3601 snprintf (newname, newname_len,
3602 "%s#%i", IDENTIFIER_POINTER (name), i);
3603 return get_identifier (newname);
3606 /* Return true if T is a primary function, class or alias template
3607 specialization, not including the template pattern. */
3609 bool
3610 primary_template_specialization_p (const_tree t)
3612 if (!t)
3613 return false;
3615 if (VAR_OR_FUNCTION_DECL_P (t))
3616 return (DECL_LANG_SPECIFIC (t)
3617 && DECL_USE_TEMPLATE (t)
3618 && DECL_TEMPLATE_INFO (t)
3619 && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t)));
3620 else if (CLASS_TYPE_P (t) && !TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
3621 return (CLASSTYPE_TEMPLATE_INFO (t)
3622 && CLASSTYPE_USE_TEMPLATE (t)
3623 && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)));
3624 else if (alias_template_specialization_p (t, nt_transparent))
3625 return true;
3626 return false;
3629 /* Return true if PARM is a template template parameter. */
3631 bool
3632 template_template_parameter_p (const_tree parm)
3634 return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
3637 /* Return true iff PARM is a DECL representing a type template
3638 parameter. */
3640 bool
3641 template_type_parameter_p (const_tree parm)
3643 return (parm
3644 && (TREE_CODE (parm) == TYPE_DECL
3645 || TREE_CODE (parm) == TEMPLATE_DECL)
3646 && DECL_TEMPLATE_PARM_P (parm));
3649 /* Return the template parameters of T if T is a
3650 primary template instantiation, NULL otherwise. */
3652 tree
3653 get_primary_template_innermost_parameters (const_tree t)
3655 tree parms = NULL, template_info = NULL;
3657 if ((template_info = get_template_info (t))
3658 && primary_template_specialization_p (t))
3659 parms = INNERMOST_TEMPLATE_PARMS
3660 (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
3662 return parms;
3665 /* Returns the template arguments of T if T is a template instantiation,
3666 NULL otherwise. */
3668 tree
3669 get_template_innermost_arguments (const_tree t)
3671 tree args = NULL, template_info = NULL;
3673 if ((template_info = get_template_info (t))
3674 && TI_ARGS (template_info))
3675 args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
3677 return args;
3680 /* Return the argument pack elements of T if T is a template argument pack,
3681 NULL otherwise. */
3683 tree
3684 get_template_argument_pack_elems (const_tree t)
3686 if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
3687 && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
3688 return NULL;
3690 return ARGUMENT_PACK_ARGS (t);
3693 /* In an ARGUMENT_PACK_SELECT, the actual underlying argument that the
3694 ARGUMENT_PACK_SELECT represents. */
3696 static tree
3697 argument_pack_select_arg (tree t)
3699 tree args = ARGUMENT_PACK_ARGS (ARGUMENT_PACK_SELECT_FROM_PACK (t));
3700 tree arg = TREE_VEC_ELT (args, ARGUMENT_PACK_SELECT_INDEX (t));
3702 /* If the selected argument is an expansion E, that most likely means we were
3703 called from gen_elem_of_pack_expansion_instantiation during the
3704 substituting of an argument pack (of which the Ith element is a pack
3705 expansion, where I is ARGUMENT_PACK_SELECT_INDEX) into a pack expansion.
3706 In this case, the Ith element resulting from this substituting is going to
3707 be a pack expansion, which pattern is the pattern of E. Let's return the
3708 pattern of E, and gen_elem_of_pack_expansion_instantiation will build the
3709 resulting pack expansion from it. */
3710 if (PACK_EXPANSION_P (arg))
3712 /* Make sure we aren't throwing away arg info. */
3713 gcc_assert (!PACK_EXPANSION_EXTRA_ARGS (arg));
3714 arg = PACK_EXPANSION_PATTERN (arg);
3717 return arg;
3720 /* Return a modification of ARGS that's suitable for preserving inside a hash
3721 table. In particular, this replaces each ARGUMENT_PACK_SELECT with its
3722 underlying argument. ARGS is copied (upon modification) iff COW_P. */
3724 static tree
3725 preserve_args (tree args, bool cow_p = true)
3727 if (!args)
3728 return NULL_TREE;
3730 for (int i = 0, len = TREE_VEC_LENGTH (args); i < len; ++i)
3732 tree t = TREE_VEC_ELT (args, i);
3733 tree r;
3734 if (!t)
3735 r = NULL_TREE;
3736 else if (TREE_CODE (t) == ARGUMENT_PACK_SELECT)
3737 r = argument_pack_select_arg (t);
3738 else if (TREE_CODE (t) == TREE_VEC)
3739 r = preserve_args (t, cow_p);
3740 else
3741 r = t;
3742 if (r != t)
3744 if (cow_p)
3746 args = copy_template_args (args);
3747 cow_p = false;
3749 TREE_VEC_ELT (args, i) = r;
3753 return args;
3756 /* True iff FN is a function representing a built-in variadic parameter
3757 pack. */
3759 bool
3760 builtin_pack_fn_p (tree fn)
3762 if (!fn
3763 || TREE_CODE (fn) != FUNCTION_DECL
3764 || !DECL_IS_UNDECLARED_BUILTIN (fn))
3765 return false;
3767 if (id_equal (DECL_NAME (fn), "__integer_pack"))
3768 return true;
3770 return false;
3773 /* True iff CALL is a call to a function representing a built-in variadic
3774 parameter pack. */
3776 static bool
3777 builtin_pack_call_p (tree call)
3779 if (TREE_CODE (call) != CALL_EXPR)
3780 return false;
3781 return builtin_pack_fn_p (CALL_EXPR_FN (call));
3784 /* Return a TREE_VEC for the expansion of __integer_pack(HI). */
3786 static tree
3787 expand_integer_pack (tree call, tree args, tsubst_flags_t complain,
3788 tree in_decl)
3790 tree ohi = CALL_EXPR_ARG (call, 0);
3791 tree hi = tsubst_expr (ohi, args, complain, in_decl);
3793 if (instantiation_dependent_expression_p (hi))
3795 if (hi != ohi)
3797 call = copy_node (call);
3798 CALL_EXPR_ARG (call, 0) = hi;
3800 tree ex = make_pack_expansion (call, complain);
3801 tree vec = make_tree_vec (1);
3802 TREE_VEC_ELT (vec, 0) = ex;
3803 return vec;
3805 else
3807 hi = instantiate_non_dependent_expr (hi, complain);
3808 hi = cxx_constant_value (hi, complain);
3809 int len = valid_constant_size_p (hi) ? tree_to_shwi (hi) : -1;
3811 /* Calculate the largest value of len that won't make the size of the vec
3812 overflow an int. The compiler will exceed resource limits long before
3813 this, but it seems a decent place to diagnose. */
3814 int max = ((INT_MAX - sizeof (tree_vec)) / sizeof (tree)) + 1;
3816 if (len < 0 || len > max)
3818 if ((complain & tf_error)
3819 && hi != error_mark_node)
3820 error ("argument to %<__integer_pack%> must be between 0 and %d",
3821 max);
3822 return error_mark_node;
3825 tree vec = make_tree_vec (len);
3827 for (int i = 0; i < len; ++i)
3828 TREE_VEC_ELT (vec, i) = size_int (i);
3830 return vec;
3834 /* Return a TREE_VEC for the expansion of built-in template parameter pack
3835 CALL. */
3837 static tree
3838 expand_builtin_pack_call (tree call, tree args, tsubst_flags_t complain,
3839 tree in_decl)
3841 if (!builtin_pack_call_p (call))
3842 return NULL_TREE;
3844 tree fn = CALL_EXPR_FN (call);
3846 if (id_equal (DECL_NAME (fn), "__integer_pack"))
3847 return expand_integer_pack (call, args, complain, in_decl);
3849 return NULL_TREE;
3852 /* Return true if the tree T has the extra args mechanism for
3853 avoiding partial instantiation. */
3855 static bool
3856 has_extra_args_mechanism_p (const_tree t)
3858 return (PACK_EXPANSION_P (t) /* PACK_EXPANSION_EXTRA_ARGS */
3859 || TREE_CODE (t) == REQUIRES_EXPR /* REQUIRES_EXPR_EXTRA_ARGS */
3860 || (TREE_CODE (t) == IF_STMT
3861 && IF_STMT_CONSTEXPR_P (t)) /* IF_STMT_EXTRA_ARGS */
3862 || TREE_CODE (t) == LAMBDA_EXPR); /* LAMBDA_EXPR_EXTRA_ARGS */
3865 /* Return *_EXTRA_ARGS of the given supported tree T. */
3867 static tree&
3868 tree_extra_args (tree t)
3870 gcc_checking_assert (has_extra_args_mechanism_p (t));
3872 if (PACK_EXPANSION_P (t))
3873 return PACK_EXPANSION_EXTRA_ARGS (t);
3874 else if (TREE_CODE (t) == REQUIRES_EXPR)
3875 return REQUIRES_EXPR_EXTRA_ARGS (t);
3876 else if (TREE_CODE (t) == IF_STMT
3877 && IF_STMT_CONSTEXPR_P (t))
3878 return IF_STMT_EXTRA_ARGS (t);
3879 else if (TREE_CODE (t) == LAMBDA_EXPR)
3880 return LAMBDA_EXPR_EXTRA_ARGS (t);
3882 gcc_unreachable ();
3885 /* Structure used to track the progress of find_parameter_packs_r. */
3886 struct find_parameter_pack_data
3888 /* TREE_LIST that will contain all of the parameter packs found by
3889 the traversal. */
3890 tree* parameter_packs;
3892 /* Set of AST nodes that have been visited by the traversal. */
3893 hash_set<tree> *visited;
3895 /* True iff we found a subtree that has the extra args mechanism. */
3896 bool found_extra_args_tree_p = false;
3899 /* Identifies all of the argument packs that occur in a template
3900 argument and appends them to the TREE_LIST inside DATA, which is a
3901 find_parameter_pack_data structure. This is a subroutine of
3902 make_pack_expansion and uses_parameter_packs. */
3903 static tree
3904 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
3906 tree t = *tp;
3907 struct find_parameter_pack_data* ppd =
3908 (struct find_parameter_pack_data*)data;
3909 bool parameter_pack_p = false;
3911 #define WALK_SUBTREE(NODE) \
3912 cp_walk_tree (&(NODE), &find_parameter_packs_r, \
3913 ppd, ppd->visited) \
3915 /* Don't look through typedefs; we are interested in whether a
3916 parameter pack is actually written in the expression/type we're
3917 looking at, not the target type. */
3918 if (TYPE_P (t) && typedef_variant_p (t))
3920 /* But do look at arguments for an alias template. */
3921 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
3922 cp_walk_tree (&TI_ARGS (tinfo),
3923 &find_parameter_packs_r,
3924 ppd, ppd->visited);
3925 *walk_subtrees = 0;
3926 return NULL_TREE;
3929 /* Identify whether this is a parameter pack or not. */
3930 switch (TREE_CODE (t))
3932 case TEMPLATE_PARM_INDEX:
3933 if (TEMPLATE_PARM_PARAMETER_PACK (t))
3934 parameter_pack_p = true;
3935 break;
3937 case TEMPLATE_TYPE_PARM:
3938 t = TYPE_MAIN_VARIANT (t);
3939 /* FALLTHRU */
3940 case TEMPLATE_TEMPLATE_PARM:
3941 if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3942 parameter_pack_p = true;
3943 break;
3945 case FIELD_DECL:
3946 case PARM_DECL:
3947 if (DECL_PACK_P (t))
3949 /* We don't want to walk into the type of a PARM_DECL,
3950 because we don't want to see the type parameter pack. */
3951 *walk_subtrees = 0;
3952 parameter_pack_p = true;
3954 break;
3956 case VAR_DECL:
3957 if (DECL_PACK_P (t))
3959 /* We don't want to walk into the type of a variadic capture proxy,
3960 because we don't want to see the type parameter pack. */
3961 *walk_subtrees = 0;
3962 parameter_pack_p = true;
3964 else if (variable_template_specialization_p (t))
3966 cp_walk_tree (&DECL_TI_ARGS (t),
3967 find_parameter_packs_r,
3968 ppd, ppd->visited);
3969 *walk_subtrees = 0;
3971 break;
3973 case CALL_EXPR:
3974 if (builtin_pack_call_p (t))
3975 parameter_pack_p = true;
3976 break;
3978 case BASES:
3979 parameter_pack_p = true;
3980 break;
3981 default:
3982 /* Not a parameter pack. */
3983 break;
3986 if (parameter_pack_p)
3988 /* Add this parameter pack to the list. */
3989 *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
3992 if (has_extra_args_mechanism_p (t) && !PACK_EXPANSION_P (t))
3993 ppd->found_extra_args_tree_p = true;
3995 if (TYPE_P (t))
3996 cp_walk_tree (&TYPE_CONTEXT (t),
3997 &find_parameter_packs_r, ppd, ppd->visited);
3999 /* This switch statement will return immediately if we don't find a
4000 parameter pack. ??? Should some of these be in cp_walk_subtrees? */
4001 switch (TREE_CODE (t))
4003 case BOUND_TEMPLATE_TEMPLATE_PARM:
4004 /* Check the template itself. */
4005 cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)),
4006 &find_parameter_packs_r, ppd, ppd->visited);
4007 return NULL_TREE;
4009 case DECL_EXPR:
4011 tree decl = DECL_EXPR_DECL (t);
4012 /* Ignore the declaration of a capture proxy for a parameter pack. */
4013 if (is_capture_proxy (decl))
4014 *walk_subtrees = 0;
4015 if (is_typedef_decl (decl))
4016 /* Since we stop at typedefs above, we need to look through them at
4017 the point of the DECL_EXPR. */
4018 cp_walk_tree (&DECL_ORIGINAL_TYPE (decl),
4019 &find_parameter_packs_r, ppd, ppd->visited);
4020 return NULL_TREE;
4023 case TEMPLATE_DECL:
4024 if (!DECL_TEMPLATE_TEMPLATE_PARM_P (t))
4025 return NULL_TREE;
4026 cp_walk_tree (&TREE_TYPE (t),
4027 &find_parameter_packs_r, ppd, ppd->visited);
4028 return NULL_TREE;
4030 case TYPE_PACK_EXPANSION:
4031 case EXPR_PACK_EXPANSION:
4032 *walk_subtrees = 0;
4033 return NULL_TREE;
4035 case INTEGER_TYPE:
4036 cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r,
4037 ppd, ppd->visited);
4038 *walk_subtrees = 0;
4039 return NULL_TREE;
4041 case IDENTIFIER_NODE:
4042 cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd,
4043 ppd->visited);
4044 *walk_subtrees = 0;
4045 return NULL_TREE;
4047 case LAMBDA_EXPR:
4049 /* Since we defer implicit capture, look in the parms and body. */
4050 tree fn = lambda_function (t);
4051 cp_walk_tree (&TREE_TYPE (fn), &find_parameter_packs_r, ppd,
4052 ppd->visited);
4053 cp_walk_tree (&DECL_SAVED_TREE (fn), &find_parameter_packs_r, ppd,
4054 ppd->visited);
4055 return NULL_TREE;
4058 case DECLTYPE_TYPE:
4059 cp_walk_tree (&DECLTYPE_TYPE_EXPR (t), &find_parameter_packs_r,
4060 ppd, ppd->visited);
4061 *walk_subtrees = 0;
4062 return NULL_TREE;
4064 case IF_STMT:
4065 cp_walk_tree (&IF_COND (t), &find_parameter_packs_r,
4066 ppd, ppd->visited);
4067 cp_walk_tree (&THEN_CLAUSE (t), &find_parameter_packs_r,
4068 ppd, ppd->visited);
4069 cp_walk_tree (&ELSE_CLAUSE (t), &find_parameter_packs_r,
4070 ppd, ppd->visited);
4071 /* Don't walk into IF_STMT_EXTRA_ARGS. */
4072 *walk_subtrees = 0;
4073 return NULL_TREE;
4075 case TAG_DEFN:
4076 t = TREE_TYPE (t);
4077 if (CLASS_TYPE_P (t))
4079 /* Local class, need to look through the whole definition.
4080 TYPE_BINFO might be unset for a partial instantiation. */
4081 if (TYPE_BINFO (t))
4082 for (tree bb : BINFO_BASE_BINFOS (TYPE_BINFO (t)))
4083 cp_walk_tree (&BINFO_TYPE (bb), &find_parameter_packs_r,
4084 ppd, ppd->visited);
4086 else
4087 /* Enum, look at the values. */
4088 for (tree l = TYPE_VALUES (t); l; l = TREE_CHAIN (l))
4089 cp_walk_tree (&DECL_INITIAL (TREE_VALUE (l)),
4090 &find_parameter_packs_r,
4091 ppd, ppd->visited);
4092 return NULL_TREE;
4094 case FUNCTION_TYPE:
4095 case METHOD_TYPE:
4096 WALK_SUBTREE (TYPE_RAISES_EXCEPTIONS (t));
4097 break;
4099 default:
4100 return NULL_TREE;
4103 #undef WALK_SUBTREE
4105 return NULL_TREE;
4108 /* Determines if the expression or type T uses any parameter packs. */
4109 tree
4110 uses_parameter_packs (tree t)
4112 tree parameter_packs = NULL_TREE;
4113 struct find_parameter_pack_data ppd;
4114 ppd.parameter_packs = &parameter_packs;
4115 ppd.visited = new hash_set<tree>;
4116 cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4117 delete ppd.visited;
4118 return parameter_packs;
4121 /* Turn ARG, which may be an expression, type, or a TREE_LIST
4122 representation a base-class initializer into a parameter pack
4123 expansion. If all goes well, the resulting node will be an
4124 EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
4125 respectively. */
4126 tree
4127 make_pack_expansion (tree arg, tsubst_flags_t complain)
4129 tree result;
4130 tree parameter_packs = NULL_TREE;
4131 bool for_types = false;
4132 struct find_parameter_pack_data ppd;
4134 if (!arg || arg == error_mark_node)
4135 return arg;
4137 if (TREE_CODE (arg) == TREE_LIST && TREE_PURPOSE (arg))
4139 /* A TREE_LIST with a non-null TREE_PURPOSE is for a base
4140 class initializer. In this case, the TREE_PURPOSE will be a
4141 _TYPE node (representing the base class expansion we're
4142 initializing) and the TREE_VALUE will be a TREE_LIST
4143 containing the initialization arguments.
4145 The resulting expansion looks somewhat different from most
4146 expansions. Rather than returning just one _EXPANSION, we
4147 return a TREE_LIST whose TREE_PURPOSE is a
4148 TYPE_PACK_EXPANSION containing the bases that will be
4149 initialized. The TREE_VALUE will be identical to the
4150 original TREE_VALUE, which is a list of arguments that will
4151 be passed to each base. We do not introduce any new pack
4152 expansion nodes into the TREE_VALUE (although it is possible
4153 that some already exist), because the TREE_PURPOSE and
4154 TREE_VALUE all need to be expanded together with the same
4155 _EXPANSION node. Note that the TYPE_PACK_EXPANSION in the
4156 resulting TREE_PURPOSE will mention the parameter packs in
4157 both the bases and the arguments to the bases. */
4158 tree purpose;
4159 tree value;
4160 tree parameter_packs = NULL_TREE;
4162 /* Determine which parameter packs will be used by the base
4163 class expansion. */
4164 ppd.visited = new hash_set<tree>;
4165 ppd.parameter_packs = &parameter_packs;
4166 gcc_assert (TYPE_P (TREE_PURPOSE (arg)));
4167 cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r,
4168 &ppd, ppd.visited);
4170 if (parameter_packs == NULL_TREE)
4172 if (complain & tf_error)
4173 error ("base initializer expansion %qT contains no parameter packs",
4174 arg);
4175 delete ppd.visited;
4176 return error_mark_node;
4179 if (TREE_VALUE (arg) != void_type_node)
4181 /* Collect the sets of parameter packs used in each of the
4182 initialization arguments. */
4183 for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
4185 /* Determine which parameter packs will be expanded in this
4186 argument. */
4187 cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r,
4188 &ppd, ppd.visited);
4192 delete ppd.visited;
4194 /* Create the pack expansion type for the base type. */
4195 purpose = cxx_make_type (TYPE_PACK_EXPANSION);
4196 PACK_EXPANSION_PATTERN (purpose) = TREE_PURPOSE (arg);
4197 PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
4198 PACK_EXPANSION_LOCAL_P (purpose) = at_function_scope_p ();
4200 /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
4201 they will rarely be compared to anything. */
4202 SET_TYPE_STRUCTURAL_EQUALITY (purpose);
4204 return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
4207 if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
4208 for_types = true;
4210 /* Build the PACK_EXPANSION_* node. */
4211 result = for_types
4212 ? cxx_make_type (TYPE_PACK_EXPANSION)
4213 : make_node (EXPR_PACK_EXPANSION);
4214 PACK_EXPANSION_PATTERN (result) = arg;
4215 if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
4217 /* Propagate type and const-expression information. */
4218 TREE_TYPE (result) = TREE_TYPE (arg);
4219 TREE_CONSTANT (result) = TREE_CONSTANT (arg);
4220 /* Mark this read now, since the expansion might be length 0. */
4221 mark_exp_read (arg);
4223 else
4224 /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
4225 they will rarely be compared to anything. */
4226 SET_TYPE_STRUCTURAL_EQUALITY (result);
4228 /* Determine which parameter packs will be expanded. */
4229 ppd.parameter_packs = &parameter_packs;
4230 ppd.visited = new hash_set<tree>;
4231 cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
4232 delete ppd.visited;
4234 /* Make sure we found some parameter packs. */
4235 if (parameter_packs == NULL_TREE)
4237 if (complain & tf_error)
4239 if (TYPE_P (arg))
4240 error ("expansion pattern %qT contains no parameter packs", arg);
4241 else
4242 error ("expansion pattern %qE contains no parameter packs", arg);
4244 return error_mark_node;
4246 PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
4248 PACK_EXPANSION_LOCAL_P (result) = at_function_scope_p ();
4249 if (ppd.found_extra_args_tree_p)
4250 /* If the pattern of this pack expansion contains a subtree that has
4251 the extra args mechanism for avoiding partial instantiation, then
4252 force this pack expansion to also use extra args. Otherwise
4253 partial instantiation of this pack expansion may not lower the
4254 level of some parameter packs within the pattern, which would
4255 confuse tsubst_pack_expansion later (PR101764). */
4256 PACK_EXPANSION_FORCE_EXTRA_ARGS_P (result) = true;
4258 return result;
4261 /* Checks T for any "bare" parameter packs, which have not yet been
4262 expanded, and issues an error if any are found. This operation can
4263 only be done on full expressions or types (e.g., an expression
4264 statement, "if" condition, etc.), because we could have expressions like:
4266 foo(f(g(h(args)))...)
4268 where "args" is a parameter pack. check_for_bare_parameter_packs
4269 should not be called for the subexpressions args, h(args),
4270 g(h(args)), or f(g(h(args))), because we would produce erroneous
4271 error messages.
4273 Returns TRUE and emits an error if there were bare parameter packs,
4274 returns FALSE otherwise. */
4275 bool
4276 check_for_bare_parameter_packs (tree t, location_t loc /* = UNKNOWN_LOCATION */)
4278 tree parameter_packs = NULL_TREE;
4279 struct find_parameter_pack_data ppd;
4281 if (!processing_template_decl || !t || t == error_mark_node)
4282 return false;
4284 if (TREE_CODE (t) == TYPE_DECL)
4285 t = TREE_TYPE (t);
4287 ppd.parameter_packs = &parameter_packs;
4288 ppd.visited = new hash_set<tree>;
4289 cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4290 delete ppd.visited;
4292 if (!parameter_packs)
4293 return false;
4295 if (loc == UNKNOWN_LOCATION)
4296 loc = cp_expr_loc_or_input_loc (t);
4298 /* It's OK for a lambda to have an unexpanded parameter pack from the
4299 containing context, but do complain about unexpanded capture packs. */
4300 tree lam = current_lambda_expr ();
4301 if (lam)
4302 lam = TREE_TYPE (lam);
4304 if (lam && lam != current_class_type)
4306 /* We're in a lambda, but it isn't the innermost class.
4307 This should work, but currently doesn't. */
4308 sorry_at (loc, "unexpanded parameter pack in local class in lambda");
4309 return true;
4312 if (lam && CLASSTYPE_TEMPLATE_INFO (lam))
4313 for (; parameter_packs;
4314 parameter_packs = TREE_CHAIN (parameter_packs))
4316 tree pack = TREE_VALUE (parameter_packs);
4317 if (is_capture_proxy (pack)
4318 || (TREE_CODE (pack) == PARM_DECL
4319 && DECL_CONTEXT (DECL_CONTEXT (pack)) == lam))
4320 break;
4323 if (parameter_packs)
4325 auto_diagnostic_group d;
4326 error_at (loc, "parameter packs not expanded with %<...%>:");
4327 while (parameter_packs)
4329 tree pack = TREE_VALUE (parameter_packs);
4330 tree name = NULL_TREE;
4332 if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
4333 || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
4334 name = TYPE_NAME (pack);
4335 else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
4336 name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
4337 else if (TREE_CODE (pack) == CALL_EXPR)
4338 name = DECL_NAME (CALL_EXPR_FN (pack));
4339 else
4340 name = DECL_NAME (pack);
4342 if (name)
4343 inform (loc, " %qD", name);
4344 else
4345 inform (loc, " %s", "<anonymous>");
4347 parameter_packs = TREE_CHAIN (parameter_packs);
4350 return true;
4353 return false;
4356 /* Expand any parameter packs that occur in the template arguments in
4357 ARGS. */
4358 tree
4359 expand_template_argument_pack (tree args)
4361 if (args == error_mark_node)
4362 return error_mark_node;
4364 tree result_args = NULL_TREE;
4365 int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
4366 int num_result_args = -1;
4367 int non_default_args_count = -1;
4369 /* First, determine if we need to expand anything, and the number of
4370 slots we'll need. */
4371 for (in_arg = 0; in_arg < nargs; ++in_arg)
4373 tree arg = TREE_VEC_ELT (args, in_arg);
4374 if (arg == NULL_TREE)
4375 return args;
4376 if (ARGUMENT_PACK_P (arg))
4378 int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
4379 if (num_result_args < 0)
4380 num_result_args = in_arg + num_packed;
4381 else
4382 num_result_args += num_packed;
4384 else
4386 if (num_result_args >= 0)
4387 num_result_args++;
4391 /* If no expansion is necessary, we're done. */
4392 if (num_result_args < 0)
4393 return args;
4395 /* Expand arguments. */
4396 result_args = make_tree_vec (num_result_args);
4397 if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
4398 non_default_args_count =
4399 GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
4400 for (in_arg = 0; in_arg < nargs; ++in_arg)
4402 tree arg = TREE_VEC_ELT (args, in_arg);
4403 if (ARGUMENT_PACK_P (arg))
4405 tree packed = ARGUMENT_PACK_ARGS (arg);
4406 int i, num_packed = TREE_VEC_LENGTH (packed);
4407 for (i = 0; i < num_packed; ++i, ++out_arg)
4408 TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
4409 if (non_default_args_count > 0)
4410 non_default_args_count += num_packed - 1;
4412 else
4414 TREE_VEC_ELT (result_args, out_arg) = arg;
4415 ++out_arg;
4418 if (non_default_args_count >= 0)
4419 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
4420 return result_args;
4423 /* Checks if DECL shadows a template parameter.
4425 [temp.local]: A template-parameter shall not be redeclared within its
4426 scope (including nested scopes).
4428 Emits an error and returns TRUE if the DECL shadows a parameter,
4429 returns FALSE otherwise. */
4431 bool
4432 check_template_shadow (tree decl)
4434 tree olddecl;
4436 /* If we're not in a template, we can't possibly shadow a template
4437 parameter. */
4438 if (!current_template_parms)
4439 return true;
4441 /* Figure out what we're shadowing. */
4442 decl = OVL_FIRST (decl);
4443 olddecl = innermost_non_namespace_value (DECL_NAME (decl));
4445 /* If there's no previous binding for this name, we're not shadowing
4446 anything, let alone a template parameter. */
4447 if (!olddecl)
4448 return true;
4450 /* If we're not shadowing a template parameter, we're done. Note
4451 that OLDDECL might be an OVERLOAD (or perhaps even an
4452 ERROR_MARK), so we can't just blithely assume it to be a _DECL
4453 node. */
4454 if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
4455 return true;
4457 /* We check for decl != olddecl to avoid bogus errors for using a
4458 name inside a class. We check TPFI to avoid duplicate errors for
4459 inline member templates. */
4460 if (decl == olddecl
4461 || (DECL_TEMPLATE_PARM_P (decl)
4462 && TEMPLATE_PARMS_FOR_INLINE (current_template_parms)))
4463 return true;
4465 /* Don't complain about the injected class name, as we've already
4466 complained about the class itself. */
4467 if (DECL_SELF_REFERENCE_P (decl))
4468 return false;
4470 auto_diagnostic_group d;
4471 if (DECL_TEMPLATE_PARM_P (decl))
4472 error ("declaration of template parameter %q+D shadows "
4473 "template parameter", decl);
4474 else
4475 error ("declaration of %q+#D shadows template parameter", decl);
4476 inform (DECL_SOURCE_LOCATION (olddecl),
4477 "template parameter %qD declared here", olddecl);
4478 return false;
4481 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
4482 ORIG_LEVEL, DECL, and TYPE. */
4484 static tree
4485 build_template_parm_index (int index,
4486 int level,
4487 int orig_level,
4488 tree decl,
4489 tree type)
4491 tree t = make_node (TEMPLATE_PARM_INDEX);
4492 TEMPLATE_PARM_IDX (t) = index;
4493 TEMPLATE_PARM_LEVEL (t) = level;
4494 TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
4495 TEMPLATE_PARM_DECL (t) = decl;
4496 TREE_TYPE (t) = type;
4497 TREE_CONSTANT (t) = TREE_CONSTANT (decl);
4498 TREE_READONLY (t) = TREE_READONLY (decl);
4500 return t;
4503 struct ctp_hasher : ggc_ptr_hash<tree_node>
4505 static hashval_t hash (tree t)
4507 ++comparing_specializations;
4508 tree_code code = TREE_CODE (t);
4509 hashval_t val = iterative_hash_object (code, 0);
4510 val = iterative_hash_object (TEMPLATE_TYPE_LEVEL (t), val);
4511 val = iterative_hash_object (TEMPLATE_TYPE_IDX (t), val);
4512 if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
4515 = iterative_hash_template_arg (CLASS_PLACEHOLDER_TEMPLATE (t), val);
4516 if (tree c = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (t)))
4517 val = iterative_hash_placeholder_constraint (c, val);
4519 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
4520 val = iterative_hash_template_arg (TYPE_TI_ARGS (t), val);
4521 --comparing_specializations;
4522 return val;
4525 static bool equal (tree t, tree u)
4527 ++comparing_specializations;
4528 bool eq = comptypes (t, u, COMPARE_STRUCTURAL);
4529 --comparing_specializations;
4530 return eq;
4534 static GTY (()) hash_table<ctp_hasher> *ctp_table;
4536 /* Find the canonical type parameter for the given template type
4537 parameter. Returns the canonical type parameter, which may be TYPE
4538 if no such parameter existed. */
4540 tree
4541 canonical_type_parameter (tree type)
4543 if (ctp_table == NULL)
4544 ctp_table = hash_table<ctp_hasher>::create_ggc (61);
4546 tree& slot = *ctp_table->find_slot (type, INSERT);
4547 if (slot == NULL_TREE)
4548 slot = type;
4549 return slot;
4552 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
4553 TEMPLATE_PARM_LEVEL has been decreased by LEVELS. If such a
4554 TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
4555 new one is created. */
4557 static tree
4558 reduce_template_parm_level (tree index, tree type, int levels, tree args,
4559 tsubst_flags_t complain)
4561 if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
4562 || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
4563 != TEMPLATE_PARM_LEVEL (index) - levels)
4564 || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
4566 tree orig_decl = TEMPLATE_PARM_DECL (index);
4568 tree decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
4569 TREE_CODE (orig_decl), DECL_NAME (orig_decl),
4570 type);
4571 TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
4572 TREE_READONLY (decl) = TREE_READONLY (orig_decl);
4573 DECL_VIRTUAL_P (decl) = DECL_VIRTUAL_P (orig_decl);
4574 DECL_ARTIFICIAL (decl) = 1;
4575 SET_DECL_TEMPLATE_PARM_P (decl);
4577 tree tpi = build_template_parm_index (TEMPLATE_PARM_IDX (index),
4578 TEMPLATE_PARM_LEVEL (index) - levels,
4579 TEMPLATE_PARM_ORIG_LEVEL (index),
4580 decl, type);
4581 TEMPLATE_PARM_DESCENDANTS (index) = tpi;
4582 TEMPLATE_PARM_PARAMETER_PACK (tpi)
4583 = TEMPLATE_PARM_PARAMETER_PACK (index);
4585 /* Template template parameters need this. */
4586 tree inner = decl;
4587 if (TREE_CODE (decl) == TEMPLATE_DECL)
4589 inner = build_lang_decl_loc (DECL_SOURCE_LOCATION (decl),
4590 TYPE_DECL, DECL_NAME (decl), type);
4591 DECL_TEMPLATE_RESULT (decl) = inner;
4592 DECL_ARTIFICIAL (inner) = true;
4593 tree parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (orig_decl),
4594 args, complain);
4595 DECL_TEMPLATE_PARMS (decl) = parms;
4596 tree orig_inner = DECL_TEMPLATE_RESULT (orig_decl);
4597 DECL_TEMPLATE_INFO (inner)
4598 = build_template_info (DECL_TI_TEMPLATE (orig_inner),
4599 template_parms_to_args (parms));
4602 /* Attach the TPI to the decl. */
4603 if (TREE_CODE (inner) == TYPE_DECL)
4604 TEMPLATE_TYPE_PARM_INDEX (type) = tpi;
4605 else
4606 DECL_INITIAL (decl) = tpi;
4609 return TEMPLATE_PARM_DESCENDANTS (index);
4612 /* Process information from new template parameter PARM and append it
4613 to the LIST being built. This new parameter is a non-type
4614 parameter iff IS_NON_TYPE is true. This new parameter is a
4615 parameter pack iff IS_PARAMETER_PACK is true. The location of PARM
4616 is in PARM_LOC. */
4618 tree
4619 process_template_parm (tree list, location_t parm_loc, tree parm,
4620 bool is_non_type, bool is_parameter_pack)
4622 gcc_assert (TREE_CODE (parm) == TREE_LIST);
4623 tree prev = NULL_TREE;
4624 int idx = 0;
4626 if (list)
4628 prev = tree_last (list);
4630 tree p = TREE_VALUE (prev);
4631 if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
4632 idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
4633 else if (TREE_CODE (p) == PARM_DECL)
4634 idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
4636 ++idx;
4639 tree decl = NULL_TREE;
4640 tree defval = TREE_PURPOSE (parm);
4641 tree constr = TREE_TYPE (parm);
4643 if (is_non_type)
4645 parm = TREE_VALUE (parm);
4647 SET_DECL_TEMPLATE_PARM_P (parm);
4649 if (TREE_TYPE (parm) != error_mark_node)
4651 /* [temp.param]
4653 The top-level cv-qualifiers on the template-parameter are
4654 ignored when determining its type. */
4655 TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
4656 if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
4657 TREE_TYPE (parm) = error_mark_node;
4658 else if (uses_parameter_packs (TREE_TYPE (parm))
4659 && !is_parameter_pack
4660 /* If we're in a nested template parameter list, the template
4661 template parameter could be a parameter pack. */
4662 && processing_template_parmlist == 1)
4664 /* This template parameter is not a parameter pack, but it
4665 should be. Complain about "bare" parameter packs. */
4666 check_for_bare_parameter_packs (TREE_TYPE (parm));
4668 /* Recover by calling this a parameter pack. */
4669 is_parameter_pack = true;
4673 /* A template parameter is not modifiable. */
4674 TREE_CONSTANT (parm) = 1;
4675 TREE_READONLY (parm) = 1;
4676 decl = build_decl (parm_loc,
4677 CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
4678 TREE_CONSTANT (decl) = 1;
4679 TREE_READONLY (decl) = 1;
4680 DECL_INITIAL (parm) = DECL_INITIAL (decl)
4681 = build_template_parm_index (idx, current_template_depth,
4682 current_template_depth,
4683 decl, TREE_TYPE (parm));
4685 TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))
4686 = is_parameter_pack;
4688 else
4690 tree t;
4691 parm = TREE_VALUE (TREE_VALUE (parm));
4693 if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
4695 t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
4696 /* This is for distinguishing between real templates and template
4697 template parameters */
4698 TREE_TYPE (parm) = t;
4700 /* any_template_parm_r expects to be able to get the targs of a
4701 DECL_TEMPLATE_RESULT. */
4702 tree result = DECL_TEMPLATE_RESULT (parm);
4703 TREE_TYPE (result) = t;
4704 tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (parm));
4705 tree tinfo = build_template_info (parm, args);
4706 retrofit_lang_decl (result);
4707 DECL_TEMPLATE_INFO (result) = tinfo;
4709 decl = parm;
4711 else
4713 t = cxx_make_type (TEMPLATE_TYPE_PARM);
4714 /* parm is either IDENTIFIER_NODE or NULL_TREE. */
4715 decl = build_decl (parm_loc,
4716 TYPE_DECL, parm, t);
4719 TYPE_NAME (t) = decl;
4720 TYPE_STUB_DECL (t) = decl;
4721 parm = decl;
4722 TEMPLATE_TYPE_PARM_INDEX (t)
4723 = build_template_parm_index (idx, current_template_depth,
4724 current_template_depth,
4725 decl, TREE_TYPE (parm));
4726 TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
4727 TYPE_CANONICAL (t) = canonical_type_parameter (t);
4729 DECL_ARTIFICIAL (decl) = 1;
4730 SET_DECL_TEMPLATE_PARM_P (decl);
4732 if (TREE_CODE (parm) == TEMPLATE_DECL
4733 && !uses_outer_template_parms (parm))
4734 TEMPLATE_TEMPLATE_PARM_SIMPLE_P (TREE_TYPE (parm)) = true;
4736 /* Build requirements for the type/template parameter.
4737 This must be done after SET_DECL_TEMPLATE_PARM_P or
4738 process_template_parm could fail. */
4739 tree reqs = finish_shorthand_constraint (parm, constr);
4741 decl = pushdecl (decl);
4742 if (!is_non_type)
4743 parm = decl;
4745 /* Build the parameter node linking the parameter declaration,
4746 its default argument (if any), and its constraints (if any). */
4747 parm = build_tree_list (defval, parm);
4748 TEMPLATE_PARM_CONSTRAINTS (parm) = reqs;
4750 if (prev)
4751 TREE_CHAIN (prev) = parm;
4752 else
4753 list = parm;
4755 return list;
4758 /* The end of a template parameter list has been reached. Process the
4759 tree list into a parameter vector, converting each parameter into a more
4760 useful form. Type parameters are saved as IDENTIFIER_NODEs, and others
4761 as PARM_DECLs. */
4763 tree
4764 end_template_parm_list (tree parms)
4766 tree saved_parmlist = make_tree_vec (list_length (parms));
4768 /* Pop the dummy parameter level and add the real one. We do not
4769 morph the dummy parameter in place, as it might have been
4770 captured by a (nested) template-template-parm. */
4771 current_template_parms = TREE_CHAIN (current_template_parms);
4773 current_template_parms
4774 = tree_cons (size_int (current_template_depth + 1),
4775 saved_parmlist, current_template_parms);
4777 for (unsigned ix = 0; parms; ix++)
4779 tree parm = parms;
4780 parms = TREE_CHAIN (parms);
4781 TREE_CHAIN (parm) = NULL_TREE;
4783 TREE_VEC_ELT (saved_parmlist, ix) = parm;
4786 --processing_template_parmlist;
4788 return saved_parmlist;
4791 // Explicitly indicate the end of the template parameter list. We assume
4792 // that the current template parameters have been constructed and/or
4793 // managed explicitly, as when creating new template template parameters
4794 // from a shorthand constraint.
4795 void
4796 end_template_parm_list ()
4798 --processing_template_parmlist;
4801 /* end_template_decl is called after a template declaration is seen. */
4803 void
4804 end_template_decl (void)
4806 reset_specialization ();
4808 if (! processing_template_decl)
4809 return;
4811 /* This matches the pushlevel in begin_template_parm_list. */
4812 finish_scope ();
4814 --processing_template_decl;
4815 current_template_parms = TREE_CHAIN (current_template_parms);
4818 /* Takes a TEMPLATE_PARM_P or DECL_TEMPLATE_PARM_P node or a TREE_LIST
4819 thereof, and converts it into an argument suitable to be passed to
4820 the type substitution functions. Note that if the TREE_LIST contains
4821 an error_mark node, the returned argument is error_mark_node. */
4823 tree
4824 template_parm_to_arg (tree t)
4826 if (!t)
4827 return NULL_TREE;
4829 if (TREE_CODE (t) == TREE_LIST)
4830 t = TREE_VALUE (t);
4832 if (error_operand_p (t))
4833 return error_mark_node;
4835 if (DECL_P (t) && DECL_TEMPLATE_PARM_P (t))
4837 if (TREE_CODE (t) == TYPE_DECL
4838 || TREE_CODE (t) == TEMPLATE_DECL)
4839 t = TREE_TYPE (t);
4840 else
4841 t = DECL_INITIAL (t);
4844 gcc_assert (TEMPLATE_PARM_P (t));
4846 if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
4847 || TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
4849 if (TEMPLATE_TYPE_PARAMETER_PACK (t))
4851 /* Turn this argument into a TYPE_ARGUMENT_PACK
4852 with a single element, which expands T. */
4853 tree vec = make_tree_vec (1);
4854 if (CHECKING_P)
4855 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4857 TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4859 t = cxx_make_type (TYPE_ARGUMENT_PACK);
4860 ARGUMENT_PACK_ARGS (t) = vec;
4863 else
4865 if (TEMPLATE_PARM_PARAMETER_PACK (t))
4867 /* Turn this argument into a NONTYPE_ARGUMENT_PACK
4868 with a single element, which expands T. */
4869 tree vec = make_tree_vec (1);
4870 if (CHECKING_P)
4871 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4873 t = convert_from_reference (t);
4874 TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4876 t = make_node (NONTYPE_ARGUMENT_PACK);
4877 ARGUMENT_PACK_ARGS (t) = vec;
4879 else
4880 t = convert_from_reference (t);
4882 return t;
4885 /* If T looks like a generic template argument produced by template_parm_to_arg,
4886 return the corresponding template parameter, otherwise return NULL_TREE. */
4888 static tree
4889 template_arg_to_parm (tree t)
4891 if (t == NULL_TREE)
4892 return NULL_TREE;
4894 if (ARGUMENT_PACK_P (t))
4896 tree args = ARGUMENT_PACK_ARGS (t);
4897 if (TREE_VEC_LENGTH (args) == 1
4898 && PACK_EXPANSION_P (TREE_VEC_ELT (args, 0)))
4899 t = PACK_EXPANSION_PATTERN (TREE_VEC_ELT (args, 0));
4902 if (REFERENCE_REF_P (t))
4903 t = TREE_OPERAND (t, 0);
4905 if (TEMPLATE_PARM_P (t))
4906 return t;
4907 else
4908 return NULL_TREE;
4911 /* Given a single level of template parameters (a TREE_VEC), return it
4912 as a set of template arguments. */
4914 tree
4915 template_parms_level_to_args (tree parms)
4917 parms = copy_node (parms);
4918 TREE_TYPE (parms) = NULL_TREE;
4919 for (tree& parm : tree_vec_range (parms))
4920 parm = template_parm_to_arg (parm);
4922 if (CHECKING_P)
4923 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (parms, TREE_VEC_LENGTH (parms));
4925 return parms;
4928 /* Given a set of template parameters, return them as a set of template
4929 arguments. The template parameters are represented as a TREE_VEC, in
4930 the form documented in cp-tree.h for template arguments. */
4932 tree
4933 template_parms_to_args (tree parms)
4935 tree header;
4936 tree args = NULL_TREE;
4937 int length = TMPL_PARMS_DEPTH (parms);
4938 int l = length;
4940 /* If there is only one level of template parameters, we do not
4941 create a TREE_VEC of TREE_VECs. Instead, we return a single
4942 TREE_VEC containing the arguments. */
4943 if (length > 1)
4944 args = make_tree_vec (length);
4946 for (header = parms; header; header = TREE_CHAIN (header))
4948 tree a = template_parms_level_to_args (TREE_VALUE (header));
4950 if (length > 1)
4951 TREE_VEC_ELT (args, --l) = a;
4952 else
4953 args = a;
4956 return args;
4959 /* Within the declaration of a template, return the currently active
4960 template parameters as an argument TREE_VEC. */
4962 static tree
4963 current_template_args (void)
4965 return template_parms_to_args (current_template_parms);
4968 /* Return the fully generic arguments for of TMPL, i.e. what
4969 current_template_args would be while parsing it. */
4971 tree
4972 generic_targs_for (tree tmpl)
4974 if (tmpl == NULL_TREE)
4975 return NULL_TREE;
4976 if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
4977 || DECL_TEMPLATE_SPECIALIZATION (tmpl))
4978 /* DECL_TEMPLATE_RESULT doesn't have the arguments we want. For a template
4979 template parameter, it has no TEMPLATE_INFO; for a partial
4980 specialization, it has the arguments for the primary template, and we
4981 want the arguments for the partial specialization. */;
4982 else if (tree result = DECL_TEMPLATE_RESULT (tmpl))
4983 if (tree ti = get_template_info (result))
4984 return TI_ARGS (ti);
4985 return template_parms_to_args (DECL_TEMPLATE_PARMS (tmpl));
4988 /* Return the template arguments corresponding to the template parameters of
4989 DECL's enclosing scope. When DECL is a member of a partial specialization,
4990 this returns the arguments for the partial specialization as opposed to those
4991 for the primary template, which is the main difference between this function
4992 and simply using e.g. the TYPE_TI_ARGS of DECL's DECL_CONTEXT. */
4994 tree
4995 outer_template_args (const_tree decl)
4997 if (TREE_CODE (decl) == TEMPLATE_DECL)
4998 decl = DECL_TEMPLATE_RESULT (decl);
4999 tree ti = get_template_info (decl);
5000 if (!ti)
5001 return NULL_TREE;
5002 tree args = TI_ARGS (ti);
5003 if (!PRIMARY_TEMPLATE_P (TI_TEMPLATE (ti)))
5004 return args;
5005 if (TMPL_ARGS_DEPTH (args) == 1)
5006 return NULL_TREE;
5007 return strip_innermost_template_args (args, 1);
5010 /* Update the declared TYPE by doing any lookups which were thought to be
5011 dependent, but are not now that we know the SCOPE of the declarator. */
5013 tree
5014 maybe_update_decl_type (tree orig_type, tree scope)
5016 tree type = orig_type;
5018 if (type == NULL_TREE)
5019 return type;
5021 if (TREE_CODE (orig_type) == TYPE_DECL)
5022 type = TREE_TYPE (type);
5024 if (scope && TYPE_P (scope) && dependent_type_p (scope)
5025 && dependent_type_p (type)
5026 /* Don't bother building up the args in this case. */
5027 && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
5029 /* tsubst in the args corresponding to the template parameters,
5030 including auto if present. Most things will be unchanged, but
5031 make_typename_type and tsubst_qualified_id will resolve
5032 TYPENAME_TYPEs and SCOPE_REFs that were previously dependent. */
5033 tree args = current_template_args ();
5034 tree auto_node = type_uses_auto (type);
5035 tree pushed;
5036 if (auto_node)
5038 tree auto_vec = make_tree_vec (1);
5039 TREE_VEC_ELT (auto_vec, 0) = auto_node;
5040 args = add_to_template_args (args, auto_vec);
5042 pushed = push_scope (scope);
5043 type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
5044 if (pushed)
5045 pop_scope (scope);
5048 if (type == error_mark_node)
5049 return orig_type;
5051 if (TREE_CODE (orig_type) == TYPE_DECL)
5053 if (same_type_p (type, TREE_TYPE (orig_type)))
5054 type = orig_type;
5055 else
5056 type = TYPE_NAME (type);
5058 return type;
5061 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
5062 template PARMS and constraints, CONSTR. If MEMBER_TEMPLATE_P is true,
5063 the new template is a member template. */
5065 static tree
5066 build_template_decl (tree decl, tree parms, bool member_template_p)
5068 gcc_checking_assert (TREE_CODE (decl) != TEMPLATE_DECL);
5070 tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
5071 SET_DECL_LANGUAGE (tmpl, DECL_LANGUAGE (decl));
5072 DECL_TEMPLATE_PARMS (tmpl) = parms;
5073 DECL_TEMPLATE_RESULT (tmpl) = decl;
5074 DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
5075 TREE_TYPE (tmpl) = TREE_TYPE (decl);
5076 DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
5077 DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
5079 /* Propagate module information from the decl. */
5080 DECL_MODULE_EXPORT_P (tmpl) = DECL_MODULE_EXPORT_P (decl);
5082 return tmpl;
5085 struct template_parm_data
5087 /* The level of the template parameters we are currently
5088 processing. */
5089 int level;
5091 /* The index of the specialization argument we are currently
5092 processing. */
5093 int current_arg;
5095 /* An array whose size is the number of template parameters. The
5096 elements are nonzero if the parameter has been used in any one
5097 of the arguments processed so far. */
5098 int* parms;
5100 /* An array whose size is the number of template arguments. The
5101 elements are nonzero if the argument makes use of template
5102 parameters of this level. */
5103 int* arg_uses_template_parms;
5106 /* Subroutine of push_template_decl used to see if each template
5107 parameter in a partial specialization is used in the explicit
5108 argument list. If T is of the LEVEL given in DATA (which is
5109 treated as a template_parm_data*), then DATA->PARMS is marked
5110 appropriately. */
5112 static int
5113 mark_template_parm (tree t, void* data)
5115 int level;
5116 int idx;
5117 struct template_parm_data* tpd = (struct template_parm_data*) data;
5119 template_parm_level_and_index (t, &level, &idx);
5121 if (level == tpd->level)
5123 tpd->parms[idx] = 1;
5124 tpd->arg_uses_template_parms[tpd->current_arg] = 1;
5127 /* In C++17 the type of a non-type argument is a deduced context. */
5128 if (cxx_dialect >= cxx17
5129 && TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5130 for_each_template_parm (TREE_TYPE (t),
5131 &mark_template_parm,
5132 data,
5133 NULL,
5134 /*include_nondeduced_p=*/false);
5136 /* Return zero so that for_each_template_parm will continue the
5137 traversal of the tree; we want to mark *every* template parm. */
5138 return 0;
5141 /* Process the partial specialization DECL. */
5143 static tree
5144 process_partial_specialization (tree decl)
5146 tree type = TREE_TYPE (decl);
5147 tree tinfo = get_template_info (decl);
5148 tree maintmpl = TI_TEMPLATE (tinfo);
5149 tree specargs = TI_ARGS (tinfo);
5150 tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
5151 tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
5152 tree inner_parms;
5153 tree inst;
5154 int nargs = TREE_VEC_LENGTH (inner_args);
5155 int ntparms;
5156 int i;
5157 struct template_parm_data tpd;
5158 struct template_parm_data tpd2;
5160 gcc_assert (current_template_parms);
5162 inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
5163 ntparms = TREE_VEC_LENGTH (inner_parms);
5165 /* We check that each of the template parameters given in the
5166 partial specialization is used in the argument list to the
5167 specialization. For example:
5169 template <class T> struct S;
5170 template <class T> struct S<T*>;
5172 The second declaration is OK because `T*' uses the template
5173 parameter T, whereas
5175 template <class T> struct S<int>;
5177 is no good. Even trickier is:
5179 template <class T>
5180 struct S1
5182 template <class U>
5183 struct S2;
5184 template <class U>
5185 struct S2<T>;
5188 The S2<T> declaration is actually invalid; it is a
5189 full-specialization. Of course,
5191 template <class U>
5192 struct S2<T (*)(U)>;
5194 or some such would have been OK. */
5195 tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
5196 tpd.parms = XALLOCAVEC (int, ntparms);
5197 memset (tpd.parms, 0, sizeof (int) * ntparms);
5199 tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
5200 memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
5201 for (i = 0; i < nargs; ++i)
5203 tpd.current_arg = i;
5204 for_each_template_parm (TREE_VEC_ELT (inner_args, i),
5205 &mark_template_parm,
5206 &tpd,
5207 NULL,
5208 /*include_nondeduced_p=*/false);
5212 auto_diagnostic_group d;
5213 bool did_error_intro = false;
5214 for (i = 0; i < ntparms; ++i)
5215 if (tpd.parms[i] == 0)
5217 /* One of the template parms was not used in a deduced context in the
5218 specialization. */
5219 if (!did_error_intro)
5221 error ("template parameters not deducible in "
5222 "partial specialization:");
5223 did_error_intro = true;
5226 inform (input_location, " %qD",
5227 TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
5230 if (did_error_intro)
5231 return error_mark_node;
5234 /* [temp.class.spec]
5236 The argument list of the specialization shall not be identical to
5237 the implicit argument list of the primary template. */
5238 tree main_args
5239 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (maintmpl)));
5240 if (comp_template_args (inner_args, INNERMOST_TEMPLATE_ARGS (main_args))
5241 && (!flag_concepts
5242 || !strictly_subsumes (current_template_constraints (), maintmpl)))
5244 auto_diagnostic_group d;
5245 if (!flag_concepts)
5246 error ("partial specialization %q+D does not specialize "
5247 "any template arguments; to define the primary template, "
5248 "remove the template argument list", decl);
5249 else
5250 error ("partial specialization %q+D does not specialize any "
5251 "template arguments and is not more constrained than "
5252 "the primary template; to define the primary template, "
5253 "remove the template argument list", decl);
5254 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5257 /* A partial specialization that replaces multiple parameters of the
5258 primary template with a pack expansion is less specialized for those
5259 parameters. */
5260 if (nargs < DECL_NTPARMS (maintmpl))
5262 auto_diagnostic_group d;
5263 error ("partial specialization is not more specialized than the "
5264 "primary template because it replaces multiple parameters "
5265 "with a pack expansion");
5266 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5267 /* Avoid crash in process_partial_specialization. */
5268 return decl;
5271 else if (nargs > DECL_NTPARMS (maintmpl))
5273 auto_diagnostic_group d;
5274 error ("too many arguments for partial specialization %qT", type);
5275 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5276 /* Avoid crash below. */
5277 return decl;
5280 /* If we aren't in a dependent class, we can actually try deduction. */
5281 else if (tpd.level == 1
5282 /* FIXME we should be able to handle a partial specialization of a
5283 partial instantiation, but currently we can't (c++/41727). */
5284 && TMPL_ARGS_DEPTH (specargs) == 1
5285 && !get_partial_spec_bindings (maintmpl, maintmpl, specargs))
5287 auto_diagnostic_group d;
5288 if (pedwarn (input_location, 0,
5289 "partial specialization %qD is not more specialized than",
5290 decl))
5291 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template %qD",
5292 maintmpl);
5295 /* [temp.spec.partial]
5297 The type of a template parameter corresponding to a specialized
5298 non-type argument shall not be dependent on a parameter of the
5299 specialization.
5301 Also, we verify that pack expansions only occur at the
5302 end of the argument list. */
5303 tpd2.parms = 0;
5304 for (i = 0; i < nargs; ++i)
5306 tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
5307 tree arg = TREE_VEC_ELT (inner_args, i);
5308 tree packed_args = NULL_TREE;
5309 int j, len = 1;
5311 if (ARGUMENT_PACK_P (arg))
5313 /* Extract the arguments from the argument pack. We'll be
5314 iterating over these in the following loop. */
5315 packed_args = ARGUMENT_PACK_ARGS (arg);
5316 len = TREE_VEC_LENGTH (packed_args);
5319 for (j = 0; j < len; j++)
5321 if (packed_args)
5322 /* Get the Jth argument in the parameter pack. */
5323 arg = TREE_VEC_ELT (packed_args, j);
5325 if (PACK_EXPANSION_P (arg))
5327 /* Pack expansions must come at the end of the
5328 argument list. */
5329 if ((packed_args && j < len - 1)
5330 || (!packed_args && i < nargs - 1))
5332 if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5333 error ("parameter pack argument %qE must be at the "
5334 "end of the template argument list", arg);
5335 else
5336 error ("parameter pack argument %qT must be at the "
5337 "end of the template argument list", arg);
5341 if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5342 /* We only care about the pattern. */
5343 arg = PACK_EXPANSION_PATTERN (arg);
5345 if (/* These first two lines are the `non-type' bit. */
5346 !TYPE_P (arg)
5347 && TREE_CODE (arg) != TEMPLATE_DECL
5348 /* This next two lines are the `argument expression is not just a
5349 simple identifier' condition and also the `specialized
5350 non-type argument' bit. */
5351 && TREE_CODE (arg) != TEMPLATE_PARM_INDEX
5352 && !((REFERENCE_REF_P (arg)
5353 || TREE_CODE (arg) == VIEW_CONVERT_EXPR)
5354 && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_PARM_INDEX))
5356 /* Look at the corresponding template parameter,
5357 marking which template parameters its type depends
5358 upon. */
5359 tree type = TREE_TYPE (parm);
5361 if (!tpd2.parms)
5363 /* We haven't yet initialized TPD2. Do so now. */
5364 tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
5365 /* The number of parameters here is the number in the
5366 main template, which, as checked in the assertion
5367 above, is NARGS. */
5368 tpd2.parms = XALLOCAVEC (int, nargs);
5369 tpd2.level =
5370 TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
5373 /* Mark the template parameters. But this time, we're
5374 looking for the template parameters of the main
5375 template, not in the specialization. */
5376 tpd2.current_arg = i;
5377 tpd2.arg_uses_template_parms[i] = 0;
5378 memset (tpd2.parms, 0, sizeof (int) * nargs);
5379 for_each_template_parm (type,
5380 &mark_template_parm,
5381 &tpd2,
5382 NULL,
5383 /*include_nondeduced_p=*/false);
5385 if (tpd2.arg_uses_template_parms [i])
5387 /* The type depended on some template parameters.
5388 If they are fully specialized in the
5389 specialization, that's OK. */
5390 int j;
5391 int count = 0;
5392 for (j = 0; j < nargs; ++j)
5393 if (tpd2.parms[j] != 0
5394 && tpd.arg_uses_template_parms [j])
5395 ++count;
5396 if (count != 0)
5397 error_n (input_location, count,
5398 "type %qT of template argument %qE depends "
5399 "on a template parameter",
5400 "type %qT of template argument %qE depends "
5401 "on template parameters",
5402 type,
5403 arg);
5409 /* We should only get here once. */
5410 if (TREE_CODE (decl) == TYPE_DECL)
5411 gcc_assert (!COMPLETE_TYPE_P (type));
5413 // Build the template decl.
5414 tree tmpl = build_template_decl (decl, current_template_parms,
5415 DECL_MEMBER_TEMPLATE_P (maintmpl));
5416 SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5417 DECL_TEMPLATE_INFO (tmpl) = build_template_info (maintmpl, specargs);
5418 DECL_PRIMARY_TEMPLATE (tmpl) = maintmpl;
5420 /* Give template template parms a DECL_CONTEXT of the template
5421 for which they are a parameter. */
5422 for (i = 0; i < ntparms; ++i)
5424 tree parm = TREE_VALUE (TREE_VEC_ELT (inner_parms, i));
5425 if (TREE_CODE (parm) == TEMPLATE_DECL)
5426 DECL_CONTEXT (parm) = tmpl;
5429 if (VAR_P (decl))
5431 /* We didn't register this in check_explicit_specialization so we could
5432 wait until the constraints were set. */
5433 tree reg = register_specialization (decl, maintmpl, specargs, false, 0);
5434 if (reg != decl)
5435 /* Redeclaration. */
5436 return reg;
5438 else
5439 associate_classtype_constraints (type);
5441 DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
5442 = tree_cons (specargs, tmpl,
5443 DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
5444 TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
5445 /* Link the DECL_TEMPLATE_RESULT back to the partial TEMPLATE_DECL. */
5446 gcc_checking_assert (!TI_PARTIAL_INFO (tinfo));
5447 TI_PARTIAL_INFO (tinfo) = build_template_info (tmpl, NULL_TREE);
5449 set_defining_module_for_partial_spec (decl);
5451 for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
5452 inst = TREE_CHAIN (inst))
5454 tree instance = TREE_VALUE (inst);
5455 if (TYPE_P (instance)
5456 ? (COMPLETE_TYPE_P (instance)
5457 && CLASSTYPE_IMPLICIT_INSTANTIATION (instance))
5458 : DECL_TEMPLATE_INSTANTIATION (instance))
5460 tree partial_ti = most_specialized_partial_spec (instance, tf_none,
5461 /*rechecking=*/true);
5462 tree inst_decl = (DECL_P (instance)
5463 ? instance : TYPE_NAME (instance));
5464 if (!partial_ti)
5465 /* OK */;
5466 else if (partial_ti == error_mark_node)
5467 permerror (input_location,
5468 "declaration of %qD ambiguates earlier template "
5469 "instantiation for %qD", decl, inst_decl);
5470 else if (TI_TEMPLATE (partial_ti) == tmpl)
5471 permerror (input_location,
5472 "partial specialization of %qD after instantiation "
5473 "of %qD", decl, inst_decl);
5477 return decl;
5480 /* PARM is a template parameter of some form; return the corresponding
5481 TEMPLATE_PARM_INDEX. */
5483 static tree
5484 get_template_parm_index (tree parm)
5486 if (TREE_CODE (parm) == PARM_DECL
5487 || TREE_CODE (parm) == CONST_DECL)
5488 parm = DECL_INITIAL (parm);
5489 else if (TREE_CODE (parm) == TYPE_DECL
5490 || TREE_CODE (parm) == TEMPLATE_DECL)
5491 parm = TREE_TYPE (parm);
5492 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
5493 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM
5494 || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
5495 parm = TEMPLATE_TYPE_PARM_INDEX (parm);
5496 gcc_assert (TREE_CODE (parm) == TEMPLATE_PARM_INDEX);
5497 return parm;
5500 /* Subroutine of fixed_parameter_pack_p below. Look for any template
5501 parameter packs used by the template parameter PARM. */
5503 static void
5504 fixed_parameter_pack_p_1 (tree parm, struct find_parameter_pack_data *ppd)
5506 /* A type parm can't refer to another parm. */
5507 if (TREE_CODE (parm) == TYPE_DECL || parm == error_mark_node)
5508 return;
5509 else if (TREE_CODE (parm) == PARM_DECL)
5511 cp_walk_tree (&TREE_TYPE (parm), &find_parameter_packs_r,
5512 ppd, ppd->visited);
5513 return;
5516 gcc_assert (TREE_CODE (parm) == TEMPLATE_DECL);
5518 tree vec = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
5519 for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
5521 tree p = TREE_VALUE (TREE_VEC_ELT (vec, i));
5522 if (template_parameter_pack_p (p))
5523 /* Any packs in the type are expanded by this parameter. */;
5524 else
5525 fixed_parameter_pack_p_1 (p, ppd);
5529 /* PARM is a template parameter pack. Return any parameter packs used in
5530 its type or the type of any of its template parameters. If there are
5531 any such packs, it will be instantiated into a fixed template parameter
5532 list by partial instantiation rather than be fully deduced. */
5534 tree
5535 fixed_parameter_pack_p (tree parm)
5537 /* This can only be true in a member template. */
5538 if (TEMPLATE_PARM_ORIG_LEVEL (get_template_parm_index (parm)) < 2)
5539 return NULL_TREE;
5540 /* This can only be true for a parameter pack. */
5541 if (!template_parameter_pack_p (parm))
5542 return NULL_TREE;
5543 /* A type parm can't refer to another parm. */
5544 if (TREE_CODE (parm) == TYPE_DECL)
5545 return NULL_TREE;
5547 tree parameter_packs = NULL_TREE;
5548 struct find_parameter_pack_data ppd;
5549 ppd.parameter_packs = &parameter_packs;
5550 ppd.visited = new hash_set<tree>;
5552 fixed_parameter_pack_p_1 (parm, &ppd);
5554 delete ppd.visited;
5555 return parameter_packs;
5558 /* Check that a template declaration's use of default arguments and
5559 parameter packs is not invalid. Here, PARMS are the template
5560 parameters. IS_PRIMARY is true if DECL is the thing declared by
5561 a primary template. IS_PARTIAL is true if DECL is a partial
5562 specialization.
5564 IS_FRIEND_DECL is nonzero if DECL is either a non-defining friend
5565 function template declaration or a friend class template
5566 declaration. In the function case, 1 indicates a declaration, 2
5567 indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
5568 emitted for extraneous default arguments.
5570 Returns TRUE if there were no errors found, FALSE otherwise. */
5572 bool
5573 check_default_tmpl_args (tree decl, tree parms, bool is_primary,
5574 bool is_partial, int is_friend_decl)
5576 const char *msg;
5577 int last_level_to_check;
5578 tree parm_level;
5579 bool no_errors = true;
5581 /* [temp.param]
5583 A default template-argument shall not be specified in a
5584 function template declaration or a function template definition, nor
5585 in the template-parameter-list of the definition of a member of a
5586 class template. */
5588 if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL
5589 || (TREE_CODE (decl) == FUNCTION_DECL && DECL_LOCAL_DECL_P (decl)))
5590 /* You can't have a function template declaration in a local
5591 scope, nor you can you define a member of a class template in a
5592 local scope. */
5593 return true;
5595 if ((TREE_CODE (decl) == TYPE_DECL
5596 && TREE_TYPE (decl)
5597 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5598 || (TREE_CODE (decl) == FUNCTION_DECL
5599 && LAMBDA_FUNCTION_P (decl)))
5600 /* A lambda doesn't have an explicit declaration; don't complain
5601 about the parms of the enclosing class. */
5602 return true;
5604 if (current_class_type
5605 && !TYPE_BEING_DEFINED (current_class_type)
5606 && DECL_LANG_SPECIFIC (decl)
5607 && DECL_DECLARES_FUNCTION_P (decl)
5608 /* If this is either a friend defined in the scope of the class
5609 or a member function. */
5610 && (DECL_FUNCTION_MEMBER_P (decl)
5611 ? same_type_p (DECL_CONTEXT (decl), current_class_type)
5612 : DECL_FRIEND_CONTEXT (decl)
5613 ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
5614 : false)
5615 /* And, if it was a member function, it really was defined in
5616 the scope of the class. */
5617 && (!DECL_FUNCTION_MEMBER_P (decl)
5618 || DECL_INITIALIZED_IN_CLASS_P (decl)))
5619 /* We already checked these parameters when the template was
5620 declared, so there's no need to do it again now. This function
5621 was defined in class scope, but we're processing its body now
5622 that the class is complete. */
5623 return true;
5625 /* Core issue 226 (C++0x only): the following only applies to class
5626 templates. */
5627 if (is_primary
5628 && ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL))
5630 /* [temp.param]
5632 If a template-parameter has a default template-argument, all
5633 subsequent template-parameters shall have a default
5634 template-argument supplied. */
5635 for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
5637 tree inner_parms = TREE_VALUE (parm_level);
5638 int ntparms = TREE_VEC_LENGTH (inner_parms);
5639 int seen_def_arg_p = 0;
5640 int i;
5642 for (i = 0; i < ntparms; ++i)
5644 tree parm = TREE_VEC_ELT (inner_parms, i);
5646 if (parm == error_mark_node)
5647 continue;
5649 if (TREE_PURPOSE (parm))
5650 seen_def_arg_p = 1;
5651 else if (seen_def_arg_p
5652 && !template_parameter_pack_p (TREE_VALUE (parm)))
5654 error ("no default argument for %qD", TREE_VALUE (parm));
5655 /* For better subsequent error-recovery, we indicate that
5656 there should have been a default argument. */
5657 TREE_PURPOSE (parm) = error_mark_node;
5658 no_errors = false;
5660 else if (!is_partial
5661 && !is_friend_decl
5662 /* Don't complain about an enclosing partial
5663 specialization. */
5664 && parm_level == parms
5665 && (TREE_CODE (decl) == TYPE_DECL || VAR_P (decl))
5666 && i < ntparms - 1
5667 && template_parameter_pack_p (TREE_VALUE (parm))
5668 /* A fixed parameter pack will be partially
5669 instantiated into a fixed length list. */
5670 && !fixed_parameter_pack_p (TREE_VALUE (parm)))
5672 /* A primary class template, primary variable template
5673 (DR 2032), or alias template can only have one
5674 parameter pack, at the end of the template
5675 parameter list. */
5677 error ("parameter pack %q+D must be at the end of the"
5678 " template parameter list", TREE_VALUE (parm));
5680 TREE_VALUE (TREE_VEC_ELT (inner_parms, i))
5681 = error_mark_node;
5682 no_errors = false;
5688 if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
5689 || is_partial
5690 || !is_primary
5691 || is_friend_decl)
5692 /* For an ordinary class template, default template arguments are
5693 allowed at the innermost level, e.g.:
5694 template <class T = int>
5695 struct S {};
5696 but, in a partial specialization, they're not allowed even
5697 there, as we have in [temp.class.spec]:
5699 The template parameter list of a specialization shall not
5700 contain default template argument values.
5702 So, for a partial specialization, or for a function template
5703 (in C++98/C++03), we look at all of them. */
5705 else
5706 /* But, for a primary class template that is not a partial
5707 specialization we look at all template parameters except the
5708 innermost ones. */
5709 parms = TREE_CHAIN (parms);
5711 /* Figure out what error message to issue. */
5712 if (is_friend_decl == 2)
5713 msg = G_("default template arguments may not be used in function template "
5714 "friend re-declaration");
5715 else if (is_friend_decl)
5716 msg = G_("default template arguments may not be used in template "
5717 "friend declarations");
5718 else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
5719 msg = G_("default template arguments may not be used in function templates "
5720 "without %<-std=c++11%> or %<-std=gnu++11%>");
5721 else if (is_partial)
5722 msg = G_("default template arguments may not be used in "
5723 "partial specializations");
5724 else if (current_class_type && CLASSTYPE_IS_TEMPLATE (current_class_type))
5725 msg = G_("default argument for template parameter for class enclosing %qD");
5726 else
5727 /* Per [temp.param]/9, "A default template-argument shall not be
5728 specified in the template-parameter-lists of the definition of
5729 a member of a class template that appears outside of the member's
5730 class.", thus if we aren't handling a member of a class template
5731 there is no need to examine the parameters. */
5732 return true;
5734 if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
5735 /* If we're inside a class definition, there's no need to
5736 examine the parameters to the class itself. On the one
5737 hand, they will be checked when the class is defined, and,
5738 on the other, default arguments are valid in things like:
5739 template <class T = double>
5740 struct S { template <class U> void f(U); };
5741 Here the default argument for `S' has no bearing on the
5742 declaration of `f'. */
5743 last_level_to_check = template_class_depth (current_class_type) + 1;
5744 else
5745 /* Check everything. */
5746 last_level_to_check = 0;
5748 for (parm_level = parms;
5749 parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
5750 parm_level = TREE_CHAIN (parm_level))
5752 tree inner_parms = TREE_VALUE (parm_level);
5753 int i;
5754 int ntparms;
5756 ntparms = TREE_VEC_LENGTH (inner_parms);
5757 for (i = 0; i < ntparms; ++i)
5759 if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
5760 continue;
5762 if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
5764 if (msg)
5766 no_errors = false;
5767 if (is_friend_decl == 2)
5768 return no_errors;
5770 error (msg, decl);
5771 msg = 0;
5774 /* Clear out the default argument so that we are not
5775 confused later. */
5776 TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
5780 /* At this point, if we're still interested in issuing messages,
5781 they must apply to classes surrounding the object declared. */
5782 if (msg)
5783 msg = G_("default argument for template parameter for class "
5784 "enclosing %qD");
5787 return no_errors;
5790 /* Worker for push_template_decl_real, called via
5791 for_each_template_parm. DATA is really an int, indicating the
5792 level of the parameters we are interested in. If T is a template
5793 parameter of that level, return nonzero. */
5795 static int
5796 template_parm_this_level_p (tree t, void* data)
5798 int this_level = *(int *)data;
5799 int level;
5801 if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5802 level = TEMPLATE_PARM_LEVEL (t);
5803 else
5804 level = TEMPLATE_TYPE_LEVEL (t);
5805 return level == this_level;
5808 /* Worker for uses_outer_template_parms, called via for_each_template_parm.
5809 DATA is really an int, indicating the innermost outer level of parameters.
5810 If T is a template parameter of that level or further out, return
5811 nonzero. */
5813 static int
5814 template_parm_outer_level (tree t, void *data)
5816 int this_level = *(int *)data;
5817 int level;
5819 if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5820 level = TEMPLATE_PARM_LEVEL (t);
5821 else
5822 level = TEMPLATE_TYPE_LEVEL (t);
5823 return level <= this_level;
5826 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
5827 parameters given by current_template_args, or reuses a
5828 previously existing one, if appropriate. Returns the DECL, or an
5829 equivalent one, if it is replaced via a call to duplicate_decls.
5831 If IS_FRIEND is true, DECL is a friend declaration. */
5833 tree
5834 push_template_decl (tree decl, bool is_friend)
5836 if (decl == error_mark_node || !current_template_parms)
5837 return error_mark_node;
5839 /* See if this is a partial specialization. */
5840 bool is_partial = ((DECL_IMPLICIT_TYPEDEF_P (decl)
5841 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
5842 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
5843 || (VAR_P (decl)
5844 && DECL_LANG_SPECIFIC (decl)
5845 && DECL_TEMPLATE_SPECIALIZATION (decl)
5846 && TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl))));
5848 /* No surprising friend functions. */
5849 gcc_checking_assert (is_friend
5850 || !(TREE_CODE (decl) == FUNCTION_DECL
5851 && DECL_UNIQUE_FRIEND_P (decl)));
5853 tree ctx;
5854 if (is_friend)
5855 /* For a friend, we want the context of the friend, not
5856 the type of which it is a friend. */
5857 ctx = CP_DECL_CONTEXT (decl);
5858 else if (CP_DECL_CONTEXT (decl)
5859 && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
5860 /* In the case of a virtual function, we want the class in which
5861 it is defined. */
5862 ctx = CP_DECL_CONTEXT (decl);
5863 else
5864 /* Otherwise, if we're currently defining some class, the DECL
5865 is assumed to be a member of the class. */
5866 ctx = current_scope ();
5868 if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
5869 ctx = NULL_TREE;
5871 if (!DECL_CONTEXT (decl))
5872 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5874 /* See if this is a primary template. */
5875 bool is_primary = false;
5876 if (is_friend && ctx
5877 && uses_template_parms_level (ctx, current_template_depth))
5878 /* A friend template that specifies a class context, i.e.
5879 template <typename T> friend void A<T>::f();
5880 is not primary. */
5882 else if (TREE_CODE (decl) == TYPE_DECL && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5883 /* Lambdas are not primary. */
5885 else
5886 is_primary = template_parm_scope_p ();
5888 /* True if the template is a member template, in the sense of
5889 [temp.mem]. */
5890 bool member_template_p = false;
5892 if (is_primary)
5894 warning (OPT_Wtemplates, "template %qD declared", decl);
5896 if (DECL_CLASS_SCOPE_P (decl))
5897 member_template_p = true;
5899 if (TREE_CODE (decl) == TYPE_DECL
5900 && IDENTIFIER_ANON_P (DECL_NAME (decl)))
5902 error ("template class without a name");
5903 return error_mark_node;
5905 else if (TREE_CODE (decl) == FUNCTION_DECL)
5907 if (member_template_p)
5909 if (DECL_OVERRIDE_P (decl) || DECL_FINAL_P (decl))
5910 error ("member template %qD may not have virt-specifiers", decl);
5912 if (DECL_DESTRUCTOR_P (decl))
5914 /* [temp.mem]
5916 A destructor shall not be a member template. */
5917 error_at (DECL_SOURCE_LOCATION (decl),
5918 "destructor %qD declared as member template", decl);
5919 return error_mark_node;
5921 if (IDENTIFIER_NEWDEL_OP_P (DECL_NAME (decl))
5922 && (!prototype_p (TREE_TYPE (decl))
5923 || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
5924 || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5925 || (TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5926 == void_list_node)))
5928 /* [basic.stc.dynamic.allocation]
5930 An allocation function can be a function
5931 template. ... Template allocation functions shall
5932 have two or more parameters. */
5933 error ("invalid template declaration of %qD", decl);
5934 return error_mark_node;
5937 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5938 && CLASS_TYPE_P (TREE_TYPE (decl)))
5939 /* Class template. */;
5940 else if (TREE_CODE (decl) == TYPE_DECL
5941 && TYPE_DECL_ALIAS_P (decl))
5942 /* alias-declaration */
5943 gcc_assert (!DECL_ARTIFICIAL (decl));
5944 else if (VAR_P (decl))
5945 /* C++14 variable template. */;
5946 else if (TREE_CODE (decl) == CONCEPT_DECL)
5947 /* C++20 concept definitions. */;
5948 else
5950 error ("template declaration of %q#D", decl);
5951 return error_mark_node;
5955 bool local_p = (!DECL_IMPLICIT_TYPEDEF_P (decl)
5956 && ((ctx && TREE_CODE (ctx) == FUNCTION_DECL)
5957 || (VAR_OR_FUNCTION_DECL_P (decl)
5958 && DECL_LOCAL_DECL_P (decl))));
5960 /* Check to see that the rules regarding the use of default
5961 arguments are not being violated. We check args for a friend
5962 functions when we know whether it's a definition, introducing
5963 declaration or re-declaration. */
5964 if (!local_p && (!is_friend || TREE_CODE (decl) != FUNCTION_DECL))
5965 check_default_tmpl_args (decl, current_template_parms,
5966 is_primary, is_partial, is_friend);
5968 /* Ensure that there are no parameter packs in the type of this
5969 declaration that have not been expanded. */
5970 if (TREE_CODE (decl) == FUNCTION_DECL)
5972 /* Check each of the arguments individually to see if there are
5973 any bare parameter packs. */
5974 tree type = TREE_TYPE (decl);
5975 tree arg = DECL_ARGUMENTS (decl);
5976 tree argtype = TYPE_ARG_TYPES (type);
5978 while (arg && argtype)
5980 if (!DECL_PACK_P (arg)
5981 && check_for_bare_parameter_packs (TREE_TYPE (arg)))
5983 /* This is a PARM_DECL that contains unexpanded parameter
5984 packs. We have already complained about this in the
5985 check_for_bare_parameter_packs call, so just replace
5986 these types with ERROR_MARK_NODE. */
5987 TREE_TYPE (arg) = error_mark_node;
5988 TREE_VALUE (argtype) = error_mark_node;
5991 arg = DECL_CHAIN (arg);
5992 argtype = TREE_CHAIN (argtype);
5995 /* Check for bare parameter packs in the return type and the
5996 exception specifiers. */
5997 if (check_for_bare_parameter_packs (TREE_TYPE (type)))
5998 /* Errors were already issued, set return type to int
5999 as the frontend doesn't expect error_mark_node as
6000 the return type. */
6001 TREE_TYPE (type) = integer_type_node;
6002 if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
6003 TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
6005 else
6007 if (check_for_bare_parameter_packs (is_typedef_decl (decl)
6008 ? DECL_ORIGINAL_TYPE (decl)
6009 : TREE_TYPE (decl)))
6011 TREE_TYPE (decl) = error_mark_node;
6012 return error_mark_node;
6015 if (is_partial && VAR_P (decl)
6016 && check_for_bare_parameter_packs (DECL_TI_ARGS (decl)))
6017 return error_mark_node;
6020 if (is_partial)
6021 return process_partial_specialization (decl);
6023 tree args = current_template_args ();
6024 tree tmpl = NULL_TREE;
6025 bool new_template_p = false;
6026 if (local_p)
6028 /* Does not get a template head. */
6029 tmpl = NULL_TREE;
6030 gcc_checking_assert (!is_primary);
6032 else if (!ctx
6033 || TREE_CODE (ctx) == FUNCTION_DECL
6034 || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
6035 || (TREE_CODE (decl) == TYPE_DECL && LAMBDA_TYPE_P (TREE_TYPE (decl)))
6036 || (is_friend && !(DECL_LANG_SPECIFIC (decl)
6037 && DECL_TEMPLATE_INFO (decl))))
6039 if (DECL_LANG_SPECIFIC (decl)
6040 && DECL_TEMPLATE_INFO (decl)
6041 && DECL_TI_TEMPLATE (decl))
6042 tmpl = DECL_TI_TEMPLATE (decl);
6043 /* If DECL is a TYPE_DECL for a class-template, then there won't
6044 be DECL_LANG_SPECIFIC. The information equivalent to
6045 DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead. */
6046 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
6047 && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
6048 && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
6050 /* Since a template declaration already existed for this
6051 class-type, we must be redeclaring it here. Make sure
6052 that the redeclaration is valid. */
6053 redeclare_class_template (TREE_TYPE (decl),
6054 current_template_parms,
6055 current_template_constraints ());
6056 /* We don't need to create a new TEMPLATE_DECL; just use the
6057 one we already had. */
6058 tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
6060 else
6062 tmpl = build_template_decl (decl, current_template_parms,
6063 member_template_p);
6064 new_template_p = true;
6066 if (DECL_LANG_SPECIFIC (decl)
6067 && DECL_TEMPLATE_SPECIALIZATION (decl))
6069 /* A specialization of a member template of a template
6070 class. */
6071 SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
6072 DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
6073 DECL_TEMPLATE_INFO (decl) = NULL_TREE;
6077 else
6079 tree a, t, current, parms;
6080 int i;
6081 tree tinfo = get_template_info (decl);
6083 if (!tinfo)
6085 error ("template definition of non-template %q#D", decl);
6086 return error_mark_node;
6089 tmpl = TI_TEMPLATE (tinfo);
6091 if (DECL_FUNCTION_TEMPLATE_P (tmpl)
6092 && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
6093 && DECL_TEMPLATE_SPECIALIZATION (decl)
6094 && DECL_MEMBER_TEMPLATE_P (tmpl))
6096 /* The declaration is a specialization of a member
6097 template, declared outside the class. Therefore, the
6098 innermost template arguments will be NULL, so we
6099 replace them with the arguments determined by the
6100 earlier call to check_explicit_specialization. */
6101 args = DECL_TI_ARGS (decl);
6103 tree new_tmpl
6104 = build_template_decl (decl, current_template_parms,
6105 member_template_p);
6106 DECL_TI_TEMPLATE (decl) = new_tmpl;
6107 SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
6108 DECL_TEMPLATE_INFO (new_tmpl)
6109 = build_template_info (tmpl, args);
6111 register_specialization (new_tmpl,
6112 most_general_template (tmpl),
6113 args,
6114 is_friend, 0);
6115 return decl;
6118 /* Make sure the template headers we got make sense. */
6120 parms = DECL_TEMPLATE_PARMS (tmpl);
6121 i = TMPL_PARMS_DEPTH (parms);
6122 if (TMPL_ARGS_DEPTH (args) != i)
6124 error ("expected %d levels of template parms for %q#D, got %d",
6125 i, decl, TMPL_ARGS_DEPTH (args));
6126 DECL_INTERFACE_KNOWN (decl) = 1;
6127 return error_mark_node;
6129 else
6130 for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
6132 a = TMPL_ARGS_LEVEL (args, i);
6133 t = INNERMOST_TEMPLATE_PARMS (parms);
6135 if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
6137 if (current == decl)
6138 error ("got %d template parameters for %q#D",
6139 TREE_VEC_LENGTH (a), decl);
6140 else
6141 error ("got %d template parameters for %q#T",
6142 TREE_VEC_LENGTH (a), current);
6143 error (" but %d required", TREE_VEC_LENGTH (t));
6144 /* Avoid crash in import_export_decl. */
6145 DECL_INTERFACE_KNOWN (decl) = 1;
6146 return error_mark_node;
6149 if (current == decl)
6150 current = ctx;
6151 else if (current == NULL_TREE)
6152 /* Can happen in erroneous input. */
6153 break;
6154 else
6155 current = get_containing_scope (current);
6158 /* Check that the parms are used in the appropriate qualifying scopes
6159 in the declarator. */
6160 if (!comp_template_args
6161 (TI_ARGS (tinfo),
6162 TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
6164 auto_diagnostic_group d;
6165 error ("template arguments to %qD do not match original "
6166 "template %qD", decl, DECL_TEMPLATE_RESULT (tmpl));
6167 if (!uses_template_parms (TI_ARGS (tinfo)))
6168 inform (input_location, "use %<template<>%> for"
6169 " an explicit specialization");
6170 /* Avoid crash in import_export_decl. */
6171 DECL_INTERFACE_KNOWN (decl) = 1;
6172 return error_mark_node;
6175 /* Check that the constraints for each enclosing template scope are
6176 consistent with the original declarations. */
6177 if (flag_concepts)
6179 tree decl_parms = DECL_TEMPLATE_PARMS (tmpl);
6180 tree scope_parms = current_template_parms;
6181 if (PRIMARY_TEMPLATE_P (tmpl))
6183 decl_parms = TREE_CHAIN (decl_parms);
6184 scope_parms = TREE_CHAIN (scope_parms);
6186 while (decl_parms)
6188 if (!template_requirements_equivalent_p (decl_parms, scope_parms))
6190 error ("redeclaration of %qD with different constraints",
6191 TPARMS_PRIMARY_TEMPLATE (TREE_VALUE (decl_parms)));
6192 break;
6194 decl_parms = TREE_CHAIN (decl_parms);
6195 scope_parms = TREE_CHAIN (scope_parms);
6200 gcc_checking_assert (!tmpl || DECL_TEMPLATE_RESULT (tmpl) == decl);
6202 if (new_template_p)
6204 /* Push template declarations for global functions and types.
6205 Note that we do not try to push a global template friend
6206 declared in a template class; such a thing may well depend on
6207 the template parameters of the class and we'll push it when
6208 instantiating the befriending class. */
6209 if (!ctx
6210 && !(is_friend && template_class_depth (current_class_type) > 0))
6212 tree pushed = pushdecl_namespace_level (tmpl, /*hiding=*/is_friend);
6213 if (pushed == error_mark_node)
6214 return error_mark_node;
6216 /* pushdecl may have found an existing template. */
6217 if (pushed != tmpl)
6219 decl = DECL_TEMPLATE_RESULT (pushed);
6220 tmpl = NULL_TREE;
6223 else if (is_friend)
6225 /* Record this decl as belonging to the current class. It's
6226 not chained onto anything else. */
6227 DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (tmpl) = true;
6228 gcc_checking_assert (!DECL_CHAIN (tmpl));
6229 DECL_CHAIN (tmpl) = current_scope ();
6232 else if (tmpl)
6233 /* The type may have been completed, or (erroneously) changed. */
6234 TREE_TYPE (tmpl) = TREE_TYPE (decl);
6236 if (tmpl)
6238 if (is_primary)
6240 tree parms = DECL_TEMPLATE_PARMS (tmpl);
6242 DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
6244 /* Give template template parms a DECL_CONTEXT of the template
6245 for which they are a parameter. */
6246 parms = INNERMOST_TEMPLATE_PARMS (parms);
6247 for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
6249 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
6250 if (TREE_CODE (parm) == TEMPLATE_DECL)
6251 DECL_CONTEXT (parm) = tmpl;
6254 if (TREE_CODE (decl) == TYPE_DECL
6255 && TYPE_DECL_ALIAS_P (decl))
6257 if (tree constr
6258 = TEMPLATE_PARMS_CONSTRAINTS (DECL_TEMPLATE_PARMS (tmpl)))
6260 /* ??? Why don't we do this here for all templates? */
6261 constr = build_constraints (constr, NULL_TREE);
6262 set_constraints (decl, constr);
6267 /* The DECL_TI_ARGS of DECL contains full set of arguments
6268 referring wback to its most general template. If TMPL is a
6269 specialization, ARGS may only have the innermost set of
6270 arguments. Add the missing argument levels if necessary. */
6271 if (DECL_TEMPLATE_INFO (tmpl))
6272 args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
6274 tree info = build_template_info (tmpl, args);
6276 if (DECL_IMPLICIT_TYPEDEF_P (decl))
6277 SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
6278 else
6280 retrofit_lang_decl (decl);
6281 DECL_TEMPLATE_INFO (decl) = info;
6285 if (is_typedef_decl (decl)
6286 && (dependent_opaque_alias_p (TREE_TYPE (decl))
6287 || dependent_alias_template_spec_p (TREE_TYPE (decl), nt_opaque)))
6289 /* Manually mark such aliases as dependent so that dependent_type_p_r
6290 doesn't have to handle them. */
6291 TYPE_DEPENDENT_P_VALID (TREE_TYPE (decl)) = true;
6292 TYPE_DEPENDENT_P (TREE_TYPE (decl)) = true;
6293 /* The identity of such aliases is hairy; see structural_comptypes. */
6294 SET_TYPE_STRUCTURAL_EQUALITY (TREE_TYPE (decl));
6297 if (flag_implicit_templates
6298 && !is_friend
6299 && TREE_PUBLIC (decl)
6300 && VAR_OR_FUNCTION_DECL_P (decl))
6301 /* Set DECL_COMDAT on template instantiations; if we force
6302 them to be emitted by explicit instantiation,
6303 mark_needed will tell cgraph to do the right thing. */
6304 DECL_COMDAT (decl) = true;
6306 gcc_checking_assert (!tmpl || DECL_TEMPLATE_RESULT (tmpl) == decl);
6308 return decl;
6311 /* FN is an inheriting constructor that inherits from the constructor
6312 template INHERITED; turn FN into a constructor template with a matching
6313 template header. */
6315 tree
6316 add_inherited_template_parms (tree fn, tree inherited)
6318 tree inner_parms
6319 = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (inherited));
6320 inner_parms = copy_node (inner_parms);
6321 tree parms
6322 = tree_cons (size_int (current_template_depth + 1),
6323 inner_parms, current_template_parms);
6324 tree tmpl = build_template_decl (fn, parms, /*member*/true);
6325 tree args = template_parms_to_args (parms);
6326 DECL_TEMPLATE_INFO (fn) = build_template_info (tmpl, args);
6327 DECL_ARTIFICIAL (tmpl) = true;
6328 DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
6329 return tmpl;
6332 /* Called when a class template TYPE is redeclared with the indicated
6333 template PARMS, e.g.:
6335 template <class T> struct S;
6336 template <class T> struct S {}; */
6338 bool
6339 redeclare_class_template (tree type, tree parms, tree cons)
6341 tree tmpl;
6342 tree tmpl_parms;
6343 int i;
6345 if (!TYPE_TEMPLATE_INFO (type))
6347 error ("%qT is not a template type", type);
6348 return false;
6351 tmpl = TYPE_TI_TEMPLATE (type);
6352 if (!PRIMARY_TEMPLATE_P (tmpl))
6353 /* The type is nested in some template class. Nothing to worry
6354 about here; there are no new template parameters for the nested
6355 type. */
6356 return true;
6358 if (!parms)
6360 error ("template specifiers not specified in declaration of %qD",
6361 tmpl);
6362 return false;
6365 parms = INNERMOST_TEMPLATE_PARMS (parms);
6366 tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
6368 if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
6370 auto_diagnostic_group d;
6371 error_n (input_location, TREE_VEC_LENGTH (parms),
6372 "redeclared with %d template parameter",
6373 "redeclared with %d template parameters",
6374 TREE_VEC_LENGTH (parms));
6375 inform_n (DECL_SOURCE_LOCATION (tmpl), TREE_VEC_LENGTH (tmpl_parms),
6376 "previous declaration %qD used %d template parameter",
6377 "previous declaration %qD used %d template parameters",
6378 tmpl, TREE_VEC_LENGTH (tmpl_parms));
6379 return false;
6382 for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
6384 tree tmpl_parm;
6385 tree parm;
6387 if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
6388 || TREE_VEC_ELT (parms, i) == error_mark_node)
6389 continue;
6391 tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
6392 if (error_operand_p (tmpl_parm))
6393 return false;
6395 parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
6397 /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
6398 TEMPLATE_DECL. */
6399 if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
6400 || (TREE_CODE (tmpl_parm) != TYPE_DECL
6401 && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
6402 || (TREE_CODE (tmpl_parm) != PARM_DECL
6403 && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
6404 != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
6405 || (TREE_CODE (tmpl_parm) == PARM_DECL
6406 && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
6407 != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
6409 auto_diagnostic_group d;
6410 error ("template parameter %q+#D", tmpl_parm);
6411 if (DECL_P (parm))
6412 inform (DECL_SOURCE_LOCATION (parm), "redeclared here as %q#D", parm);
6413 else
6414 inform (input_location, "redeclared here");
6415 return false;
6418 /* The parameters can be declared to introduce different
6419 constraints. */
6420 tree p1 = TREE_VEC_ELT (tmpl_parms, i);
6421 tree p2 = TREE_VEC_ELT (parms, i);
6422 if (!template_parameter_constraints_equivalent_p (p1, p2))
6424 auto_diagnostic_group d;
6425 error ("declaration of template parameter %q+#D with different "
6426 "constraints", parm);
6427 inform (DECL_SOURCE_LOCATION (tmpl_parm),
6428 "original declaration appeared here");
6429 return false;
6432 /* Give each template template parm in this redeclaration a
6433 DECL_CONTEXT of the template for which they are a parameter. */
6434 if (TREE_CODE (parm) == TEMPLATE_DECL)
6436 gcc_checking_assert (DECL_CONTEXT (parm) == NULL_TREE
6437 || DECL_CONTEXT (parm) == tmpl);
6438 DECL_CONTEXT (parm) = tmpl;
6442 if (!merge_default_template_args (parms, tmpl_parms, /*class_p=*/true))
6443 return false;
6445 tree ci = get_constraints (tmpl);
6446 tree req1 = ci ? CI_TEMPLATE_REQS (ci) : NULL_TREE;
6447 tree req2 = cons ? CI_TEMPLATE_REQS (cons) : NULL_TREE;
6449 /* Two classes with different constraints declare different entities. */
6450 if (!cp_tree_equal (req1, req2))
6452 auto_diagnostic_group d;
6453 error_at (input_location, "redeclaration of %q#D with different "
6454 "constraints", tmpl);
6455 inform (DECL_SOURCE_LOCATION (tmpl),
6456 "original declaration appeared here");
6457 return false;
6460 return true;
6463 /* The actual substitution part of instantiate_non_dependent_expr,
6464 to be used when the caller has already checked
6465 !instantiation_dependent_uneval_expression_p (expr)
6466 and cleared processing_template_decl. */
6468 tree
6469 instantiate_non_dependent_expr_internal (tree expr, tsubst_flags_t complain)
6471 return tsubst_expr (expr, /*args=*/NULL_TREE, complain, /*in_decl=*/NULL_TREE);
6474 /* Instantiate the non-dependent expression EXPR. */
6476 tree
6477 instantiate_non_dependent_expr (tree expr,
6478 tsubst_flags_t complain /* = tf_error */)
6480 if (expr == NULL_TREE)
6481 return NULL_TREE;
6483 if (processing_template_decl)
6485 /* The caller should have checked this already. */
6486 gcc_checking_assert (!instantiation_dependent_uneval_expression_p (expr));
6487 processing_template_decl_sentinel s;
6488 expr = instantiate_non_dependent_expr_internal (expr, complain);
6490 return expr;
6493 /* Like instantiate_non_dependent_expr, but return NULL_TREE if the
6494 expression is dependent or non-constant. */
6496 tree
6497 instantiate_non_dependent_or_null (tree expr)
6499 if (expr == NULL_TREE)
6500 return NULL_TREE;
6501 if (processing_template_decl)
6503 if (!is_nondependent_constant_expression (expr))
6504 expr = NULL_TREE;
6505 else
6507 processing_template_decl_sentinel s;
6508 expr = instantiate_non_dependent_expr_internal (expr, tf_error);
6511 return expr;
6514 /* True iff T is a specialization of a variable template. */
6516 bool
6517 variable_template_specialization_p (tree t)
6519 if (!VAR_P (t) || !DECL_LANG_SPECIFIC (t) || !DECL_TEMPLATE_INFO (t))
6520 return false;
6521 tree tmpl = DECL_TI_TEMPLATE (t);
6522 return variable_template_p (tmpl);
6525 /* Return TRUE iff T is a type alias, a TEMPLATE_DECL for an alias
6526 template declaration, or a TYPE_DECL for an alias declaration. */
6528 bool
6529 alias_type_or_template_p (tree t)
6531 if (t == NULL_TREE)
6532 return false;
6533 return ((TREE_CODE (t) == TYPE_DECL && TYPE_DECL_ALIAS_P (t))
6534 || (TYPE_P (t)
6535 && TYPE_NAME (t)
6536 && TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
6537 || DECL_ALIAS_TEMPLATE_P (t));
6540 /* If T is a specialization of an alias template, return it; otherwise return
6541 NULL_TREE. If TRANSPARENT_TYPEDEFS is true, look through other aliases. */
6543 tree
6544 alias_template_specialization_p (const_tree t,
6545 bool transparent_typedefs)
6547 if (!TYPE_P (t))
6548 return NULL_TREE;
6550 /* It's an alias template specialization if it's an alias and its
6551 TYPE_NAME is a specialization of a primary template. */
6552 if (typedef_variant_p (t))
6554 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
6555 if (PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo)))
6556 return CONST_CAST_TREE (t);
6557 if (transparent_typedefs && !dependent_opaque_alias_p (t))
6558 return alias_template_specialization_p (DECL_ORIGINAL_TYPE
6559 (TYPE_NAME (t)),
6560 transparent_typedefs);
6563 return NULL_TREE;
6566 /* A cache of the result of complex_alias_template_p. */
6568 static GTY((deletable)) hash_map<const_tree, tree> *complex_alias_tmpl_info;
6570 /* Data structure for complex_alias_template_*. */
6572 struct uses_all_template_parms_data
6574 int level;
6575 tree *seen;
6578 /* walk_tree callback for complex_alias_template_p. */
6580 static tree
6581 complex_alias_template_r (tree *tp, int *walk_subtrees, void *data_)
6583 tree t = *tp;
6584 auto &data = *(struct uses_all_template_parms_data*)data_;
6586 switch (TREE_CODE (t))
6588 case TEMPLATE_TYPE_PARM:
6589 case TEMPLATE_PARM_INDEX:
6590 case TEMPLATE_TEMPLATE_PARM:
6591 case BOUND_TEMPLATE_TEMPLATE_PARM:
6593 tree idx = get_template_parm_index (t);
6594 if (TEMPLATE_PARM_LEVEL (idx) == data.level)
6595 data.seen[TEMPLATE_PARM_IDX (idx)] = boolean_true_node;
6598 default:;
6601 if (!PACK_EXPANSION_P (t))
6602 return 0;
6604 /* An alias template with a pack expansion that expands a pack from the
6605 enclosing class needs to be considered complex, to avoid confusion with
6606 the same pack being used as an argument to the alias's own template
6607 parameter (91966). */
6608 for (tree pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
6609 pack = TREE_CHAIN (pack))
6611 tree parm_pack = TREE_VALUE (pack);
6612 if (!TEMPLATE_PARM_P (parm_pack))
6613 continue;
6614 int idx, level;
6615 template_parm_level_and_index (parm_pack, &level, &idx);
6616 if (level < data.level)
6617 return t;
6619 /* Consider the expanded packs to be used outside the expansion... */
6620 data.seen[idx] = boolean_true_node;
6623 /* ...but don't walk into the pattern. Consider PR104008:
6625 template <typename T, typename... Ts>
6626 using IsOneOf = disjunction<is_same<T, Ts>...>;
6628 where IsOneOf seemingly uses all of its template parameters in its
6629 expansion (and does not expand a pack from the enclosing class), so the
6630 alias was not marked as complex. However, if it is used like
6631 "IsOneOf<T>", the empty pack for Ts means that T no longer appears in the
6632 expansion. So only Ts is considered used by the pack expansion. */
6633 *walk_subtrees = false;
6635 return 0;
6638 /* An alias template is complex from a SFINAE perspective if a template-id
6639 using that alias can be ill-formed when the expansion is not, as with
6640 the void_t template.
6642 If this predicate returns true in the ordinary case, the out parameter
6643 SEEN_OUT is set to a TREE_VEC containing boolean_true_node at element I if
6644 the I'th template parameter of the alias template is used in the alias. */
6646 static bool
6647 complex_alias_template_p (const_tree tmpl, tree *seen_out)
6649 tmpl = most_general_template (tmpl);
6650 if (!PRIMARY_TEMPLATE_P (tmpl))
6651 return false;
6653 /* A renaming alias isn't complex. */
6654 if (get_underlying_template (CONST_CAST_TREE (tmpl)) != tmpl)
6655 return false;
6657 /* Any other constrained alias is complex. */
6658 if (get_constraints (tmpl))
6659 return true;
6661 /* An alias with dependent type attributes is complex. */
6662 if (dependent_opaque_alias_p (TREE_TYPE (tmpl)))
6663 return true;
6665 if (!complex_alias_tmpl_info)
6666 complex_alias_tmpl_info = hash_map<const_tree, tree>::create_ggc (13);
6668 if (tree *slot = complex_alias_tmpl_info->get (tmpl))
6670 tree result = *slot;
6671 if (result == boolean_false_node)
6672 return false;
6673 if (result == boolean_true_node)
6674 return true;
6675 gcc_assert (TREE_CODE (result) == TREE_VEC);
6676 if (seen_out)
6677 *seen_out = result;
6678 return true;
6681 struct uses_all_template_parms_data data;
6682 tree pat = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6683 tree parms = DECL_TEMPLATE_PARMS (tmpl);
6684 data.level = TMPL_PARMS_DEPTH (parms);
6685 int len = TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS (parms));
6686 tree seen = make_tree_vec (len);
6687 data.seen = TREE_VEC_BEGIN (seen);
6688 for (int i = 0; i < len; ++i)
6689 data.seen[i] = boolean_false_node;
6691 if (cp_walk_tree_without_duplicates (&pat, complex_alias_template_r, &data))
6693 complex_alias_tmpl_info->put (tmpl, boolean_true_node);
6694 return true;
6697 for (int i = 0; i < len; ++i)
6698 if (data.seen[i] != boolean_true_node)
6700 complex_alias_tmpl_info->put (tmpl, seen);
6701 if (seen_out)
6702 *seen_out = seen;
6703 return true;
6706 complex_alias_tmpl_info->put (tmpl, boolean_false_node);
6707 return false;
6710 /* If T is a specialization of a complex alias template with a dependent
6711 argument for an unused template parameter, return it; otherwise return
6712 NULL_TREE. If T is a typedef to such a specialization, return the
6713 specialization. This predicate is usually checked alongside
6714 dependent_opaque_alias_p. Whereas dependent_opaque_alias_p checks
6715 type equivalence of an alias vs its expansion, this predicate more
6716 broadly checks SFINAE equivalence. */
6718 tree
6719 dependent_alias_template_spec_p (const_tree t, bool transparent_typedefs)
6721 if (t == error_mark_node)
6722 return NULL_TREE;
6723 gcc_assert (TYPE_P (t));
6725 if (!processing_template_decl || !typedef_variant_p (t))
6726 return NULL_TREE;
6728 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
6730 tree seen = NULL_TREE;
6731 if (complex_alias_template_p (TI_TEMPLATE (tinfo), &seen))
6733 tree args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo));
6734 if (!seen)
6736 if (any_dependent_template_arguments_p (args))
6737 return CONST_CAST_TREE (t);
6739 else
6741 gcc_assert (TREE_VEC_LENGTH (args) == TREE_VEC_LENGTH (seen));
6742 for (int i = 0, len = TREE_VEC_LENGTH (args); i < len; ++i)
6743 if (TREE_VEC_ELT (seen, i) != boolean_true_node
6744 && dependent_template_arg_p (TREE_VEC_ELT (args, i)))
6745 return CONST_CAST_TREE (t);
6748 return NULL_TREE;
6752 if (transparent_typedefs && !dependent_opaque_alias_p (t))
6754 tree utype = DECL_ORIGINAL_TYPE (TYPE_NAME (t));
6755 return dependent_alias_template_spec_p (utype, transparent_typedefs);
6758 return NULL_TREE;
6761 /* Return true if substituting into T would yield a different type than
6762 substituting into its expansion. This predicate is usually checked
6763 alongside dependent_alias_template_spec_p. */
6765 bool
6766 dependent_opaque_alias_p (const_tree t)
6768 return (TYPE_P (t)
6769 && typedef_variant_p (t)
6770 && (any_dependent_type_attributes_p (DECL_ATTRIBUTES
6771 (TYPE_NAME (t)))
6772 /* Treat a dependent decltype(lambda) alias as opaque so that we
6773 don't prematurely strip it when used as a template argument.
6774 Otherwise substitution into each occurrence of the (stripped)
6775 alias would incorrectly yield a distinct lambda type. */
6776 || (TREE_CODE (t) == DECLTYPE_TYPE
6777 && TREE_CODE (DECLTYPE_TYPE_EXPR (t)) == LAMBDA_EXPR
6778 && !typedef_variant_p (DECL_ORIGINAL_TYPE (TYPE_NAME (t))))));
6781 /* Return the number of innermost template parameters in TMPL. */
6783 static int
6784 num_innermost_template_parms (const_tree tmpl)
6786 tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
6787 return TREE_VEC_LENGTH (parms);
6790 /* Return either TMPL or another template that it is equivalent to under DR
6791 1286: An alias that just changes the name of a template is equivalent to
6792 the other template. */
6794 static tree
6795 get_underlying_template (tree tmpl)
6797 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
6798 while (DECL_ALIAS_TEMPLATE_P (tmpl))
6800 /* Determine if the alias is equivalent to an underlying template. */
6801 tree orig_type = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6802 /* The underlying type may have been ill-formed. Don't proceed. */
6803 if (!orig_type)
6804 break;
6805 tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (orig_type);
6806 if (!tinfo)
6807 break;
6809 tree underlying = TI_TEMPLATE (tinfo);
6810 if (!PRIMARY_TEMPLATE_P (underlying)
6811 || (num_innermost_template_parms (tmpl)
6812 != num_innermost_template_parms (underlying)))
6813 break;
6815 /* Does the alias add cv-quals? */
6816 if (TYPE_QUALS (TREE_TYPE (underlying)) != TYPE_QUALS (TREE_TYPE (tmpl)))
6817 break;
6819 tree alias_args = INNERMOST_TEMPLATE_ARGS (generic_targs_for (tmpl));
6820 if (!comp_template_args (TI_ARGS (tinfo), alias_args))
6821 break;
6823 /* Are any default template arguments equivalent? */
6824 tree aparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
6825 tree uparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (underlying));
6826 const int nparms = TREE_VEC_LENGTH (aparms);
6827 for (int i = 0; i < nparms; ++i)
6829 tree adefarg = TREE_PURPOSE (TREE_VEC_ELT (aparms, i));
6830 tree udefarg = TREE_PURPOSE (TREE_VEC_ELT (uparms, i));
6831 if (!template_args_equal (adefarg, udefarg))
6832 goto top_break;
6835 /* If TMPL adds or changes any constraints, it isn't equivalent. I think
6836 it's appropriate to treat a less-constrained alias as equivalent. */
6837 if (!at_least_as_constrained (underlying, tmpl))
6838 break;
6840 /* If TMPL adds dependent type attributes, it isn't equivalent. */
6841 if (dependent_opaque_alias_p (TREE_TYPE (tmpl)))
6842 break;
6844 /* Alias is equivalent. Strip it and repeat. */
6845 tmpl = underlying;
6847 top_break:;
6849 return tmpl;
6852 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
6853 must be a reference-to-function or a pointer-to-function type, as specified
6854 in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
6855 and check that the resulting function has external linkage. */
6857 static tree
6858 convert_nontype_argument_function (tree type, tree expr,
6859 tsubst_flags_t complain)
6861 tree fns = expr;
6862 tree fn, fn_no_ptr;
6863 linkage_kind linkage;
6865 fn = instantiate_type (type, fns, tf_none);
6866 if (fn == error_mark_node)
6867 return error_mark_node;
6869 if (value_dependent_expression_p (fn))
6870 goto accept;
6872 fn_no_ptr = fn;
6873 if (REFERENCE_REF_P (fn_no_ptr))
6874 fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
6875 fn_no_ptr = strip_fnptr_conv (fn_no_ptr);
6876 if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
6877 fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
6878 if (BASELINK_P (fn_no_ptr))
6879 fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
6881 /* [temp.arg.nontype]/1
6883 A template-argument for a non-type, non-template template-parameter
6884 shall be one of:
6885 [...]
6886 -- the address of an object or function with external [C++11: or
6887 internal] linkage. */
6889 STRIP_ANY_LOCATION_WRAPPER (fn_no_ptr);
6890 if (TREE_CODE (fn_no_ptr) != FUNCTION_DECL)
6892 if (complain & tf_error)
6894 auto_diagnostic_group d;
6895 location_t loc = cp_expr_loc_or_input_loc (expr);
6896 error_at (loc, "%qE is not a valid template argument for type %qT",
6897 expr, type);
6898 if (TYPE_PTR_P (type))
6899 inform (loc, "it must be the address of a function "
6900 "with external linkage");
6901 else
6902 inform (loc, "it must be the name of a function with "
6903 "external linkage");
6905 return NULL_TREE;
6908 linkage = decl_linkage (fn_no_ptr);
6909 if ((cxx_dialect < cxx11 && linkage != lk_external)
6910 || (cxx_dialect < cxx17 && linkage == lk_none))
6912 if (complain & tf_error)
6914 location_t loc = cp_expr_loc_or_input_loc (expr);
6915 if (cxx_dialect >= cxx11)
6916 error_at (loc, "%qE is not a valid template argument for type "
6917 "%qT because %qD has no linkage",
6918 expr, type, fn_no_ptr);
6919 else
6920 error_at (loc, "%qE is not a valid template argument for type "
6921 "%qT because %qD does not have external linkage",
6922 expr, type, fn_no_ptr);
6924 return NULL_TREE;
6927 accept:
6928 if (TYPE_REF_P (type))
6930 if (REFERENCE_REF_P (fn))
6931 fn = TREE_OPERAND (fn, 0);
6932 else
6933 fn = build_address (fn);
6935 if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (fn)))
6936 fn = build_nop (type, fn);
6938 return fn;
6941 /* Subroutine of convert_nontype_argument.
6942 Check if EXPR of type TYPE is a valid pointer-to-member constant.
6943 Emit an error otherwise. */
6945 static bool
6946 check_valid_ptrmem_cst_expr (tree type, tree expr,
6947 tsubst_flags_t complain)
6949 tree orig_expr = expr;
6950 STRIP_NOPS (expr);
6951 if (null_ptr_cst_p (expr))
6952 return true;
6953 if (TREE_CODE (expr) == PTRMEM_CST
6954 && same_type_p (TYPE_PTRMEM_CLASS_TYPE (type),
6955 PTRMEM_CST_CLASS (expr)))
6956 return true;
6957 if (cxx_dialect >= cxx11 && null_member_pointer_value_p (expr))
6958 return true;
6959 if (processing_template_decl
6960 && TREE_CODE (expr) == ADDR_EXPR
6961 && TREE_CODE (TREE_OPERAND (expr, 0)) == OFFSET_REF)
6962 return true;
6963 if (complain & tf_error)
6965 auto_diagnostic_group d;
6966 location_t loc = cp_expr_loc_or_input_loc (orig_expr);
6967 error_at (loc, "%qE is not a valid template argument for type %qT",
6968 orig_expr, type);
6969 if (TREE_CODE (expr) != PTRMEM_CST)
6970 inform (loc, "it must be a pointer-to-member of the form %<&X::Y%>");
6971 else
6972 inform (loc, "because it is a member of %qT", PTRMEM_CST_CLASS (expr));
6974 return false;
6977 /* Returns TRUE iff the address of OP is value-dependent.
6979 14.6.2.4 [temp.dep.temp]:
6980 A non-integral non-type template-argument is dependent if its type is
6981 dependent or it has either of the following forms
6982 qualified-id
6983 & qualified-id
6984 and contains a nested-name-specifier which specifies a class-name that
6985 names a dependent type.
6987 We generalize this to just say that the address of a member of a
6988 dependent class is value-dependent; the above doesn't cover the
6989 address of a static data member named with an unqualified-id. */
6991 static bool
6992 has_value_dependent_address (tree op)
6994 STRIP_ANY_LOCATION_WRAPPER (op);
6996 /* We could use get_inner_reference here, but there's no need;
6997 this is only relevant for template non-type arguments, which
6998 can only be expressed as &id-expression. */
6999 if (DECL_P (op))
7001 tree ctx = CP_DECL_CONTEXT (op);
7003 if (TYPE_P (ctx) && dependent_type_p (ctx))
7004 return true;
7006 if (VAR_P (op)
7007 && TREE_STATIC (op)
7008 && TREE_CODE (ctx) == FUNCTION_DECL
7009 && type_dependent_expression_p (ctx))
7010 return true;
7013 return false;
7016 /* The next set of functions are used for providing helpful explanatory
7017 diagnostics for failed overload resolution. Their messages should be
7018 indented by two spaces for consistency with the messages in
7019 call.cc */
7021 static int
7022 unify_success (bool /*explain_p*/)
7024 return 0;
7027 /* Other failure functions should call this one, to provide a single function
7028 for setting a breakpoint on. */
7030 static int
7031 unify_invalid (bool /*explain_p*/)
7033 return 1;
7036 static int
7037 unify_parameter_deduction_failure (bool explain_p, tree parm)
7039 if (explain_p)
7040 inform (input_location,
7041 " couldn%'t deduce template parameter %qD", parm);
7042 return unify_invalid (explain_p);
7045 static int
7046 unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
7048 if (explain_p)
7049 inform (input_location,
7050 " types %qT and %qT have incompatible cv-qualifiers",
7051 parm, arg);
7052 return unify_invalid (explain_p);
7055 static int
7056 unify_type_mismatch (bool explain_p, tree parm, tree arg)
7058 if (explain_p)
7059 inform (input_location, " mismatched types %qT and %qT", parm, arg);
7060 return unify_invalid (explain_p);
7063 static int
7064 unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
7066 if (explain_p)
7067 inform (input_location,
7068 " template parameter %qD is not a parameter pack, but "
7069 "argument %qD is",
7070 parm, arg);
7071 return unify_invalid (explain_p);
7074 static int
7075 unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
7077 if (explain_p)
7078 inform (input_location,
7079 " template argument %qE does not match "
7080 "pointer-to-member constant %qE",
7081 arg, parm);
7082 return unify_invalid (explain_p);
7085 static int
7086 unify_expression_unequal (bool explain_p, tree parm, tree arg)
7088 if (explain_p)
7089 inform (input_location, " %qE is not equivalent to %qE", parm, arg);
7090 return unify_invalid (explain_p);
7093 static int
7094 unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
7096 if (explain_p)
7097 inform (input_location,
7098 " inconsistent parameter pack deduction with %qT and %qT",
7099 old_arg, new_arg);
7100 return unify_invalid (explain_p);
7103 static int
7104 unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
7106 if (explain_p)
7108 if (TYPE_P (parm))
7109 inform (input_location,
7110 " deduced conflicting types for parameter %qT (%qT and %qT)",
7111 parm, first, second);
7112 else
7113 inform (input_location,
7114 " deduced conflicting values for non-type parameter "
7115 "%qE (%qE and %qE)", parm, first, second);
7117 return unify_invalid (explain_p);
7120 static int
7121 unify_vla_arg (bool explain_p, tree arg)
7123 if (explain_p)
7124 inform (input_location,
7125 " variable-sized array type %qT is not "
7126 "a valid template argument",
7127 arg);
7128 return unify_invalid (explain_p);
7131 static int
7132 unify_method_type_error (bool explain_p, tree arg)
7134 if (explain_p)
7135 inform (input_location,
7136 " member function type %qT is not a valid template argument",
7137 arg);
7138 return unify_invalid (explain_p);
7141 static int
7142 unify_arity (bool explain_p, int have, int wanted, bool least_p = false)
7144 if (explain_p)
7146 if (least_p)
7147 inform_n (input_location, wanted,
7148 " candidate expects at least %d argument, %d provided",
7149 " candidate expects at least %d arguments, %d provided",
7150 wanted, have);
7151 else
7152 inform_n (input_location, wanted,
7153 " candidate expects %d argument, %d provided",
7154 " candidate expects %d arguments, %d provided",
7155 wanted, have);
7157 return unify_invalid (explain_p);
7160 static int
7161 unify_too_many_arguments (bool explain_p, int have, int wanted)
7163 return unify_arity (explain_p, have, wanted);
7166 static int
7167 unify_too_few_arguments (bool explain_p, int have, int wanted,
7168 bool least_p = false)
7170 return unify_arity (explain_p, have, wanted, least_p);
7173 static int
7174 unify_arg_conversion (bool explain_p, tree to_type,
7175 tree from_type, tree arg)
7177 if (explain_p)
7178 inform (cp_expr_loc_or_input_loc (arg),
7179 " cannot convert %qE (type %qT) to type %qT",
7180 arg, from_type, to_type);
7181 return unify_invalid (explain_p);
7184 static int
7185 unify_no_common_base (bool explain_p, enum template_base_result r,
7186 tree parm, tree arg)
7188 if (explain_p)
7189 switch (r)
7191 case tbr_ambiguous_baseclass:
7192 inform (input_location, " %qT is an ambiguous base class of %qT",
7193 parm, arg);
7194 break;
7195 default:
7196 inform (input_location, " %qT is not derived from %qT", arg, parm);
7197 break;
7199 return unify_invalid (explain_p);
7202 static int
7203 unify_inconsistent_template_template_parameters (bool explain_p)
7205 if (explain_p)
7206 inform (input_location,
7207 " template parameters of a template template argument are "
7208 "inconsistent with other deduced template arguments");
7209 return unify_invalid (explain_p);
7212 static int
7213 unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
7215 if (explain_p)
7216 inform (input_location,
7217 " cannot deduce a template for %qT from non-template type %qT",
7218 parm, arg);
7219 return unify_invalid (explain_p);
7222 static int
7223 unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
7225 if (explain_p)
7226 inform (input_location,
7227 " template argument %qE does not match %qE", arg, parm);
7228 return unify_invalid (explain_p);
7231 /* Subroutine of convert_nontype_argument, to check whether EXPR, as an
7232 argument for TYPE, points to an unsuitable object.
7234 Also adjust the type of the index in C++20 array subobject references. */
7236 static bool
7237 invalid_tparm_referent_p (tree type, tree expr, tsubst_flags_t complain)
7239 switch (TREE_CODE (expr))
7241 CASE_CONVERT:
7242 return invalid_tparm_referent_p (type, TREE_OPERAND (expr, 0),
7243 complain);
7245 case TARGET_EXPR:
7246 return invalid_tparm_referent_p (type, TARGET_EXPR_INITIAL (expr),
7247 complain);
7249 case CONSTRUCTOR:
7251 for (auto &e: CONSTRUCTOR_ELTS (expr))
7252 if (invalid_tparm_referent_p (TREE_TYPE (e.value), e.value, complain))
7253 return true;
7255 break;
7257 case ADDR_EXPR:
7259 tree decl = TREE_OPERAND (expr, 0);
7261 if (cxx_dialect >= cxx20)
7262 while (TREE_CODE (decl) == COMPONENT_REF
7263 || TREE_CODE (decl) == ARRAY_REF)
7265 tree &op = TREE_OPERAND (decl, 1);
7266 if (TREE_CODE (decl) == ARRAY_REF
7267 && TREE_CODE (op) == INTEGER_CST)
7268 /* Canonicalize array offsets to ptrdiff_t; how they were
7269 written doesn't matter for subobject identity. */
7270 op = fold_convert (ptrdiff_type_node, op);
7271 decl = TREE_OPERAND (decl, 0);
7274 if (!VAR_OR_FUNCTION_DECL_P (decl))
7276 if (complain & tf_error)
7277 error_at (cp_expr_loc_or_input_loc (expr),
7278 "%qE is not a valid template argument of type %qT "
7279 "because %qE is not a variable or function",
7280 expr, type, decl);
7281 return true;
7283 else if (cxx_dialect < cxx11 && !DECL_EXTERNAL_LINKAGE_P (decl))
7285 if (complain & tf_error)
7286 error_at (cp_expr_loc_or_input_loc (expr),
7287 "%qE is not a valid template argument of type %qT "
7288 "in C++98 because %qD does not have external linkage",
7289 expr, type, decl);
7290 return true;
7292 else if ((cxx_dialect >= cxx11 && cxx_dialect < cxx17)
7293 && decl_linkage (decl) == lk_none)
7295 if (complain & tf_error)
7296 error_at (cp_expr_loc_or_input_loc (expr),
7297 "%qE is not a valid template argument of type %qT "
7298 "because %qD has no linkage", expr, type, decl);
7299 return true;
7301 /* C++17: For a non-type template-parameter of reference or pointer
7302 type, the value of the constant expression shall not refer to (or
7303 for a pointer type, shall not be the address of):
7304 * a subobject (4.5),
7305 * a temporary object (15.2),
7306 * a string literal (5.13.5),
7307 * the result of a typeid expression (8.2.8), or
7308 * a predefined __func__ variable (11.4.1). */
7309 else if (VAR_P (decl) && DECL_ARTIFICIAL (decl)
7310 && !DECL_NTTP_OBJECT_P (decl))
7312 gcc_checking_assert (DECL_TINFO_P (decl) || DECL_FNAME_P (decl));
7313 if (complain & tf_error)
7314 error ("the address of %qD is not a valid template argument",
7315 decl);
7316 return true;
7318 else if (cxx_dialect < cxx20
7319 && !(same_type_ignoring_top_level_qualifiers_p
7320 (strip_array_types (TREE_TYPE (type)),
7321 strip_array_types (TREE_TYPE (decl)))))
7323 if (complain & tf_error)
7324 error ("the address of the %qT subobject of %qD is not a "
7325 "valid template argument", TREE_TYPE (type), decl);
7326 return true;
7328 else if (!TREE_STATIC (decl) && !DECL_EXTERNAL (decl))
7330 if (complain & tf_error)
7331 error ("the address of %qD is not a valid template argument "
7332 "because it does not have static storage duration",
7333 decl);
7334 return true;
7337 break;
7339 default:
7340 if (!INDIRECT_TYPE_P (type))
7341 /* We're only concerned about pointers and references here. */;
7342 else if (cxx_dialect >= cxx11 && integer_zerop (expr))
7343 /* Null pointer values are OK in C++11. */;
7344 else
7346 if (VAR_P (expr))
7348 if (complain & tf_error)
7349 error ("%qD is not a valid template argument "
7350 "because %qD is a variable, not the address of "
7351 "a variable", expr, expr);
7352 return true;
7354 else
7356 if (complain & tf_error)
7357 error ("%qE is not a valid template argument for %qT "
7358 "because it is not the address of a variable",
7359 expr, type);
7360 return true;
7364 return false;
7368 /* Return a VAR_DECL for the C++20 template parameter object corresponding to
7369 template argument EXPR. */
7371 static tree
7372 create_template_parm_object (tree expr, tsubst_flags_t complain)
7374 tree orig = expr;
7375 if (TREE_CODE (expr) == TARGET_EXPR)
7376 expr = TARGET_EXPR_INITIAL (expr);
7378 if (!TREE_CONSTANT (expr))
7380 if ((complain & tf_error)
7381 && require_rvalue_constant_expression (orig))
7382 cxx_constant_value (orig);
7383 return error_mark_node;
7385 if (invalid_tparm_referent_p (TREE_TYPE (expr), expr, complain))
7386 return error_mark_node;
7388 /* This is no longer a compound literal. */
7389 gcc_assert (!TREE_HAS_CONSTRUCTOR (expr));
7391 return get_template_parm_object (expr, mangle_template_parm_object (expr));
7394 /* The template arguments corresponding to template parameter objects of types
7395 that contain pointers to members. */
7397 static GTY(()) hash_map<tree, tree> *tparm_obj_values;
7399 /* Find or build an nttp object for (already-validated) EXPR with name
7400 NAME. When CHECK_INIT is false we don't need to process the initialiser,
7401 it's already been done. */
7403 tree
7404 get_template_parm_object (tree expr, tree name, bool check_init/*=true*/)
7406 tree decl = get_global_binding (name);
7407 if (decl)
7408 return decl;
7410 tree type = cp_build_qualified_type (TREE_TYPE (expr), TYPE_QUAL_CONST);
7411 decl = create_temporary_var (type);
7412 DECL_NTTP_OBJECT_P (decl) = true;
7413 DECL_CONTEXT (decl) = NULL_TREE;
7414 TREE_STATIC (decl) = true;
7415 DECL_DECLARED_CONSTEXPR_P (decl) = true;
7416 TREE_READONLY (decl) = true;
7417 DECL_NAME (decl) = name;
7418 SET_DECL_ASSEMBLER_NAME (decl, name);
7419 comdat_linkage (decl);
7421 if (!zero_init_p (type))
7423 /* If EXPR contains any PTRMEM_CST, they will get clobbered by
7424 lower_var_init before we're done mangling. So store the original
7425 value elsewhere. We only need to unshare EXPR if it's not yet
7426 been processed. */
7427 tree copy = check_init ? unshare_constructor (expr) : expr;
7428 hash_map_safe_put<hm_ggc> (tparm_obj_values, decl, copy);
7431 if (!check_init)
7433 /* The EXPR is the already processed initializer, set it on the NTTP
7434 object now so that cp_finish_decl doesn't do it again later. */
7435 DECL_INITIAL (decl) = expr;
7436 DECL_INITIALIZED_P (decl) = 1;
7439 pushdecl_top_level_and_finish (decl, expr);
7441 return decl;
7444 /* Return the actual template argument corresponding to template parameter
7445 object VAR. */
7447 tree
7448 tparm_object_argument (tree var)
7450 if (zero_init_p (TREE_TYPE (var)))
7451 return DECL_INITIAL (var);
7452 return *(tparm_obj_values->get (var));
7455 /* Attempt to convert the non-type template parameter EXPR to the
7456 indicated TYPE. If the conversion is successful, return the
7457 converted value. If the conversion is unsuccessful, return
7458 NULL_TREE if we issued an error message, or error_mark_node if we
7459 did not. We issue error messages for out-and-out bad template
7460 parameters, but not simply because the conversion failed, since we
7461 might be just trying to do argument deduction. Both TYPE and EXPR
7462 must be non-dependent.
7464 The conversion follows the special rules described in
7465 [temp.arg.nontype], and it is much more strict than an implicit
7466 conversion.
7468 This function is called twice for each template argument (see
7469 lookup_template_class for a more accurate description of this
7470 problem). This means that we need to handle expressions which
7471 are not valid in a C++ source, but can be created from the
7472 first call (for instance, casts to perform conversions). These
7473 hacks can go away after we fix the double coercion problem. */
7475 static tree
7476 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
7478 tree expr_type;
7479 location_t loc = cp_expr_loc_or_input_loc (expr);
7481 /* Detect immediately string literals as invalid non-type argument.
7482 This special-case is not needed for correctness (we would easily
7483 catch this later), but only to provide better diagnostic for this
7484 common user mistake. As suggested by DR 100, we do not mention
7485 linkage issues in the diagnostic as this is not the point. */
7486 if (TREE_CODE (expr) == STRING_CST && !CLASS_TYPE_P (type))
7488 if (complain & tf_error)
7489 error ("%qE is not a valid template argument for type %qT "
7490 "because string literals can never be used in this context",
7491 expr, type);
7492 return NULL_TREE;
7495 /* Add the ADDR_EXPR now for the benefit of
7496 value_dependent_expression_p. */
7497 if (TYPE_PTROBV_P (type)
7498 && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
7500 expr = decay_conversion (expr, complain);
7501 if (expr == error_mark_node)
7502 return error_mark_node;
7505 /* If we are in a template, EXPR may be non-dependent, but still
7506 have a syntactic, rather than semantic, form. For example, EXPR
7507 might be a SCOPE_REF, rather than the VAR_DECL to which the
7508 SCOPE_REF refers. Preserving the qualifying scope is necessary
7509 so that access checking can be performed when the template is
7510 instantiated -- but here we need the resolved form so that we can
7511 convert the argument. */
7512 bool non_dep = false;
7513 if (TYPE_REF_OBJ_P (type)
7514 && has_value_dependent_address (expr))
7515 /* If we want the address and it's value-dependent, don't fold. */;
7516 else if (processing_template_decl
7517 && !instantiation_dependent_expression_p (expr))
7518 non_dep = true;
7519 if (error_operand_p (expr))
7520 return error_mark_node;
7521 expr_type = TREE_TYPE (expr);
7523 /* If the argument is non-dependent, perform any conversions in
7524 non-dependent context as well. */
7525 processing_template_decl_sentinel s (non_dep);
7526 if (non_dep)
7527 expr = instantiate_non_dependent_expr_internal (expr, complain);
7529 bool val_dep_p = value_dependent_expression_p (expr);
7530 if (val_dep_p)
7531 expr = canonicalize_expr_argument (expr, complain);
7532 else
7533 STRIP_ANY_LOCATION_WRAPPER (expr);
7535 /* 14.3.2/5: The null pointer{,-to-member} conversion is applied
7536 to a non-type argument of "nullptr". */
7537 if (NULLPTR_TYPE_P (expr_type) && TYPE_PTR_OR_PTRMEM_P (type))
7538 expr = fold_simple (convert (type, expr));
7540 /* In C++11, integral or enumeration non-type template arguments can be
7541 arbitrary constant expressions. Pointer and pointer to
7542 member arguments can be general constant expressions that evaluate
7543 to a null value, but otherwise still need to be of a specific form. */
7544 if (cxx_dialect >= cxx11)
7546 if (TREE_CODE (expr) == PTRMEM_CST && TYPE_PTRMEM_P (type))
7547 /* A PTRMEM_CST is already constant, and a valid template
7548 argument for a parameter of pointer to member type, we just want
7549 to leave it in that form rather than lower it to a
7550 CONSTRUCTOR. */;
7551 else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
7552 || cxx_dialect >= cxx17)
7554 /* C++17: A template-argument for a non-type template-parameter shall
7555 be a converted constant expression (8.20) of the type of the
7556 template-parameter. */
7557 expr = build_converted_constant_expr (type, expr, complain);
7558 if (expr == error_mark_node)
7559 /* Make sure we return NULL_TREE only if we have really issued
7560 an error, as described above. */
7561 return (complain & tf_error) ? NULL_TREE : error_mark_node;
7562 else if (TREE_CODE (expr) == IMPLICIT_CONV_EXPR)
7564 IMPLICIT_CONV_EXPR_NONTYPE_ARG (expr) = true;
7565 return expr;
7567 expr = maybe_constant_value (expr, NULL_TREE, mce_true);
7568 expr = convert_from_reference (expr);
7569 /* EXPR may have become value-dependent. */
7570 val_dep_p = value_dependent_expression_p (expr);
7572 else if (TYPE_PTR_OR_PTRMEM_P (type))
7574 tree folded = maybe_constant_value (expr, NULL_TREE, mce_true);
7575 if (TYPE_PTR_P (type) ? integer_zerop (folded)
7576 : null_member_pointer_value_p (folded))
7577 expr = folded;
7581 if (TYPE_REF_P (type))
7582 expr = mark_lvalue_use (expr);
7583 else
7584 expr = mark_rvalue_use (expr);
7586 /* HACK: Due to double coercion, we can get a
7587 NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
7588 which is the tree that we built on the first call (see
7589 below when coercing to reference to object or to reference to
7590 function). We just strip everything and get to the arg.
7591 See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
7592 for examples. */
7593 if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
7595 /* Check this before we strip *& to avoid redundancy. */
7596 if (!mark_single_function (expr, complain))
7597 return error_mark_node;
7599 tree probe_type, probe = expr;
7600 if (REFERENCE_REF_P (probe))
7601 probe = TREE_OPERAND (probe, 0);
7602 probe_type = TREE_TYPE (probe);
7603 if (TREE_CODE (probe) == NOP_EXPR)
7605 /* ??? Maybe we could use convert_from_reference here, but we
7606 would need to relax its constraints because the NOP_EXPR
7607 could actually change the type to something more cv-qualified,
7608 and this is not folded by convert_from_reference. */
7609 tree addr = TREE_OPERAND (probe, 0);
7610 if (TYPE_REF_P (probe_type)
7611 && TREE_CODE (addr) == ADDR_EXPR
7612 && TYPE_PTR_P (TREE_TYPE (addr))
7613 && (same_type_ignoring_top_level_qualifiers_p
7614 (TREE_TYPE (probe_type),
7615 TREE_TYPE (TREE_TYPE (addr)))))
7617 expr = TREE_OPERAND (addr, 0);
7618 expr_type = TREE_TYPE (probe_type);
7623 /* [temp.arg.nontype]/5, bullet 1
7625 For a non-type template-parameter of integral or enumeration type,
7626 integral promotions (_conv.prom_) and integral conversions
7627 (_conv.integral_) are applied. */
7628 if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
7629 || SCALAR_FLOAT_TYPE_P (type))
7631 if (cxx_dialect < cxx11)
7633 tree t = build_converted_constant_expr (type, expr, complain);
7634 t = maybe_constant_value (t);
7635 if (t != error_mark_node)
7636 expr = t;
7639 if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
7640 return error_mark_node;
7642 /* Notice that there are constant expressions like '4 % 0' which
7643 do not fold into integer constants. */
7644 if (!CONSTANT_CLASS_P (expr) && !val_dep_p)
7646 if (complain & tf_error)
7648 int errs = errorcount, warns = warningcount + werrorcount;
7649 if (!require_potential_constant_expression (expr))
7650 expr = error_mark_node;
7651 else
7652 expr = cxx_constant_value (expr);
7653 if (errorcount > errs || warningcount + werrorcount > warns)
7654 inform (loc, "in template argument for type %qT", type);
7655 if (expr == error_mark_node)
7656 return NULL_TREE;
7657 /* else cxx_constant_value complained but gave us
7658 a real constant, so go ahead. */
7659 if (!CONSTANT_CLASS_P (expr))
7661 /* Some assemble time constant expressions like
7662 (intptr_t)&&lab1 - (intptr_t)&&lab2 or
7663 4 + (intptr_t)&&var satisfy reduced_constant_expression_p
7664 as we can emit them into .rodata initializers of
7665 variables, yet they can't fold into an INTEGER_CST at
7666 compile time. Refuse them here. */
7667 gcc_checking_assert (reduced_constant_expression_p (expr));
7668 error_at (loc, "template argument %qE for type %qT not "
7669 "a compile-time constant", expr, type);
7670 return NULL_TREE;
7673 else
7674 return NULL_TREE;
7677 /* Avoid typedef problems. */
7678 if (TREE_TYPE (expr) != type)
7679 expr = fold_convert (type, expr);
7681 /* [temp.arg.nontype]/5, bullet 2
7683 For a non-type template-parameter of type pointer to object,
7684 qualification conversions (_conv.qual_) and the array-to-pointer
7685 conversion (_conv.array_) are applied. */
7686 else if (TYPE_PTROBV_P (type))
7688 tree decayed = expr;
7690 /* Look through any NOP_EXPRs around an ADDR_EXPR, whether they come from
7691 decay_conversion or an explicit cast. If it's a problematic cast,
7692 we'll complain about it below. */
7693 if (TREE_CODE (expr) == NOP_EXPR)
7695 tree probe = expr;
7696 STRIP_NOPS (probe);
7697 if (TREE_CODE (probe) == ADDR_EXPR
7698 && TYPE_PTR_P (TREE_TYPE (probe)))
7700 expr = probe;
7701 expr_type = TREE_TYPE (expr);
7705 /* [temp.arg.nontype]/1 (TC1 version, DR 49):
7707 A template-argument for a non-type, non-template template-parameter
7708 shall be one of: [...]
7710 -- the name of a non-type template-parameter;
7711 -- the address of an object or function with external linkage, [...]
7712 expressed as "& id-expression" where the & is optional if the name
7713 refers to a function or array, or if the corresponding
7714 template-parameter is a reference.
7716 Here, we do not care about functions, as they are invalid anyway
7717 for a parameter of type pointer-to-object. */
7719 if (val_dep_p)
7720 /* Non-type template parameters are OK. */
7722 else if (cxx_dialect >= cxx11 && integer_zerop (expr))
7723 /* Null pointer values are OK in C++11. */;
7724 else if (TREE_CODE (expr) != ADDR_EXPR
7725 && !INDIRECT_TYPE_P (expr_type))
7726 /* Other values, like integer constants, might be valid
7727 non-type arguments of some other type. */
7728 return error_mark_node;
7729 else if (invalid_tparm_referent_p (type, expr, complain))
7730 return NULL_TREE;
7732 expr = decayed;
7734 expr = perform_qualification_conversions (type, expr);
7735 if (expr == error_mark_node)
7736 return error_mark_node;
7738 /* [temp.arg.nontype]/5, bullet 3
7740 For a non-type template-parameter of type reference to object, no
7741 conversions apply. The type referred to by the reference may be more
7742 cv-qualified than the (otherwise identical) type of the
7743 template-argument. The template-parameter is bound directly to the
7744 template-argument, which must be an lvalue. */
7745 else if (TYPE_REF_OBJ_P (type))
7747 if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
7748 expr_type))
7749 return error_mark_node;
7751 if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
7753 if (complain & tf_error)
7754 error ("%qE is not a valid template argument for type %qT "
7755 "because of conflicts in cv-qualification", expr, type);
7756 return NULL_TREE;
7759 if (!lvalue_p (expr))
7761 if (complain & tf_error)
7762 error ("%qE is not a valid template argument for type %qT "
7763 "because it is not an lvalue", expr, type);
7764 return NULL_TREE;
7767 /* [temp.arg.nontype]/1
7769 A template-argument for a non-type, non-template template-parameter
7770 shall be one of: [...]
7772 -- the address of an object or function with external linkage. */
7773 if (INDIRECT_REF_P (expr)
7774 && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
7776 expr = TREE_OPERAND (expr, 0);
7777 if (DECL_P (expr))
7779 if (complain & tf_error)
7780 error ("%q#D is not a valid template argument for type %qT "
7781 "because a reference variable does not have a constant "
7782 "address", expr, type);
7783 return NULL_TREE;
7787 if (TYPE_REF_OBJ_P (TREE_TYPE (expr)) && val_dep_p)
7788 /* OK, dependent reference. We don't want to ask whether a DECL is
7789 itself value-dependent, since what we want here is its address. */;
7790 else
7792 expr = build_address (expr);
7794 if (invalid_tparm_referent_p (type, expr, complain))
7795 return NULL_TREE;
7798 if (!same_type_p (type, TREE_TYPE (expr)))
7799 expr = build_nop (type, expr);
7801 /* [temp.arg.nontype]/5, bullet 4
7803 For a non-type template-parameter of type pointer to function, only
7804 the function-to-pointer conversion (_conv.func_) is applied. If the
7805 template-argument represents a set of overloaded functions (or a
7806 pointer to such), the matching function is selected from the set
7807 (_over.over_). */
7808 else if (TYPE_PTRFN_P (type))
7810 /* If the argument is a template-id, we might not have enough
7811 context information to decay the pointer. */
7812 if (!type_unknown_p (expr_type))
7814 expr = decay_conversion (expr, complain);
7815 if (expr == error_mark_node)
7816 return error_mark_node;
7819 if (cxx_dialect >= cxx11 && integer_zerop (expr))
7820 /* Null pointer values are OK in C++11. */
7821 return perform_qualification_conversions (type, expr);
7823 expr = convert_nontype_argument_function (type, expr, complain);
7824 if (!expr || expr == error_mark_node)
7825 return expr;
7827 /* [temp.arg.nontype]/5, bullet 5
7829 For a non-type template-parameter of type reference to function, no
7830 conversions apply. If the template-argument represents a set of
7831 overloaded functions, the matching function is selected from the set
7832 (_over.over_). */
7833 else if (TYPE_REFFN_P (type))
7835 if (TREE_CODE (expr) == ADDR_EXPR)
7837 if (complain & tf_error)
7839 auto_diagnostic_group d;
7840 error ("%qE is not a valid template argument for type %qT "
7841 "because it is a pointer", expr, type);
7842 inform (input_location, "try using %qE instead",
7843 TREE_OPERAND (expr, 0));
7845 return NULL_TREE;
7848 expr = convert_nontype_argument_function (type, expr, complain);
7849 if (!expr || expr == error_mark_node)
7850 return expr;
7852 /* [temp.arg.nontype]/5, bullet 6
7854 For a non-type template-parameter of type pointer to member function,
7855 no conversions apply. If the template-argument represents a set of
7856 overloaded member functions, the matching member function is selected
7857 from the set (_over.over_). */
7858 else if (TYPE_PTRMEMFUNC_P (type))
7860 expr = instantiate_type (type, expr, tf_none);
7861 if (expr == error_mark_node)
7862 return error_mark_node;
7864 /* [temp.arg.nontype] bullet 1 says the pointer to member
7865 expression must be a pointer-to-member constant. */
7866 if (!val_dep_p
7867 && !check_valid_ptrmem_cst_expr (type, expr, complain))
7868 return NULL_TREE;
7870 /* Repeated conversion can't deal with a conversion that turns PTRMEM_CST
7871 into a CONSTRUCTOR, so build up a new PTRMEM_CST instead. */
7872 if (fnptr_conv_p (type, TREE_TYPE (expr)))
7873 expr = make_ptrmem_cst (type, PTRMEM_CST_MEMBER (expr));
7875 /* [temp.arg.nontype]/5, bullet 7
7877 For a non-type template-parameter of type pointer to data member,
7878 qualification conversions (_conv.qual_) are applied. */
7879 else if (TYPE_PTRDATAMEM_P (type))
7881 /* [temp.arg.nontype] bullet 1 says the pointer to member
7882 expression must be a pointer-to-member constant. */
7883 if (!val_dep_p
7884 && !check_valid_ptrmem_cst_expr (type, expr, complain))
7885 return NULL_TREE;
7887 expr = perform_qualification_conversions (type, expr);
7888 if (expr == error_mark_node)
7889 return expr;
7891 else if (NULLPTR_TYPE_P (type))
7893 if (!NULLPTR_TYPE_P (TREE_TYPE (expr)))
7895 if (complain & tf_error)
7896 error ("%qE is not a valid template argument for type %qT "
7897 "because it is of type %qT", expr, type, TREE_TYPE (expr));
7898 return NULL_TREE;
7900 return expr;
7902 else if (CLASS_TYPE_P (type))
7904 /* Replace the argument with a reference to the corresponding template
7905 parameter object. */
7906 if (!val_dep_p)
7907 expr = create_template_parm_object (expr, complain);
7908 if (expr == error_mark_node)
7909 return NULL_TREE;
7911 /* A template non-type parameter must be one of the above. */
7912 else
7913 gcc_unreachable ();
7915 /* Sanity check: did we actually convert the argument to the
7916 right type? */
7917 gcc_assert (same_type_ignoring_top_level_qualifiers_p
7918 (type, TREE_TYPE (expr)));
7919 return convert_from_reference (expr);
7922 /* Subroutine of coerce_template_template_parms, which returns true if
7923 PARM and ARG match using the rule for the template parameters of
7924 template template parameters. Both PARM and ARG are template parameters;
7925 the rest of the arguments are the same as for
7926 coerce_template_template_parms. */
7928 static bool
7929 coerce_template_template_parm (tree parm, tree arg, tsubst_flags_t complain,
7930 tree in_decl, tree outer_args)
7932 if (arg == NULL_TREE || error_operand_p (arg)
7933 || parm == NULL_TREE || error_operand_p (parm))
7934 return false;
7936 if (TREE_CODE (arg) != TREE_CODE (parm))
7937 return false;
7939 switch (TREE_CODE (parm))
7941 case TEMPLATE_DECL:
7942 /* We encounter instantiations of templates like
7943 template <template <template <class> class> class TT>
7944 class C; */
7946 if (!coerce_template_template_parms
7947 (parm, arg, complain, in_decl, outer_args))
7948 return false;
7950 /* Fall through. */
7952 case TYPE_DECL:
7953 if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
7954 && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
7955 /* Argument is a parameter pack but parameter is not. */
7956 return false;
7957 break;
7959 case PARM_DECL:
7960 /* The tsubst call is used to handle cases such as
7962 template <int> class C {};
7963 template <class T, template <T> class TT> class D {};
7964 D<int, C> d;
7966 i.e. the parameter list of TT depends on earlier parameters. */
7967 if (!uses_template_parms (TREE_TYPE (arg)))
7969 ++processing_template_decl;
7970 tree t = tsubst (TREE_TYPE (parm), outer_args, complain, in_decl);
7971 --processing_template_decl;
7972 if (!uses_template_parms (t)
7973 && !same_type_p (t, TREE_TYPE (arg)))
7974 return false;
7977 if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
7978 && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
7979 /* Argument is a parameter pack but parameter is not. */
7980 return false;
7982 break;
7984 default:
7985 gcc_unreachable ();
7988 return true;
7991 /* Coerce template argument list ARGLIST for use with template
7992 template-parameter TEMPL. */
7994 static tree
7995 coerce_template_args_for_ttp (tree templ, tree arglist,
7996 tsubst_flags_t complain)
7998 /* Consider an example where a template template parameter declared as
8000 template <class T, class U = std::allocator<T> > class TT
8002 The template parameter level of T and U are one level larger than
8003 of TT. To proper process the default argument of U, say when an
8004 instantiation `TT<int>' is seen, we need to build the full
8005 arguments containing {int} as the innermost level. Outer levels,
8006 available when not appearing as default template argument, can be
8007 obtained from the arguments of the enclosing template.
8009 Suppose that TT is later substituted with std::vector. The above
8010 instantiation is `TT<int, std::allocator<T> >' with TT at
8011 level 1, and T at level 2, while the template arguments at level 1
8012 becomes {std::vector} and the inner level 2 is {int}. */
8014 tree outer = DECL_CONTEXT (templ);
8015 if (outer)
8016 outer = generic_targs_for (outer);
8017 else if (current_template_parms)
8019 /* This is an argument of the current template, so we haven't set
8020 DECL_CONTEXT yet. We can also get here when level-lowering a
8021 bound ttp. */
8022 tree relevant_template_parms;
8024 /* Parameter levels that are greater than the level of the given
8025 template template parm are irrelevant. */
8026 relevant_template_parms = current_template_parms;
8027 while (TMPL_PARMS_DEPTH (relevant_template_parms)
8028 != TEMPLATE_TYPE_LEVEL (TREE_TYPE (templ)))
8029 relevant_template_parms = TREE_CHAIN (relevant_template_parms);
8031 outer = template_parms_to_args (relevant_template_parms);
8034 if (outer)
8035 arglist = add_to_template_args (outer, arglist);
8037 tree parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
8038 return coerce_template_parms (parmlist, arglist, templ, complain);
8041 /* A cache of template template parameters with match-all default
8042 arguments. */
8043 static GTY((deletable)) hash_map<tree,tree> *defaulted_ttp_cache;
8045 /* T is a bound template template-parameter. Copy its arguments into default
8046 arguments of the template template-parameter's template parameters. */
8048 static tree
8049 add_defaults_to_ttp (tree otmpl)
8051 if (tree *c = hash_map_safe_get (defaulted_ttp_cache, otmpl))
8052 return *c;
8054 tree ntmpl = copy_node (otmpl);
8056 tree ntype = copy_node (TREE_TYPE (otmpl));
8057 TYPE_STUB_DECL (ntype) = TYPE_NAME (ntype) = ntmpl;
8058 TYPE_MAIN_VARIANT (ntype) = ntype;
8059 TYPE_POINTER_TO (ntype) = TYPE_REFERENCE_TO (ntype) = NULL_TREE;
8060 TYPE_NAME (ntype) = ntmpl;
8061 SET_TYPE_STRUCTURAL_EQUALITY (ntype);
8063 tree idx = TEMPLATE_TYPE_PARM_INDEX (ntype)
8064 = copy_node (TEMPLATE_TYPE_PARM_INDEX (ntype));
8065 TEMPLATE_PARM_DECL (idx) = ntmpl;
8066 TREE_TYPE (ntmpl) = TREE_TYPE (idx) = ntype;
8068 tree oparms = DECL_TEMPLATE_PARMS (otmpl);
8069 tree parms = DECL_TEMPLATE_PARMS (ntmpl) = copy_node (oparms);
8070 TREE_CHAIN (parms) = TREE_CHAIN (oparms);
8071 tree vec = TREE_VALUE (parms) = copy_node (TREE_VALUE (parms));
8072 for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
8074 tree o = TREE_VEC_ELT (vec, i);
8075 if (!template_parameter_pack_p (TREE_VALUE (o)))
8077 tree n = TREE_VEC_ELT (vec, i) = copy_node (o);
8078 TREE_PURPOSE (n) = any_targ_node;
8082 tree oresult = DECL_TEMPLATE_RESULT (otmpl);
8083 tree gen_otmpl = DECL_TI_TEMPLATE (oresult);
8084 tree gen_ntmpl;
8085 if (gen_otmpl == otmpl)
8086 gen_ntmpl = ntmpl;
8087 else
8088 gen_ntmpl = add_defaults_to_ttp (gen_otmpl);
8090 tree nresult = copy_decl (oresult);
8091 DECL_TEMPLATE_INFO (nresult)
8092 = build_template_info (gen_ntmpl, TI_ARGS (DECL_TEMPLATE_INFO (oresult)));
8093 DECL_TEMPLATE_RESULT (ntmpl) = nresult;
8095 hash_map_safe_put<hm_ggc> (defaulted_ttp_cache, otmpl, ntmpl);
8096 return ntmpl;
8099 /* ARG is a bound potential template template-argument, and PARGS is a list
8100 of arguments for the corresponding template template-parameter. Adjust
8101 PARGS as appropriate for application to ARG's template, and if ARG is a
8102 BOUND_TEMPLATE_TEMPLATE_PARM, possibly adjust it to add default template
8103 arguments to the template template parameter. */
8105 static tree
8106 coerce_ttp_args_for_tta (tree& arg, tree pargs, tsubst_flags_t complain)
8108 ++processing_template_decl;
8109 tree arg_tmpl = TYPE_TI_TEMPLATE (arg);
8110 if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
8112 /* When comparing two template template-parameters in partial ordering,
8113 rewrite the one currently being used as an argument to have default
8114 arguments for all parameters. */
8115 arg_tmpl = add_defaults_to_ttp (arg_tmpl);
8116 pargs = coerce_template_args_for_ttp (arg_tmpl, pargs, complain);
8117 if (pargs != error_mark_node)
8118 arg = bind_template_template_parm (TREE_TYPE (arg_tmpl),
8119 TYPE_TI_ARGS (arg));
8121 else
8123 tree aparms
8124 = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (arg_tmpl));
8125 pargs = coerce_template_parms (aparms, pargs, arg_tmpl, complain);
8127 --processing_template_decl;
8128 return pargs;
8131 /* Subroutine of unify for the case when PARM is a
8132 BOUND_TEMPLATE_TEMPLATE_PARM. */
8134 static int
8135 unify_bound_ttp_args (tree tparms, tree targs, tree parm, tree& arg,
8136 bool explain_p)
8138 tree parmvec = TYPE_TI_ARGS (parm);
8139 tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
8141 /* The template template parm might be variadic and the argument
8142 not, so flatten both argument lists. */
8143 parmvec = expand_template_argument_pack (parmvec);
8144 argvec = expand_template_argument_pack (argvec);
8146 if (flag_new_ttp)
8148 /* In keeping with P0522R0, adjust P's template arguments
8149 to apply to A's template; then flatten it again. */
8150 tree nparmvec = coerce_ttp_args_for_tta (arg, parmvec, tf_none);
8151 nparmvec = expand_template_argument_pack (nparmvec);
8153 if (unify (tparms, targs, nparmvec, argvec,
8154 UNIFY_ALLOW_NONE, explain_p))
8155 return 1;
8157 /* If the P0522 adjustment eliminated a pack expansion, deduce
8158 empty packs. */
8159 if (flag_new_ttp
8160 && TREE_VEC_LENGTH (nparmvec) < TREE_VEC_LENGTH (parmvec)
8161 && unify_pack_expansion (tparms, targs, parmvec, argvec,
8162 DEDUCE_EXACT, /*sub*/true, explain_p))
8163 return 1;
8165 else
8167 /* Deduce arguments T, i from TT<T> or TT<i>.
8168 We check each element of PARMVEC and ARGVEC individually
8169 rather than the whole TREE_VEC since they can have
8170 different number of elements, which is allowed under N2555. */
8172 int len = TREE_VEC_LENGTH (parmvec);
8174 /* Check if the parameters end in a pack, making them
8175 variadic. */
8176 int parm_variadic_p = 0;
8177 if (len > 0
8178 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
8179 parm_variadic_p = 1;
8181 for (int i = 0; i < len - parm_variadic_p; ++i)
8182 /* If the template argument list of P contains a pack
8183 expansion that is not the last template argument, the
8184 entire template argument list is a non-deduced
8185 context. */
8186 if (PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, i)))
8187 return unify_success (explain_p);
8189 if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
8190 return unify_too_few_arguments (explain_p,
8191 TREE_VEC_LENGTH (argvec), len);
8193 for (int i = 0; i < len - parm_variadic_p; ++i)
8194 if (unify (tparms, targs,
8195 TREE_VEC_ELT (parmvec, i),
8196 TREE_VEC_ELT (argvec, i),
8197 UNIFY_ALLOW_NONE, explain_p))
8198 return 1;
8200 if (parm_variadic_p
8201 && unify_pack_expansion (tparms, targs,
8202 parmvec, argvec,
8203 DEDUCE_EXACT,
8204 /*subr=*/true, explain_p))
8205 return 1;
8208 return 0;
8211 /* Return 1 if PARM_TMPL and ARG_TMPL match using rule for
8212 template template parameters.
8214 Consider the example:
8215 template <class T> class A;
8216 template<template <class U> class TT> class B;
8218 For B<A>, PARM_TMPL is TT, while ARG_TMPL is A,
8219 and OUTER_ARGS contains A. */
8221 static int
8222 coerce_template_template_parms (tree parm_tmpl,
8223 tree arg_tmpl,
8224 tsubst_flags_t complain,
8225 tree in_decl,
8226 tree outer_args)
8228 int nparms, nargs, i;
8229 tree parm, arg;
8230 int variadic_p = 0;
8232 tree parm_parms = DECL_INNERMOST_TEMPLATE_PARMS (parm_tmpl);
8233 tree arg_parms = DECL_INNERMOST_TEMPLATE_PARMS (arg_tmpl);
8234 tree gen_arg_tmpl = most_general_template (arg_tmpl);
8235 tree gen_arg_parms = DECL_INNERMOST_TEMPLATE_PARMS (gen_arg_tmpl);
8237 nparms = TREE_VEC_LENGTH (parm_parms);
8238 nargs = TREE_VEC_LENGTH (arg_parms);
8240 if (flag_new_ttp)
8242 /* P0522R0: A template template-parameter P is at least as specialized as
8243 a template template-argument A if, given the following rewrite to two
8244 function templates, the function template corresponding to P is at
8245 least as specialized as the function template corresponding to A
8246 according to the partial ordering rules for function templates
8247 ([temp.func.order]). Given an invented class template X with the
8248 template parameter list of A (including default arguments):
8250 * Each of the two function templates has the same template parameters,
8251 respectively, as P or A.
8253 * Each function template has a single function parameter whose type is
8254 a specialization of X with template arguments corresponding to the
8255 template parameters from the respective function template where, for
8256 each template parameter PP in the template parameter list of the
8257 function template, a corresponding template argument AA is formed. If
8258 PP declares a parameter pack, then AA is the pack expansion
8259 PP... ([temp.variadic]); otherwise, AA is the id-expression PP.
8261 If the rewrite produces an invalid type, then P is not at least as
8262 specialized as A. */
8264 /* So coerce P's args to apply to A's parms, and then deduce between A's
8265 args and the converted args. If that succeeds, A is at least as
8266 specialized as P, so they match.*/
8267 processing_template_decl_sentinel ptds (/*reset*/false);
8268 ++processing_template_decl;
8270 tree pargs = template_parms_level_to_args (parm_parms);
8272 /* PARM and ARG might be at different template depths, and we want to
8273 pass the right additional levels of args when coercing PARGS to
8274 ARG_PARMS in case we need to do any substitution into non-type
8275 template parameter types.
8277 OUTER_ARGS are not the right outer levels in this case, as they are
8278 the args we're building up for PARM, and for the coercion we want the
8279 args for ARG. If DECL_CONTEXT isn't set for a template template
8280 parameter, we can assume that it's in the current scope. */
8281 tree ctx = DECL_CONTEXT (arg_tmpl);
8282 if (!ctx && DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
8283 ctx = current_scope ();
8284 tree scope_args = NULL_TREE;
8285 if (tree tinfo = get_template_info (ctx))
8286 scope_args = TI_ARGS (tinfo);
8287 if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
8289 int level = TEMPLATE_TYPE_LEVEL (TREE_TYPE (gen_arg_tmpl));
8290 int scope_depth = TMPL_ARGS_DEPTH (scope_args);
8291 tree full_pargs = make_tree_vec (level + 1);
8293 /* Only use as many levels from the scope as needed
8294 (excluding the level of ARG). */
8295 for (int i = 0; i < level - 1; ++i)
8296 if (i < scope_depth)
8297 TREE_VEC_ELT (full_pargs, i) = TMPL_ARGS_LEVEL (scope_args, i + 1);
8298 else
8299 TREE_VEC_ELT (full_pargs, i) = make_tree_vec (0);
8301 /* Add the arguments that appear at the levels of ARG. */
8302 tree adjacent = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (arg_tmpl));
8303 adjacent = TMPL_ARGS_LEVEL (adjacent, TMPL_ARGS_DEPTH (adjacent) - 1);
8304 TREE_VEC_ELT (full_pargs, level - 1) = adjacent;
8306 TREE_VEC_ELT (full_pargs, level) = pargs;
8307 pargs = full_pargs;
8309 else
8310 pargs = add_to_template_args (scope_args, pargs);
8312 pargs = coerce_template_parms (gen_arg_parms, pargs,
8313 NULL_TREE, tf_none);
8314 if (pargs != error_mark_node)
8316 tree targs = make_tree_vec (nargs);
8317 tree aargs = template_parms_level_to_args (arg_parms);
8318 if (!unify (arg_parms, targs, aargs, pargs, UNIFY_ALLOW_NONE,
8319 /*explain*/false))
8320 return 1;
8324 /* Determine whether we have a parameter pack at the end of the
8325 template template parameter's template parameter list. */
8326 if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
8328 parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
8330 if (error_operand_p (parm))
8331 return 0;
8333 switch (TREE_CODE (parm))
8335 case TEMPLATE_DECL:
8336 case TYPE_DECL:
8337 if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
8338 variadic_p = 1;
8339 break;
8341 case PARM_DECL:
8342 if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
8343 variadic_p = 1;
8344 break;
8346 default:
8347 gcc_unreachable ();
8351 if (nargs != nparms
8352 && !(variadic_p && nargs >= nparms - 1))
8353 return 0;
8355 /* Check all of the template parameters except the parameter pack at
8356 the end (if any). */
8357 for (i = 0; i < nparms - variadic_p; ++i)
8359 if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
8360 || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
8361 continue;
8363 parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
8364 arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
8366 if (!coerce_template_template_parm (parm, arg, complain, in_decl,
8367 outer_args))
8368 return 0;
8372 if (variadic_p)
8374 /* Check each of the template parameters in the template
8375 argument against the template parameter pack at the end of
8376 the template template parameter. */
8377 if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
8378 return 0;
8380 parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
8382 for (; i < nargs; ++i)
8384 if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
8385 continue;
8387 arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
8389 if (!coerce_template_template_parm (parm, arg, complain, in_decl,
8390 outer_args))
8391 return 0;
8395 return 1;
8398 /* Verifies that the deduced template arguments (in TARGS) for the
8399 template template parameters (in TPARMS) represent valid bindings,
8400 by comparing the template parameter list of each template argument
8401 to the template parameter list of its corresponding template
8402 template parameter, in accordance with DR150. This
8403 routine can only be called after all template arguments have been
8404 deduced. It will return TRUE if all of the template template
8405 parameter bindings are okay, FALSE otherwise. */
8406 bool
8407 template_template_parm_bindings_ok_p (tree tparms, tree targs)
8409 int i, ntparms = TREE_VEC_LENGTH (tparms);
8410 bool ret = true;
8412 /* We're dealing with template parms in this process. */
8413 ++processing_template_decl;
8415 targs = INNERMOST_TEMPLATE_ARGS (targs);
8417 for (i = 0; i < ntparms; ++i)
8419 tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
8420 tree targ = TREE_VEC_ELT (targs, i);
8422 if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
8424 tree packed_args = NULL_TREE;
8425 int idx, len = 1;
8427 if (ARGUMENT_PACK_P (targ))
8429 /* Look inside the argument pack. */
8430 packed_args = ARGUMENT_PACK_ARGS (targ);
8431 len = TREE_VEC_LENGTH (packed_args);
8434 for (idx = 0; idx < len; ++idx)
8436 if (packed_args)
8437 /* Extract the next argument from the argument
8438 pack. */
8439 targ = TREE_VEC_ELT (packed_args, idx);
8441 if (PACK_EXPANSION_P (targ))
8442 /* Look at the pattern of the pack expansion. */
8443 targ = PACK_EXPANSION_PATTERN (targ);
8445 /* Extract the template parameters from the template
8446 argument. */
8447 if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
8448 targ = TYPE_NAME (targ);
8450 /* Verify that we can coerce the template template
8451 parameters from the template argument to the template
8452 parameter. This requires an exact match. */
8453 if (TREE_CODE (targ) == TEMPLATE_DECL
8454 && !coerce_template_template_parms
8455 (tparm,
8456 targ,
8457 tf_none,
8458 tparm,
8459 targs))
8461 ret = false;
8462 goto out;
8468 out:
8470 --processing_template_decl;
8471 return ret;
8474 /* Since type attributes aren't mangled, we need to strip them from
8475 template type arguments. */
8477 tree
8478 canonicalize_type_argument (tree arg, tsubst_flags_t complain)
8480 if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
8481 return arg;
8482 bool removed_attributes = false;
8483 tree canon = strip_typedefs (arg, &removed_attributes);
8484 if (removed_attributes
8485 && (complain & tf_warning))
8486 warning (OPT_Wignored_attributes,
8487 "ignoring attributes on template argument %qT", arg);
8488 return canon;
8491 /* And from inside dependent non-type arguments like sizeof(Type). */
8493 static tree
8494 canonicalize_expr_argument (tree arg, tsubst_flags_t complain)
8496 if (!arg || arg == error_mark_node)
8497 return arg;
8498 bool removed_attributes = false;
8499 tree canon = strip_typedefs_expr (arg, &removed_attributes);
8500 if (removed_attributes
8501 && (complain & tf_warning))
8502 warning (OPT_Wignored_attributes,
8503 "ignoring attributes in template argument %qE", arg);
8504 return canon;
8507 /* A template declaration can be substituted for a constrained
8508 template template parameter only when the argument is no more
8509 constrained than the parameter. */
8511 static bool
8512 is_compatible_template_arg (tree parm, tree arg, tree args)
8514 tree parm_cons = get_constraints (parm);
8516 /* For now, allow constrained template template arguments
8517 and unconstrained template template parameters. */
8518 if (parm_cons == NULL_TREE)
8519 return true;
8521 /* If the template parameter is constrained, we need to rewrite its
8522 constraints in terms of the ARG's template parameters. This ensures
8523 that all of the template parameter types will have the same depth.
8525 Note that this is only valid when coerce_template_template_parm is
8526 true for the innermost template parameters of PARM and ARG. In other
8527 words, because coercion is successful, this conversion will be valid. */
8528 tree new_args = NULL_TREE;
8529 if (parm_cons)
8531 tree aparms = DECL_INNERMOST_TEMPLATE_PARMS (arg);
8532 new_args = template_parms_level_to_args (aparms);
8533 new_args = add_to_template_args (args, new_args);
8534 ++processing_template_decl;
8535 parm_cons = tsubst_constraint_info (parm_cons, new_args,
8536 tf_none, NULL_TREE);
8537 --processing_template_decl;
8538 if (parm_cons == error_mark_node)
8539 return false;
8542 return ttp_subsumes (parm_cons, arg);
8545 // Convert a placeholder argument into a binding to the original
8546 // parameter. The original parameter is saved as the TREE_TYPE of
8547 // ARG.
8548 static inline tree
8549 convert_wildcard_argument (tree parm, tree arg)
8551 TREE_TYPE (arg) = parm;
8552 return arg;
8555 /* We can't fully resolve ARG given as a non-type template argument to TYPE,
8556 because one of them is dependent. But we need to represent the
8557 conversion for the benefit of cp_tree_equal. */
8559 static tree
8560 maybe_convert_nontype_argument (tree type, tree arg, bool force)
8562 /* Auto parms get no conversion. */
8563 if (type_uses_auto (type))
8564 return arg;
8565 /* ??? Do we need to push the IMPLICIT_CONV_EXPR into the pack expansion?
8566 That would complicate other things, and it doesn't seem necessary. */
8567 if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
8568 return arg;
8569 /* We don't need or want to add this conversion now if we're going to use the
8570 argument for deduction. */
8571 if (!value_dependent_expression_p (arg))
8572 force = false;
8573 else if (!force)
8574 return arg;
8576 type = cv_unqualified (type);
8577 tree argtype = TREE_TYPE (arg);
8578 if (argtype && same_type_p (type, argtype))
8579 return arg;
8581 arg = build1 (IMPLICIT_CONV_EXPR, type, arg);
8582 IMPLICIT_CONV_EXPR_NONTYPE_ARG (arg) = true;
8583 IMPLICIT_CONV_EXPR_FORCED (arg) = force;
8584 return arg;
8587 /* Convert the indicated template ARG as necessary to match the
8588 indicated template PARM. Returns the converted ARG, or
8589 error_mark_node if the conversion was unsuccessful. Error and
8590 warning messages are issued under control of COMPLAIN. This
8591 conversion is for the Ith parameter in the parameter list. ARGS is
8592 the full set of template arguments deduced so far. */
8594 static tree
8595 convert_template_argument (tree parm,
8596 tree arg,
8597 tree args,
8598 tsubst_flags_t complain,
8599 int i,
8600 tree in_decl)
8602 tree orig_arg;
8603 tree val;
8604 int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
8606 if (parm == error_mark_node || error_operand_p (arg))
8607 return error_mark_node;
8609 /* Trivially convert placeholders. */
8610 if (TREE_CODE (arg) == WILDCARD_DECL)
8611 return convert_wildcard_argument (parm, arg);
8613 if (arg == any_targ_node)
8614 return arg;
8616 if (TREE_CODE (arg) == TREE_LIST
8617 && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
8619 /* The template argument was the name of some
8620 member function. That's usually
8621 invalid, but static members are OK. In any
8622 case, grab the underlying fields/functions
8623 and issue an error later if required. */
8624 TREE_TYPE (arg) = unknown_type_node;
8627 orig_arg = arg;
8629 requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
8630 requires_type = (TREE_CODE (parm) == TYPE_DECL
8631 || requires_tmpl_type);
8633 /* When determining whether an argument pack expansion is a template,
8634 look at the pattern. */
8635 if (PACK_EXPANSION_P (arg))
8636 arg = PACK_EXPANSION_PATTERN (arg);
8638 /* Deal with an injected-class-name used as a template template arg. */
8639 if (requires_tmpl_type && CLASS_TYPE_P (arg))
8641 tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
8642 if (TREE_CODE (t) == TEMPLATE_DECL)
8644 if (cxx_dialect >= cxx11)
8645 /* OK under DR 1004. */;
8646 else if (complain & tf_warning_or_error)
8647 pedwarn (input_location, OPT_Wpedantic, "injected-class-name %qD"
8648 " used as template template argument", TYPE_NAME (arg));
8649 else if (flag_pedantic_errors)
8650 t = arg;
8652 arg = t;
8656 is_tmpl_type =
8657 ((TREE_CODE (arg) == TEMPLATE_DECL
8658 && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
8659 || (requires_tmpl_type && TREE_CODE (arg) == TYPE_ARGUMENT_PACK)
8660 || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
8661 || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
8663 if (is_tmpl_type
8664 && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
8665 || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
8666 arg = TYPE_STUB_DECL (arg);
8668 is_type = TYPE_P (arg) || is_tmpl_type;
8670 if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
8671 && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
8673 if (TREE_CODE (TREE_OPERAND (arg, 1)) == BIT_NOT_EXPR)
8675 if (complain & tf_error)
8676 error ("invalid use of destructor %qE as a type", orig_arg);
8677 return error_mark_node;
8680 permerror (input_location,
8681 "to refer to a type member of a template parameter, "
8682 "use %<typename %E%>", orig_arg);
8684 orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
8685 TREE_OPERAND (arg, 1),
8686 typename_type,
8687 complain);
8688 arg = orig_arg;
8689 is_type = 1;
8691 if (is_type != requires_type)
8693 if (in_decl)
8695 if (complain & tf_error)
8697 auto_diagnostic_group d;
8698 error ("type/value mismatch at argument %d in template "
8699 "parameter list for %qD",
8700 i + 1, in_decl);
8701 if (is_type)
8703 /* The template argument is a type, but we're expecting
8704 an expression. */
8705 inform (input_location,
8706 " expected a constant of type %qT, got %qT",
8707 TREE_TYPE (parm),
8708 (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
8709 /* [temp.arg]/2: "In a template-argument, an ambiguity
8710 between a type-id and an expression is resolved to a
8711 type-id, regardless of the form of the corresponding
8712 template-parameter." So give the user a clue. */
8713 if (TREE_CODE (arg) == FUNCTION_TYPE)
8714 inform (input_location, " ambiguous template argument "
8715 "for non-type template parameter is treated as "
8716 "function type");
8718 else if (requires_tmpl_type)
8719 inform (input_location,
8720 " expected a class template, got %qE", orig_arg);
8721 else
8722 inform (input_location,
8723 " expected a type, got %qE", orig_arg);
8726 return error_mark_node;
8728 if (is_tmpl_type ^ requires_tmpl_type)
8730 if (in_decl && (complain & tf_error))
8732 auto_diagnostic_group d;
8733 error ("type/value mismatch at argument %d in template "
8734 "parameter list for %qD",
8735 i + 1, in_decl);
8736 if (is_tmpl_type)
8737 inform (input_location,
8738 " expected a type, got %qT", DECL_NAME (arg));
8739 else
8740 inform (input_location,
8741 " expected a class template, got %qT", orig_arg);
8743 return error_mark_node;
8746 if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
8747 /* We already did the appropriate conversion when packing args. */
8748 val = orig_arg;
8749 else if (is_type)
8751 if (requires_tmpl_type)
8753 if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
8754 /* The number of argument required is not known yet.
8755 Just accept it for now. */
8756 val = orig_arg;
8757 else
8759 /* Strip alias templates that are equivalent to another
8760 template. */
8761 arg = get_underlying_template (arg);
8763 if (coerce_template_template_parms (parm, arg,
8764 complain, in_decl,
8765 args))
8767 val = arg;
8769 /* TEMPLATE_TEMPLATE_PARM node is preferred over
8770 TEMPLATE_DECL. */
8771 if (val != error_mark_node)
8773 if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
8774 val = TREE_TYPE (val);
8775 if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
8776 val = make_pack_expansion (val, complain);
8779 else
8781 if (in_decl && (complain & tf_error))
8783 auto_diagnostic_group d;
8784 error ("type/value mismatch at argument %d in "
8785 "template parameter list for %qD",
8786 i + 1, in_decl);
8787 inform (input_location,
8788 " expected a template of type %qD, got %qT",
8789 parm, orig_arg);
8792 val = error_mark_node;
8795 // Check that the constraints are compatible before allowing the
8796 // substitution.
8797 if (val != error_mark_node)
8798 if (!is_compatible_template_arg (parm, arg, args))
8800 if (in_decl && (complain & tf_error))
8802 auto_diagnostic_group d;
8803 error ("constraint mismatch at argument %d in "
8804 "template parameter list for %qD",
8805 i + 1, in_decl);
8806 inform (input_location, " expected %qD but got %qD",
8807 parm, arg);
8809 val = error_mark_node;
8813 else
8814 val = orig_arg;
8815 /* We only form one instance of each template specialization.
8816 Therefore, if we use a non-canonical variant (i.e., a
8817 typedef), any future messages referring to the type will use
8818 the typedef, which is confusing if those future uses do not
8819 themselves also use the typedef. */
8820 if (TYPE_P (val))
8821 val = canonicalize_type_argument (val, complain);
8823 else
8825 tree t = TREE_TYPE (parm);
8827 if (TEMPLATE_PARM_LEVEL (get_template_parm_index (parm))
8828 > TMPL_ARGS_DEPTH (args))
8829 /* We don't have enough levels of args to do any substitution. This
8830 can happen in the context of -fnew-ttp-matching. */;
8831 else if (tree a = type_uses_auto (t))
8833 t = do_auto_deduction (t, arg, a, complain, adc_unify, args,
8834 LOOKUP_IMPLICIT, /*tmpl=*/in_decl);
8835 if (t == error_mark_node)
8836 return error_mark_node;
8838 else
8839 t = tsubst (t, args, complain, in_decl);
8841 /* Perform array-to-pointer and function-to-pointer conversion
8842 as per [temp.param]/10. */
8843 t = type_decays_to (t);
8845 if (invalid_nontype_parm_type_p (t, complain))
8846 return error_mark_node;
8848 /* Drop top-level cv-qualifiers on the substituted/deduced type of
8849 this non-type template parameter, as per [temp.param]/6. */
8850 t = cv_unqualified (t);
8852 if (t != TREE_TYPE (parm))
8853 t = canonicalize_type_argument (t, complain);
8855 /* We need to handle arguments for alias or concept templates
8856 differently: we need to force building an IMPLICIT_CONV_EXPR, because
8857 these arguments are going to be substituted directly into the
8858 dependent type; they might not get another chance at
8859 convert_nontype_argument. But if the argument ends up here again for
8860 a template that isn't one of those, remove the conversion for
8861 consistency between naming the same dependent type directly or through
8862 an alias. */
8863 bool force_conv = in_decl && (DECL_ALIAS_TEMPLATE_P (in_decl)
8864 || concept_definition_p (in_decl));
8865 if (!force_conv
8866 && TREE_CODE (orig_arg) == IMPLICIT_CONV_EXPR
8867 && IMPLICIT_CONV_EXPR_FORCED (orig_arg)
8868 && same_type_p (TREE_TYPE (orig_arg), t))
8869 orig_arg = TREE_OPERAND (orig_arg, 0);
8871 if (!type_dependent_expression_p (orig_arg)
8872 && !uses_template_parms (t))
8873 /* We used to call digest_init here. However, digest_init
8874 will report errors, which we don't want when complain
8875 is zero. More importantly, digest_init will try too
8876 hard to convert things: for example, `0' should not be
8877 converted to pointer type at this point according to
8878 the standard. Accepting this is not merely an
8879 extension, since deciding whether or not these
8880 conversions can occur is part of determining which
8881 function template to call, or whether a given explicit
8882 argument specification is valid. */
8883 val = convert_nontype_argument (t, orig_arg, complain);
8884 else
8886 val = canonicalize_expr_argument (orig_arg, complain);
8887 val = maybe_convert_nontype_argument (t, val, force_conv);
8890 if (val == NULL_TREE)
8891 val = error_mark_node;
8892 else if (val == error_mark_node && (complain & tf_error))
8893 error_at (cp_expr_loc_or_input_loc (orig_arg),
8894 "could not convert template argument %qE from %qT to %qT",
8895 orig_arg, TREE_TYPE (orig_arg), t);
8897 if (INDIRECT_REF_P (val))
8899 /* Reject template arguments that are references to built-in
8900 functions with no library fallbacks. */
8901 const_tree inner = TREE_OPERAND (val, 0);
8902 const_tree innertype = TREE_TYPE (inner);
8903 if (innertype
8904 && TYPE_REF_P (innertype)
8905 && TREE_CODE (TREE_TYPE (innertype)) == FUNCTION_TYPE
8906 && TREE_OPERAND_LENGTH (inner) > 0
8907 && reject_gcc_builtin (TREE_OPERAND (inner, 0)))
8908 return error_mark_node;
8911 if (TREE_CODE (val) == SCOPE_REF)
8913 /* Strip typedefs from the SCOPE_REF. */
8914 tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
8915 tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
8916 complain);
8917 val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
8918 QUALIFIED_NAME_IS_TEMPLATE (val));
8922 return val;
8925 /* Coerces the remaining template arguments in INNER_ARGS (from
8926 ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
8927 Returns the coerced argument pack. PARM_IDX is the position of this
8928 parameter in the template parameter list. ARGS is the original
8929 template argument list. */
8930 static tree
8931 coerce_template_parameter_pack (tree parms,
8932 int parm_idx,
8933 tree args,
8934 tree inner_args,
8935 int arg_idx,
8936 tree new_args,
8937 int* lost,
8938 tree in_decl,
8939 tsubst_flags_t complain)
8941 tree parm = TREE_VEC_ELT (parms, parm_idx);
8942 int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8943 tree packed_args;
8944 tree argument_pack;
8945 tree packed_parms = NULL_TREE;
8947 if (arg_idx > nargs)
8948 arg_idx = nargs;
8950 if (tree packs = fixed_parameter_pack_p (TREE_VALUE (parm)))
8952 /* When the template parameter is a non-type template parameter pack
8953 or template template parameter pack whose type or template
8954 parameters use parameter packs, we know exactly how many arguments
8955 we are looking for. Build a vector of the instantiated decls for
8956 these template parameters in PACKED_PARMS. */
8957 /* We can't use make_pack_expansion here because it would interpret a
8958 _DECL as a use rather than a declaration. */
8959 tree decl = TREE_VALUE (parm);
8960 tree exp = cxx_make_type (TYPE_PACK_EXPANSION);
8961 PACK_EXPANSION_PATTERN (exp) = decl;
8962 PACK_EXPANSION_PARAMETER_PACKS (exp) = packs;
8963 SET_TYPE_STRUCTURAL_EQUALITY (exp);
8965 TREE_VEC_LENGTH (args)--;
8966 packed_parms = tsubst_pack_expansion (exp, args, complain, decl);
8967 TREE_VEC_LENGTH (args)++;
8969 if (packed_parms == error_mark_node)
8970 return error_mark_node;
8972 /* If we're doing a partial instantiation of a member template,
8973 verify that all of the types used for the non-type
8974 template parameter pack are, in fact, valid for non-type
8975 template parameters. */
8976 if (arg_idx < nargs
8977 && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
8979 int j, len = TREE_VEC_LENGTH (packed_parms);
8980 for (j = 0; j < len; ++j)
8982 tree t = TREE_VEC_ELT (packed_parms, j);
8983 if (TREE_CODE (t) == PARM_DECL
8984 && invalid_nontype_parm_type_p (TREE_TYPE (t), complain))
8985 return error_mark_node;
8987 /* We don't know how many args we have yet, just
8988 use the unconverted ones for now. */
8989 return NULL_TREE;
8992 packed_args = make_tree_vec (TREE_VEC_LENGTH (packed_parms));
8994 /* Check if we have a placeholder pack, which indicates we're
8995 in the context of a introduction list. In that case we want
8996 to match this pack to the single placeholder. */
8997 else if (arg_idx < nargs
8998 && TREE_CODE (TREE_VEC_ELT (inner_args, arg_idx)) == WILDCARD_DECL
8999 && WILDCARD_PACK_P (TREE_VEC_ELT (inner_args, arg_idx)))
9001 nargs = arg_idx + 1;
9002 packed_args = make_tree_vec (1);
9004 else
9005 packed_args = make_tree_vec (nargs - arg_idx);
9007 /* Convert the remaining arguments, which will be a part of the
9008 parameter pack "parm". */
9009 int first_pack_arg = arg_idx;
9010 for (; arg_idx < nargs; ++arg_idx)
9012 tree arg = TREE_VEC_ELT (inner_args, arg_idx);
9013 tree actual_parm = TREE_VALUE (parm);
9014 int pack_idx = arg_idx - first_pack_arg;
9016 if (packed_parms)
9018 /* Once we've packed as many args as we have types, stop. */
9019 if (pack_idx >= TREE_VEC_LENGTH (packed_parms))
9020 break;
9021 else if (PACK_EXPANSION_P (arg))
9022 /* We don't know how many args we have yet, just
9023 use the unconverted ones for now. */
9024 return NULL_TREE;
9025 else
9026 actual_parm = TREE_VEC_ELT (packed_parms, pack_idx);
9029 if (arg == error_mark_node)
9031 if (complain & tf_error)
9032 error ("template argument %d is invalid", arg_idx + 1);
9034 else
9035 arg = convert_template_argument (actual_parm,
9036 arg, new_args, complain, parm_idx,
9037 in_decl);
9038 if (arg == error_mark_node)
9039 (*lost)++;
9040 TREE_VEC_ELT (packed_args, pack_idx) = arg;
9043 if (arg_idx - first_pack_arg < TREE_VEC_LENGTH (packed_args)
9044 && TREE_VEC_LENGTH (packed_args) > 0)
9046 if (complain & tf_error)
9047 error ("wrong number of template arguments (%d, should be %d)",
9048 arg_idx - first_pack_arg, TREE_VEC_LENGTH (packed_args));
9049 return error_mark_node;
9052 if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
9053 || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
9054 argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
9055 else
9057 argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
9058 TREE_CONSTANT (argument_pack) = 1;
9061 ARGUMENT_PACK_ARGS (argument_pack) = packed_args;
9062 if (CHECKING_P)
9063 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
9064 TREE_VEC_LENGTH (packed_args));
9065 return argument_pack;
9068 /* Returns the number of pack expansions in the template argument vector
9069 ARGS. */
9071 static int
9072 pack_expansion_args_count (tree args)
9074 int i;
9075 int count = 0;
9076 if (args)
9077 for (i = 0; i < TREE_VEC_LENGTH (args); ++i)
9079 tree elt = TREE_VEC_ELT (args, i);
9080 if (elt && PACK_EXPANSION_P (elt))
9081 ++count;
9083 return count;
9086 /* Convert all template arguments to their appropriate types, and
9087 return a vector containing the innermost resulting template
9088 arguments. If any error occurs, return error_mark_node. Error and
9089 warning messages are issued under control of COMPLAIN.
9091 If PARMS represents all template parameters levels, this function
9092 returns a vector of vectors representing all the resulting argument
9093 levels. Note that in this case, only the innermost arguments are
9094 coerced because the outermost ones are supposed to have been coerced
9095 already. Otherwise, if PARMS represents only (the innermost) vector
9096 of parameters, this function returns a vector containing just the
9097 innermost resulting arguments.
9099 If REQUIRE_ALL_ARGS is false, argument deduction will be performed
9100 for arguments not specified in ARGS. If REQUIRE_ALL_ARGS is true,
9101 arguments not specified in ARGS must have default arguments which
9102 we'll use to fill in ARGS. */
9104 tree
9105 coerce_template_parms (tree parms,
9106 tree args,
9107 tree in_decl,
9108 tsubst_flags_t complain,
9109 bool require_all_args /* = true */)
9111 int nparms, nargs, parm_idx, arg_idx, lost = 0;
9112 tree orig_inner_args;
9113 tree inner_args;
9115 /* When used as a boolean value, indicates whether this is a
9116 variadic template parameter list. Since it's an int, we can also
9117 subtract it from nparms to get the number of non-variadic
9118 parameters. */
9119 int variadic_p = 0;
9120 int variadic_args_p = 0;
9121 int post_variadic_parms = 0;
9123 /* Adjustment to nparms for fixed parameter packs. */
9124 int fixed_pack_adjust = 0;
9125 int fixed_packs = 0;
9126 int missing = 0;
9128 /* Likewise for parameters with default arguments. */
9129 int default_p = 0;
9131 if (args == error_mark_node)
9132 return error_mark_node;
9134 bool return_full_args = false;
9135 if (TREE_CODE (parms) == TREE_LIST)
9137 if (TMPL_PARMS_DEPTH (parms) > 1)
9139 gcc_assert (TMPL_PARMS_DEPTH (parms) == TMPL_ARGS_DEPTH (args));
9140 return_full_args = true;
9142 parms = INNERMOST_TEMPLATE_PARMS (parms);
9145 nparms = TREE_VEC_LENGTH (parms);
9147 /* Determine if there are any parameter packs or default arguments. */
9148 for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
9150 tree parm = TREE_VEC_ELT (parms, parm_idx);
9151 if (variadic_p)
9152 ++post_variadic_parms;
9153 if (template_parameter_pack_p (TREE_VALUE (parm)))
9154 ++variadic_p;
9155 if (TREE_PURPOSE (parm))
9156 ++default_p;
9159 inner_args = orig_inner_args = INNERMOST_TEMPLATE_ARGS (args);
9160 /* If there are no parameters that follow a parameter pack, we need to
9161 expand any argument packs so that we can deduce a parameter pack from
9162 some non-packed args followed by an argument pack, as in variadic85.C.
9163 If there are such parameters, we need to leave argument packs intact
9164 so the arguments are assigned properly. This can happen when dealing
9165 with a nested class inside a partial specialization of a class
9166 template, as in variadic92.C, or when deducing a template parameter pack
9167 from a sub-declarator, as in variadic114.C. */
9168 if (!post_variadic_parms)
9169 inner_args = expand_template_argument_pack (inner_args);
9171 /* Count any pack expansion args. */
9172 variadic_args_p = pack_expansion_args_count (inner_args);
9174 nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
9175 if ((nargs - variadic_args_p > nparms && !variadic_p)
9176 || (nargs < nparms - variadic_p
9177 && require_all_args
9178 && !variadic_args_p
9179 && (TREE_VEC_ELT (parms, nargs) != error_mark_node
9180 && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs)))))
9182 bad_nargs:
9183 if (complain & tf_error)
9185 auto_diagnostic_group d;
9186 if (variadic_p || default_p)
9188 nparms -= variadic_p + default_p;
9189 error ("wrong number of template arguments "
9190 "(%d, should be at least %d)", nargs, nparms);
9192 else
9193 error ("wrong number of template arguments "
9194 "(%d, should be %d)", nargs, nparms);
9196 if (in_decl)
9197 inform (DECL_SOURCE_LOCATION (in_decl),
9198 "provided for %qD", in_decl);
9201 return error_mark_node;
9203 /* We can't pass a pack expansion to a non-pack parameter of an alias
9204 template (DR 1430). */
9205 else if (in_decl
9206 && (DECL_ALIAS_TEMPLATE_P (in_decl)
9207 || concept_definition_p (in_decl))
9208 && variadic_args_p
9209 && nargs - variadic_args_p < nparms - variadic_p)
9211 if (complain & tf_error)
9213 for (int i = 0; i < TREE_VEC_LENGTH (inner_args); ++i)
9215 tree arg = TREE_VEC_ELT (inner_args, i);
9216 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
9218 if (PACK_EXPANSION_P (arg)
9219 && !template_parameter_pack_p (parm))
9221 auto_diagnostic_group d;
9222 if (DECL_ALIAS_TEMPLATE_P (in_decl))
9223 error_at (location_of (arg),
9224 "pack expansion argument for non-pack parameter "
9225 "%qD of alias template %qD", parm, in_decl);
9226 else
9227 error_at (location_of (arg),
9228 "pack expansion argument for non-pack parameter "
9229 "%qD of concept %qD", parm, in_decl);
9230 inform (DECL_SOURCE_LOCATION (parm), "declared here");
9231 goto found;
9234 gcc_unreachable ();
9235 found:;
9237 return error_mark_node;
9240 /* We need to evaluate the template arguments, even though this
9241 template-id may be nested within a "sizeof". */
9242 cp_evaluated ev;
9244 tree new_args = add_outermost_template_args (args, make_tree_vec (nparms));
9245 tree& new_inner_args = TMPL_ARGS_LEVEL (new_args, TMPL_ARGS_DEPTH (new_args));
9246 int pack_adjust = 0;
9247 for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
9249 tree arg;
9250 tree parm;
9252 /* Get the Ith template parameter. */
9253 parm = TREE_VEC_ELT (parms, parm_idx);
9255 if (parm == error_mark_node)
9257 TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
9258 continue;
9261 /* Calculate the next argument. */
9262 if (arg_idx < nargs)
9263 arg = TREE_VEC_ELT (inner_args, arg_idx);
9264 else
9265 arg = NULL_TREE;
9267 if (template_parameter_pack_p (TREE_VALUE (parm))
9268 && (arg || require_all_args || !(complain & tf_partial))
9269 && !(arg && ARGUMENT_PACK_P (arg)))
9271 /* Some arguments will be placed in the
9272 template parameter pack PARM. */
9273 arg = coerce_template_parameter_pack (parms, parm_idx, args,
9274 inner_args, arg_idx,
9275 new_args, &lost,
9276 in_decl, complain);
9278 if (arg == NULL_TREE)
9280 /* We don't know how many args we have yet, just use the
9281 unconverted (and still packed) ones for now. */
9282 ggc_free (new_inner_args);
9283 new_inner_args = orig_inner_args;
9284 arg_idx = nargs;
9285 break;
9288 TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
9290 /* Store this argument. */
9291 if (arg == error_mark_node)
9293 lost++;
9294 /* We are done with all of the arguments. */
9295 arg_idx = nargs;
9296 break;
9298 else
9300 pack_adjust = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg)) - 1;
9301 arg_idx += pack_adjust;
9302 if (fixed_parameter_pack_p (TREE_VALUE (parm)))
9304 ++fixed_packs;
9305 fixed_pack_adjust += pack_adjust;
9309 continue;
9311 else if (arg)
9313 if (PACK_EXPANSION_P (arg))
9315 /* "If every valid specialization of a variadic template
9316 requires an empty template parameter pack, the template is
9317 ill-formed, no diagnostic required." So check that the
9318 pattern works with this parameter. */
9319 tree pattern = PACK_EXPANSION_PATTERN (arg);
9320 tree conv = convert_template_argument (TREE_VALUE (parm),
9321 pattern, new_args,
9322 complain, parm_idx,
9323 in_decl);
9324 if (conv == error_mark_node)
9326 if (complain & tf_error)
9327 inform (input_location, "so any instantiation with a "
9328 "non-empty parameter pack would be ill-formed");
9329 ++lost;
9331 else if (TYPE_P (conv) && !TYPE_P (pattern))
9332 /* Recover from missing typename. */
9333 TREE_VEC_ELT (inner_args, arg_idx)
9334 = make_pack_expansion (conv, complain);
9336 /* We don't know how many args we have yet, just
9337 use the unconverted (but unpacked) ones for now. */
9338 ggc_free (new_inner_args);
9339 new_inner_args = inner_args;
9340 arg_idx = nargs;
9341 break;
9344 else if (require_all_args)
9346 /* There must be a default arg in this case. */
9347 arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
9348 complain | (processing_template_decl
9349 ? tf_partial : tf_none),
9350 in_decl);
9351 /* The position of the first default template argument,
9352 is also the number of non-defaulted arguments in NEW_INNER_ARGS.
9353 Record that. */
9354 if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
9355 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
9356 arg_idx - pack_adjust);
9358 else
9359 break;
9361 if (arg == error_mark_node)
9363 if (complain & tf_error)
9364 error ("template argument %d is invalid", arg_idx + 1);
9366 else if (!arg)
9368 /* This can occur if there was an error in the template
9369 parameter list itself (which we would already have
9370 reported) that we are trying to recover from, e.g., a class
9371 template with a parameter list such as
9372 template<typename..., typename> (cpp0x/variadic150.C). */
9373 ++lost;
9375 /* This can also happen with a fixed parameter pack (71834). */
9376 if (arg_idx >= nargs)
9377 ++missing;
9379 else
9380 arg = convert_template_argument (TREE_VALUE (parm),
9381 arg, new_args, complain,
9382 parm_idx, in_decl);
9384 if (arg == error_mark_node)
9385 lost++;
9387 TREE_VEC_ELT (new_inner_args, arg_idx - pack_adjust) = arg;
9390 if (missing || arg_idx < nargs - variadic_args_p)
9392 /* If we had fixed parameter packs, we didn't know how many arguments we
9393 actually needed earlier; now we do. */
9394 nparms += fixed_pack_adjust;
9395 variadic_p -= fixed_packs;
9396 goto bad_nargs;
9399 if (arg_idx < nargs)
9401 /* We had some pack expansion arguments that will only work if the packs
9402 are empty, but wait until instantiation time to complain.
9403 See variadic-ttp3.C. */
9405 /* Except that we can't provide empty packs to alias templates or
9406 concepts when there are no corresponding parameters. Basically,
9407 we can get here with this:
9409 template<typename T> concept C = true;
9411 template<typename... Args>
9412 requires C<Args...>
9413 void f();
9415 When parsing C<Args...>, we try to form a concept check of
9416 C<?, Args...>. Without the extra check for substituting an empty
9417 pack past the last parameter, we can accept the check as valid.
9419 FIXME: This may be valid for alias templates (but I doubt it).
9421 FIXME: The error could be better also. */
9422 if (in_decl && concept_definition_p (in_decl))
9424 if (complain & tf_error)
9425 error_at (location_of (TREE_VEC_ELT (args, arg_idx)),
9426 "too many arguments");
9427 return error_mark_node;
9430 int len = nparms + (nargs - arg_idx);
9431 tree args = make_tree_vec (len);
9432 int i = 0;
9433 for (; i < nparms; ++i)
9434 TREE_VEC_ELT (args, i) = TREE_VEC_ELT (new_inner_args, i);
9435 for (; i < len; ++i, ++arg_idx)
9436 TREE_VEC_ELT (args, i) = TREE_VEC_ELT (inner_args,
9437 arg_idx - pack_adjust);
9438 new_inner_args = args;
9441 if (lost)
9443 gcc_assert (!(complain & tf_error) || seen_error ());
9444 return error_mark_node;
9447 if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
9448 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
9449 TREE_VEC_LENGTH (new_inner_args));
9451 /* If we expanded packs in inner_args and aren't returning it now, the
9452 expanded vec is garbage. */
9453 if (inner_args != new_inner_args
9454 && inner_args != orig_inner_args)
9455 ggc_free (inner_args);
9457 return return_full_args ? new_args : new_inner_args;
9460 /* Returns true if T is a wrapper to make a C++20 template parameter
9461 object const. */
9463 static bool
9464 class_nttp_const_wrapper_p (tree t)
9466 if (cxx_dialect < cxx20)
9467 return false;
9468 return (TREE_CODE (t) == VIEW_CONVERT_EXPR
9469 && CP_TYPE_CONST_P (TREE_TYPE (t))
9470 && TREE_CODE (TREE_OPERAND (t, 0)) == TEMPLATE_PARM_INDEX);
9473 /* Returns 1 if template args OT and NT are equivalent. */
9476 template_args_equal (tree ot, tree nt)
9478 if (nt == ot)
9479 return 1;
9480 if (nt == NULL_TREE || ot == NULL_TREE)
9481 return false;
9482 if (nt == any_targ_node || ot == any_targ_node)
9483 return true;
9485 if (class_nttp_const_wrapper_p (nt))
9486 nt = TREE_OPERAND (nt, 0);
9487 if (class_nttp_const_wrapper_p (ot))
9488 ot = TREE_OPERAND (ot, 0);
9490 /* DR 1558: Don't treat an alias template specialization with dependent
9491 arguments as equivalent to its underlying type when used as a template
9492 argument; we need them to be distinct so that we substitute into the
9493 specialization arguments at instantiation time. And aliases can't be
9494 equivalent without being ==, so we don't need to look any deeper.
9496 During partial ordering, however, we need to treat them normally so we can
9497 order uses of the same alias with different cv-qualification (79960). */
9498 auto cso = make_temp_override (comparing_dependent_aliases);
9499 if (!comparing_for_partial_ordering)
9500 ++comparing_dependent_aliases;
9502 if (TREE_CODE (nt) == TREE_VEC || TREE_CODE (ot) == TREE_VEC)
9503 /* For member templates */
9504 return TREE_CODE (ot) == TREE_CODE (nt) && comp_template_args (ot, nt);
9505 else if (PACK_EXPANSION_P (ot) || PACK_EXPANSION_P (nt))
9506 return (PACK_EXPANSION_P (ot) && PACK_EXPANSION_P (nt)
9507 && template_args_equal (PACK_EXPANSION_PATTERN (ot),
9508 PACK_EXPANSION_PATTERN (nt))
9509 && template_args_equal (PACK_EXPANSION_EXTRA_ARGS (ot),
9510 PACK_EXPANSION_EXTRA_ARGS (nt)));
9511 else if (ARGUMENT_PACK_P (ot) || ARGUMENT_PACK_P (nt))
9512 return cp_tree_equal (ot, nt);
9513 else if (TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
9514 gcc_unreachable ();
9515 else if (TYPE_P (nt) || TYPE_P (ot))
9517 if (!(TYPE_P (nt) && TYPE_P (ot)))
9518 return false;
9519 return same_type_p (ot, nt);
9521 else
9523 /* Try to treat a template non-type argument that has been converted
9524 to the parameter type as equivalent to one that hasn't yet. */
9525 for (enum tree_code code1 = TREE_CODE (ot);
9526 CONVERT_EXPR_CODE_P (code1)
9527 || code1 == NON_LVALUE_EXPR;
9528 code1 = TREE_CODE (ot))
9529 ot = TREE_OPERAND (ot, 0);
9531 for (enum tree_code code2 = TREE_CODE (nt);
9532 CONVERT_EXPR_CODE_P (code2)
9533 || code2 == NON_LVALUE_EXPR;
9534 code2 = TREE_CODE (nt))
9535 nt = TREE_OPERAND (nt, 0);
9537 return cp_tree_equal (ot, nt);
9541 /* Returns true iff the OLDARGS and NEWARGS are in fact identical sets of
9542 template arguments. Returns false otherwise, and updates OLDARG_PTR and
9543 NEWARG_PTR with the offending arguments if they are non-NULL. */
9545 bool
9546 comp_template_args (tree oldargs, tree newargs,
9547 tree *oldarg_ptr /* = NULL */, tree *newarg_ptr /* = NULL */)
9549 if (oldargs == newargs)
9550 return true;
9552 if (!oldargs || !newargs)
9553 return false;
9555 if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
9556 return false;
9558 for (int i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
9560 tree nt = TREE_VEC_ELT (newargs, i);
9561 tree ot = TREE_VEC_ELT (oldargs, i);
9563 if (! template_args_equal (ot, nt))
9565 if (oldarg_ptr != NULL)
9566 *oldarg_ptr = ot;
9567 if (newarg_ptr != NULL)
9568 *newarg_ptr = nt;
9569 return false;
9572 return true;
9575 static bool
9576 comp_template_args_porder (tree oargs, tree nargs)
9578 ++comparing_for_partial_ordering;
9579 bool equal = comp_template_args (oargs, nargs);
9580 --comparing_for_partial_ordering;
9581 return equal;
9584 /* Implement a freelist interface for objects of type T.
9586 Head is a separate object, rather than a regular member, so that we
9587 can define it as a GTY deletable pointer, which is highly
9588 desirable. A data member could be declared that way, but then the
9589 containing object would implicitly get GTY((user)), which would
9590 prevent us from instantiating freelists as global objects.
9591 Although this way we can create freelist global objects, they're
9592 such thin wrappers that instantiating temporaries at every use
9593 loses nothing and saves permanent storage for the freelist object.
9595 Member functions next, anew, poison and reinit have default
9596 implementations that work for most of the types we're interested
9597 in, but if they don't work for some type, they should be explicitly
9598 specialized. See the comments before them for requirements, and
9599 the example specializations for the tree_list_freelist. */
9600 template <typename T>
9601 class freelist
9603 /* Return the next object in a chain. We could just do type
9604 punning, but if we access the object with its underlying type, we
9605 avoid strict-aliasing trouble. This needs only work between
9606 poison and reinit. */
9607 static T *&next (T *obj) { return obj->next; }
9609 /* Return a newly allocated, uninitialized or minimally-initialized
9610 object of type T. Any initialization performed by anew should
9611 either remain across the life of the object and the execution of
9612 poison, or be redone by reinit. */
9613 static T *anew () { return ggc_alloc<T> (); }
9615 /* Optionally scribble all over the bits holding the object, so that
9616 they become (mostly?) uninitialized memory. This is called while
9617 preparing to make the object part of the free list. */
9618 static void poison (T *obj) {
9619 T *p ATTRIBUTE_UNUSED = obj;
9620 T **q ATTRIBUTE_UNUSED = &next (obj);
9622 #ifdef ENABLE_GC_CHECKING
9623 /* Poison the data, to indicate the data is garbage. */
9624 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, sizeof (*p)));
9625 memset (p, 0xa5, sizeof (*p));
9626 #endif
9627 /* Let valgrind know the object is free. */
9628 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, sizeof (*p)));
9630 /* Let valgrind know the next portion of the object is available,
9631 but uninitialized. */
9632 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
9635 /* Bring an object that underwent at least one lifecycle after anew
9636 and before the most recent free and poison, back to a usable
9637 state, reinitializing whatever is needed for it to be
9638 functionally equivalent to an object just allocated and returned
9639 by anew. This may poison or clear the next field, used by
9640 freelist housekeeping after poison was called. */
9641 static void reinit (T *obj) {
9642 T **q ATTRIBUTE_UNUSED = &next (obj);
9644 #ifdef ENABLE_GC_CHECKING
9645 memset (q, 0xa5, sizeof (*q));
9646 #endif
9647 /* Let valgrind know the entire object is available, but
9648 uninitialized. */
9649 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (*obj)));
9652 /* Reference a GTY-deletable pointer that points to the first object
9653 in the free list proper. */
9654 T *&head;
9655 public:
9656 /* Construct a freelist object chaining objects off of HEAD. */
9657 freelist (T *&head) : head(head) {}
9659 /* Add OBJ to the free object list. The former head becomes OBJ's
9660 successor. */
9661 void free (T *obj)
9663 poison (obj);
9664 next (obj) = head;
9665 head = obj;
9668 /* Take an object from the free list, if one is available, or
9669 allocate a new one. Objects taken from the free list should be
9670 regarded as filled with garbage, except for bits that are
9671 configured to be preserved across free and alloc. */
9672 T *alloc ()
9674 if (head)
9676 T *obj = head;
9677 head = next (head);
9678 reinit (obj);
9679 return obj;
9681 else
9682 return anew ();
9686 /* Explicitly specialize the interfaces for freelist<tree_node>: we
9687 want to allocate a TREE_LIST using the usual interface, and ensure
9688 TREE_CHAIN remains functional. Alas, we have to duplicate a bit of
9689 build_tree_list logic in reinit, so this could go out of sync. */
9690 template <>
9691 inline tree &
9692 freelist<tree_node>::next (tree obj)
9694 return TREE_CHAIN (obj);
9696 template <>
9697 inline tree
9698 freelist<tree_node>::anew ()
9700 return build_tree_list (NULL, NULL);
9702 template <>
9703 inline void
9704 freelist<tree_node>::poison (tree obj ATTRIBUTE_UNUSED)
9706 int size ATTRIBUTE_UNUSED = sizeof (tree_list);
9707 tree p ATTRIBUTE_UNUSED = obj;
9708 tree_base *b ATTRIBUTE_UNUSED = &obj->base;
9709 tree *q ATTRIBUTE_UNUSED = &next (obj);
9711 #ifdef ENABLE_GC_CHECKING
9712 gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
9714 /* Poison the data, to indicate the data is garbage. */
9715 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, size));
9716 memset (p, 0xa5, size);
9717 #endif
9718 /* Let valgrind know the object is free. */
9719 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, size));
9720 /* But we still want to use the TREE_CODE and TREE_CHAIN parts. */
9721 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9722 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
9724 #ifdef ENABLE_GC_CHECKING
9725 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (b, sizeof (*b)));
9726 /* Keep TREE_CHAIN functional. */
9727 TREE_SET_CODE (obj, TREE_LIST);
9728 #else
9729 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9730 #endif
9732 template <>
9733 inline void
9734 freelist<tree_node>::reinit (tree obj ATTRIBUTE_UNUSED)
9736 tree_common *c ATTRIBUTE_UNUSED = &obj->common;
9738 #ifdef ENABLE_GC_CHECKING
9739 gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
9740 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
9741 memset (obj, 0, sizeof (tree_list));
9742 #endif
9744 /* Let valgrind know the entire object is available, but
9745 uninitialized. */
9746 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
9748 #ifdef ENABLE_GC_CHECKING
9749 TREE_SET_CODE (obj, TREE_LIST);
9750 #else
9751 TREE_CHAIN (obj) = NULL_TREE;
9752 TREE_TYPE (obj) = NULL_TREE;
9753 #endif
9754 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (c, sizeof (*c)));
9757 /* Point to the first object in the TREE_LIST freelist. */
9758 static GTY((deletable)) tree tree_list_freelist_head;
9759 /* Return the/an actual TREE_LIST freelist. */
9760 static inline freelist<tree_node>
9761 tree_list_freelist ()
9763 return tree_list_freelist_head;
9766 /* Point to the first object in the tinst_level freelist. */
9767 static GTY((deletable)) tinst_level *tinst_level_freelist_head;
9768 /* Return the/an actual tinst_level freelist. */
9769 static inline freelist<tinst_level>
9770 tinst_level_freelist ()
9772 return tinst_level_freelist_head;
9775 /* Point to the first object in the pending_template freelist. */
9776 static GTY((deletable)) pending_template *pending_template_freelist_head;
9777 /* Return the/an actual pending_template freelist. */
9778 static inline freelist<pending_template>
9779 pending_template_freelist ()
9781 return pending_template_freelist_head;
9784 /* Build the TREE_LIST object out of a split list, store it
9785 permanently, and return it. */
9786 tree
9787 tinst_level::to_list ()
9789 gcc_assert (split_list_p ());
9790 tree ret = tree_list_freelist ().alloc ();
9791 TREE_PURPOSE (ret) = tldcl;
9792 TREE_VALUE (ret) = targs;
9793 tldcl = ret;
9794 targs = NULL;
9795 gcc_assert (tree_list_p ());
9796 return ret;
9799 const unsigned short tinst_level::refcount_infinity;
9801 /* Increment OBJ's refcount unless it is already infinite. */
9802 static tinst_level *
9803 inc_refcount_use (tinst_level *obj)
9805 if (obj && obj->refcount != tinst_level::refcount_infinity)
9806 ++obj->refcount;
9807 return obj;
9810 /* Release storage for OBJ and node, if it's a TREE_LIST. */
9811 void
9812 tinst_level::free (tinst_level *obj)
9814 if (obj->tree_list_p ())
9815 tree_list_freelist ().free (obj->get_node ());
9816 tinst_level_freelist ().free (obj);
9819 /* Decrement OBJ's refcount if not infinite. If it reaches zero, release
9820 OBJ's DECL and OBJ, and start over with the tinst_level object that
9821 used to be referenced by OBJ's NEXT. */
9822 static void
9823 dec_refcount_use (tinst_level *obj)
9825 while (obj
9826 && obj->refcount != tinst_level::refcount_infinity
9827 && !--obj->refcount)
9829 tinst_level *next = obj->next;
9830 tinst_level::free (obj);
9831 obj = next;
9835 /* Modify PTR so that it points to OBJ, adjusting the refcounts of OBJ
9836 and of the former PTR. Omitting the second argument is equivalent
9837 to passing (T*)NULL; this is allowed because passing the
9838 zero-valued integral constant NULL confuses type deduction and/or
9839 overload resolution. */
9840 template <typename T>
9841 static void
9842 set_refcount_ptr (T *& ptr, T *obj = NULL)
9844 T *save = ptr;
9845 ptr = inc_refcount_use (obj);
9846 dec_refcount_use (save);
9849 static void
9850 add_pending_template (tree d)
9852 tree ti = (TYPE_P (d)
9853 ? CLASSTYPE_TEMPLATE_INFO (d)
9854 : DECL_TEMPLATE_INFO (d));
9855 struct pending_template *pt;
9856 int level;
9858 if (TI_PENDING_TEMPLATE_FLAG (ti))
9859 return;
9861 /* We are called both from instantiate_decl, where we've already had a
9862 tinst_level pushed, and instantiate_template, where we haven't.
9863 Compensate. */
9864 gcc_assert (TREE_CODE (d) != TREE_LIST);
9865 level = !current_tinst_level
9866 || current_tinst_level->maybe_get_node () != d;
9868 if (level)
9869 push_tinst_level (d);
9871 pt = pending_template_freelist ().alloc ();
9872 pt->next = NULL;
9873 pt->tinst = NULL;
9874 set_refcount_ptr (pt->tinst, current_tinst_level);
9875 if (last_pending_template)
9876 last_pending_template->next = pt;
9877 else
9878 pending_templates = pt;
9880 last_pending_template = pt;
9882 TI_PENDING_TEMPLATE_FLAG (ti) = 1;
9884 if (level)
9885 pop_tinst_level ();
9889 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
9890 ARGLIST. Valid choices for FNS are given in the cp-tree.def
9891 documentation for TEMPLATE_ID_EXPR. */
9893 tree
9894 lookup_template_function (tree fns, tree arglist)
9896 if (fns == error_mark_node || arglist == error_mark_node)
9897 return error_mark_node;
9899 gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
9901 if (!is_overloaded_fn (fns) && !identifier_p (fns))
9903 error ("%q#D is not a function template", fns);
9904 return error_mark_node;
9907 if (BASELINK_P (fns))
9909 fns = copy_node (fns);
9910 BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
9911 unknown_type_node,
9912 BASELINK_FUNCTIONS (fns),
9913 arglist);
9914 return fns;
9917 return build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, arglist);
9920 /* Within the scope of a template class S<T>, the name S gets bound
9921 (in build_self_reference) to a TYPE_DECL for the class, not a
9922 TEMPLATE_DECL. If DECL is a TYPE_DECL for current_class_type,
9923 or one of its enclosing classes, and that type is a template,
9924 return the associated TEMPLATE_DECL. Otherwise, the original
9925 DECL is returned.
9927 Also handle the case when DECL is a TREE_LIST of ambiguous
9928 injected-class-names from different bases. */
9930 tree
9931 maybe_get_template_decl_from_type_decl (tree decl)
9933 if (decl == NULL_TREE)
9934 return decl;
9936 /* DR 176: A lookup that finds an injected-class-name (10.2
9937 [class.member.lookup]) can result in an ambiguity in certain cases
9938 (for example, if it is found in more than one base class). If all of
9939 the injected-class-names that are found refer to specializations of
9940 the same class template, and if the name is followed by a
9941 template-argument-list, the reference refers to the class template
9942 itself and not a specialization thereof, and is not ambiguous. */
9943 if (TREE_CODE (decl) == TREE_LIST)
9945 tree t, tmpl = NULL_TREE;
9946 for (t = decl; t; t = TREE_CHAIN (t))
9948 tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
9949 if (!tmpl)
9950 tmpl = elt;
9951 else if (tmpl != elt)
9952 break;
9954 if (tmpl && t == NULL_TREE)
9955 return tmpl;
9956 else
9957 return decl;
9960 return (decl != NULL_TREE
9961 && DECL_SELF_REFERENCE_P (decl)
9962 && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
9963 ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
9966 /* If TYPE is the generic implicit instantiation A<T>, return the primary
9967 template type A<T> (which is suitable for entering into, e.g. for defining
9968 a member of A<T>), otherwise return TYPE. */
9970 tree
9971 adjust_type_for_entering_scope (tree type)
9973 if (CLASS_TYPE_P (type)
9974 && dependent_type_p (type)
9975 && TYPE_TEMPLATE_INFO (type)
9976 /* We detect the generic implicit instantiation A<T> by inspecting
9977 TYPE_CANONICAL, which lookup_template_class sets to the primary
9978 template type A<T>. */
9979 && TYPE_CANONICAL (type) == TREE_TYPE (TYPE_TI_TEMPLATE (type)))
9980 type = TYPE_CANONICAL (type);
9982 return type;
9985 /* Convenience wrapper over tsubst that does adjust_type_for_entering_scope
9986 on the result. */
9988 static tree
9989 tsubst_entering_scope (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9991 t = tsubst (t, args, complain, in_decl);
9992 return adjust_type_for_entering_scope (t);
9995 /* Given an IDENTIFIER_NODE (or type TEMPLATE_DECL) and a chain of
9996 parameters, find the desired type.
9998 D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
10000 IN_DECL, if non-NULL, is the template declaration we are trying to
10001 instantiate.
10003 Issue error and warning messages under control of COMPLAIN.
10005 If the template class is really a local class in a template
10006 function, then the FUNCTION_CONTEXT is the function in which it is
10007 being instantiated.
10009 ??? Note that this function is currently called *twice* for each
10010 template-id: the first time from the parser, while creating the
10011 incomplete type (finish_template_type), and the second type during the
10012 real instantiation (instantiate_template_class). This is surely something
10013 that we want to avoid. It also causes some problems with argument
10014 coercion (see convert_nontype_argument for more information on this). */
10016 tree
10017 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
10018 tsubst_flags_t complain)
10020 auto_timevar tv (TV_TEMPLATE_INST);
10022 tree templ = NULL_TREE, parmlist;
10023 tree t;
10024 spec_entry **slot;
10025 spec_entry *entry;
10027 if (identifier_p (d1))
10029 tree value = innermost_non_namespace_value (d1);
10030 if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
10031 templ = value;
10032 else
10034 if (context)
10035 push_decl_namespace (context);
10036 templ = lookup_name (d1);
10037 templ = maybe_get_template_decl_from_type_decl (templ);
10038 if (context)
10039 pop_decl_namespace ();
10042 else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
10044 tree type = TREE_TYPE (d1);
10046 /* If we are declaring a constructor, say A<T>::A<T>, we will get
10047 an implicit typename for the second A. Deal with it. */
10048 if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
10049 type = TREE_TYPE (type);
10051 if (CLASSTYPE_TEMPLATE_INFO (type))
10053 templ = CLASSTYPE_TI_TEMPLATE (type);
10054 d1 = DECL_NAME (templ);
10057 else if (TREE_CODE (d1) == ENUMERAL_TYPE
10058 || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
10060 templ = TYPE_TI_TEMPLATE (d1);
10061 d1 = DECL_NAME (templ);
10063 else if (DECL_TYPE_TEMPLATE_P (d1))
10065 templ = d1;
10066 d1 = DECL_NAME (templ);
10068 else if (DECL_TEMPLATE_TEMPLATE_PARM_P (d1))
10070 templ = d1;
10071 d1 = DECL_NAME (templ);
10074 /* Issue an error message if we didn't find a template. */
10075 if (! templ)
10077 if (complain & tf_error)
10078 error ("%qT is not a template", d1);
10079 return error_mark_node;
10082 if (TREE_CODE (templ) != TEMPLATE_DECL
10083 /* Make sure it's a user visible template, if it was named by
10084 the user. */
10085 || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
10086 && !PRIMARY_TEMPLATE_P (templ)))
10088 if (complain & tf_error)
10090 error ("non-template type %qT used as a template", d1);
10091 if (in_decl)
10092 error ("for template declaration %q+D", in_decl);
10094 return error_mark_node;
10097 complain &= ~tf_user;
10099 /* An alias that just changes the name of a template is equivalent to the
10100 other template, so if any of the arguments are pack expansions, strip
10101 the alias to avoid problems with a pack expansion passed to a non-pack
10102 alias template parameter (DR 1430). */
10103 if (pack_expansion_args_count (INNERMOST_TEMPLATE_ARGS (arglist)))
10104 templ = get_underlying_template (templ);
10106 if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
10108 tree parm;
10109 tree arglist2 = coerce_template_args_for_ttp (templ, arglist, complain);
10110 if (arglist2 == error_mark_node
10111 || (!uses_template_parms (arglist2)
10112 && check_instantiated_args (templ, arglist2, complain)))
10113 return error_mark_node;
10115 parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
10116 return parm;
10118 else
10120 tree template_type = TREE_TYPE (templ);
10121 tree gen_tmpl;
10122 tree type_decl;
10123 tree found = NULL_TREE;
10124 int arg_depth;
10125 int parm_depth;
10126 int is_dependent_type;
10127 int use_partial_inst_tmpl = false;
10129 if (template_type == error_mark_node)
10130 /* An error occurred while building the template TEMPL, and a
10131 diagnostic has most certainly been emitted for that
10132 already. Let's propagate that error. */
10133 return error_mark_node;
10135 gen_tmpl = most_general_template (templ);
10136 if (modules_p ())
10137 lazy_load_pendings (gen_tmpl);
10139 parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
10140 parm_depth = TMPL_PARMS_DEPTH (parmlist);
10141 arg_depth = TMPL_ARGS_DEPTH (arglist);
10143 if (arg_depth == 1 && parm_depth > 1)
10145 /* We've been given an incomplete set of template arguments.
10146 For example, given:
10148 template <class T> struct S1 {
10149 template <class U> struct S2 {};
10150 template <class U> struct S2<U*> {};
10153 we will be called with an ARGLIST of `U*', but the
10154 TEMPLATE will be `template <class T> template
10155 <class U> struct S1<T>::S2'. We must fill in the missing
10156 arguments. */
10157 tree ti = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (templ));
10158 arglist = add_outermost_template_args (TI_ARGS (ti), arglist);
10159 arg_depth = TMPL_ARGS_DEPTH (arglist);
10162 /* Now we should have enough arguments. */
10163 gcc_assert (parm_depth == arg_depth);
10165 if (DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10167 /* The user referred to a specialization of an alias
10168 template represented by GEN_TMPL.
10170 [temp.alias]/2 says:
10172 When a template-id refers to the specialization of an
10173 alias template, it is equivalent to the associated
10174 type obtained by substitution of its
10175 template-arguments for the template-parameters in the
10176 type-id of the alias template. */
10178 t = instantiate_alias_template (gen_tmpl, arglist, complain);
10179 /* Note that the call above (by indirectly calling
10180 register_specialization in tsubst_decl) registers the
10181 TYPE_DECL representing the specialization of the alias
10182 template. So next time someone substitutes ARGLIST for
10183 the template parms into the alias template (GEN_TMPL),
10184 she'll get that TYPE_DECL back. */
10186 if (t == error_mark_node)
10187 return error_mark_node;
10188 return TREE_TYPE (t);
10191 /* From here on, we're only interested in the most general
10192 template. */
10194 /* Shortcut looking up the current class scope again. */
10195 for (tree cur = current_nonlambda_class_type ();
10196 cur != NULL_TREE;
10197 cur = get_containing_scope (cur))
10199 if (!CLASS_TYPE_P (cur))
10200 continue;
10202 tree ti = CLASSTYPE_TEMPLATE_INFO (cur);
10203 if (!ti || arg_depth > TMPL_ARGS_DEPTH (TI_ARGS (ti)))
10204 break;
10206 if (gen_tmpl == most_general_template (TI_TEMPLATE (ti))
10207 && comp_template_args (arglist, TI_ARGS (ti)))
10208 return cur;
10211 /* Calculate the BOUND_ARGS. These will be the args that are
10212 actually tsubst'd into the definition to create the
10213 instantiation. */
10214 if (PRIMARY_TEMPLATE_P (gen_tmpl))
10215 arglist = coerce_template_parms (parmlist, arglist, gen_tmpl, complain);
10217 if (arglist == error_mark_node)
10218 /* We were unable to bind the arguments. */
10219 return error_mark_node;
10221 /* In the scope of a template class, explicit references to the
10222 template class refer to the type of the template, not any
10223 instantiation of it. For example, in:
10225 template <class T> class C { void f(C<T>); }
10227 the `C<T>' is just the same as `C'. Outside of the
10228 class, however, such a reference is an instantiation.
10229 One can use adjust_type_for_entering_scope to make
10230 this adjustment as needed. */
10231 if (!PRIMARY_TEMPLATE_P (gen_tmpl)
10232 || currently_open_class (template_type))
10234 tree tinfo = TYPE_TEMPLATE_INFO (template_type);
10236 if (tinfo && comp_template_args (TI_ARGS (tinfo), arglist))
10237 return template_type;
10240 /* If we already have this specialization, return it. */
10241 spec_entry elt;
10242 elt.tmpl = gen_tmpl;
10243 elt.args = arglist;
10244 entry = type_specializations->find (&elt);
10246 if (entry)
10247 return entry->spec;
10249 /* If the template's constraints are not satisfied,
10250 then we cannot form a valid type.
10252 Note that the check is deferred until after the hash
10253 lookup. This prevents redundant checks on previously
10254 instantiated specializations. */
10255 if (flag_concepts
10256 && !constraints_satisfied_p (gen_tmpl, arglist))
10258 if (complain & tf_error)
10260 auto_diagnostic_group d;
10261 error ("template constraint failure for %qD", gen_tmpl);
10262 diagnose_constraints (input_location, gen_tmpl, arglist);
10264 return error_mark_node;
10267 is_dependent_type = uses_template_parms (arglist);
10269 /* If the deduced arguments are invalid, then the binding
10270 failed. */
10271 if (!is_dependent_type
10272 && check_instantiated_args (gen_tmpl,
10273 INNERMOST_TEMPLATE_ARGS (arglist),
10274 complain))
10275 return error_mark_node;
10277 if (!is_dependent_type
10278 && !PRIMARY_TEMPLATE_P (gen_tmpl)
10279 && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
10280 && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
10281 /* This occurs when the user has tried to define a tagged type
10282 in a scope that forbids it. We emitted an error during the
10283 parse. We didn't complete the bail out then, so here we
10284 are. */
10285 return error_mark_node;
10287 context = DECL_CONTEXT (gen_tmpl);
10288 if (context && TYPE_P (context))
10290 if (!uses_template_parms (DECL_CONTEXT (templ)))
10291 /* If the context of the partially instantiated template is
10292 already non-dependent, then we might as well use it. */
10293 context = DECL_CONTEXT (templ);
10294 else
10296 context = tsubst_entering_scope (context, arglist,
10297 complain, in_decl);
10298 /* Try completing the enclosing context if it's not already so. */
10299 if (context != error_mark_node
10300 && !COMPLETE_TYPE_P (context))
10302 context = complete_type (context);
10303 if (COMPLETE_TYPE_P (context))
10305 /* Completion could have caused us to register the desired
10306 specialization already, so check the table again. */
10307 entry = type_specializations->find (&elt);
10308 if (entry)
10309 return entry->spec;
10314 else
10315 context = tsubst (context, arglist, complain, in_decl);
10317 if (context == error_mark_node)
10318 return error_mark_node;
10320 if (!context)
10321 context = global_namespace;
10323 /* Create the type. */
10324 if (TREE_CODE (template_type) == ENUMERAL_TYPE)
10326 if (!is_dependent_type)
10328 set_current_access_from_decl (TYPE_NAME (template_type));
10329 t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
10330 tsubst (ENUM_UNDERLYING_TYPE (template_type),
10331 arglist, complain, in_decl),
10332 tsubst_attributes (TYPE_ATTRIBUTES (template_type),
10333 arglist, complain, in_decl),
10334 SCOPED_ENUM_P (template_type), NULL);
10336 if (t == error_mark_node)
10337 return t;
10339 else
10341 /* We don't want to call start_enum for this type, since
10342 the values for the enumeration constants may involve
10343 template parameters. And, no one should be interested
10344 in the enumeration constants for such a type. */
10345 t = cxx_make_type (ENUMERAL_TYPE);
10346 SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
10348 SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
10349 ENUM_FIXED_UNDERLYING_TYPE_P (t)
10350 = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
10352 else if (CLASS_TYPE_P (template_type))
10354 /* Lambda closures are regenerated in tsubst_lambda_expr, not
10355 instantiated here. */
10356 gcc_assert (!LAMBDA_TYPE_P (template_type));
10358 t = make_class_type (TREE_CODE (template_type));
10359 CLASSTYPE_DECLARED_CLASS (t)
10360 = CLASSTYPE_DECLARED_CLASS (template_type);
10361 SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
10363 /* A local class. Make sure the decl gets registered properly. */
10364 if (context == current_function_decl)
10365 if (pushtag (DECL_NAME (gen_tmpl), t)
10366 == error_mark_node)
10367 return error_mark_node;
10369 if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
10370 /* This instantiation is another name for the primary
10371 template type. Set the TYPE_CANONICAL field
10372 appropriately. */
10373 TYPE_CANONICAL (t) = template_type;
10374 else if (any_template_arguments_need_structural_equality_p (arglist))
10375 SET_TYPE_STRUCTURAL_EQUALITY (t);
10377 else
10378 gcc_unreachable ();
10380 /* If we called start_enum or pushtag above, this information
10381 will already be set up. */
10382 type_decl = TYPE_NAME (t);
10383 if (!type_decl)
10385 TYPE_CONTEXT (t) = FROB_CONTEXT (context);
10387 type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
10388 DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
10389 DECL_SOURCE_LOCATION (type_decl)
10390 = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
10393 set_instantiating_module (type_decl);
10394 /* Although GEN_TMPL is the TEMPLATE_DECL, it has the same value
10395 of export flag. We want to propagate this because it might
10396 be a friend declaration that pushes a new hidden binding. */
10397 DECL_MODULE_EXPORT_P (type_decl) = DECL_MODULE_EXPORT_P (gen_tmpl);
10399 if (CLASS_TYPE_P (template_type))
10401 TREE_PRIVATE (type_decl)
10402 = TREE_PRIVATE (TYPE_MAIN_DECL (template_type));
10403 TREE_PROTECTED (type_decl)
10404 = TREE_PROTECTED (TYPE_MAIN_DECL (template_type));
10405 if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
10407 DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
10408 DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
10412 if (OVERLOAD_TYPE_P (t))
10414 static const char *tags[] = {"abi_tag", "may_alias"};
10416 for (unsigned ix = 0; ix != 2; ix++)
10418 tree attributes
10419 = lookup_attribute (tags[ix], TYPE_ATTRIBUTES (template_type));
10421 if (attributes)
10422 TYPE_ATTRIBUTES (t)
10423 = tree_cons (TREE_PURPOSE (attributes),
10424 TREE_VALUE (attributes),
10425 TYPE_ATTRIBUTES (t));
10429 /* Let's consider the explicit specialization of a member
10430 of a class template specialization that is implicitly instantiated,
10431 e.g.:
10432 template<class T>
10433 struct S
10435 template<class U> struct M {}; //#0
10438 template<>
10439 template<>
10440 struct S<int>::M<char> //#1
10442 int i;
10444 [temp.expl.spec]/4 says this is valid.
10446 In this case, when we write:
10447 S<int>::M<char> m;
10449 M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
10450 the one of #0.
10452 When we encounter #1, we want to store the partial instantiation
10453 of M (template<class T> S<int>::M<T>) in its CLASSTYPE_TI_TEMPLATE.
10455 For all cases other than this "explicit specialization of member of a
10456 class template", we just want to store the most general template into
10457 the CLASSTYPE_TI_TEMPLATE of M.
10459 This case of "explicit specialization of member of a class template"
10460 only happens when:
10461 1/ the enclosing class is an instantiation of, and therefore not
10462 the same as, the context of the most general template, and
10463 2/ we aren't looking at the partial instantiation itself, i.e.
10464 the innermost arguments are not the same as the innermost parms of
10465 the most general template.
10467 So it's only when 1/ and 2/ happens that we want to use the partial
10468 instantiation of the member template in lieu of its most general
10469 template. */
10471 if (PRIMARY_TEMPLATE_P (gen_tmpl)
10472 && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
10473 /* the enclosing class must be an instantiation... */
10474 && CLASS_TYPE_P (context)
10475 && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
10477 TREE_VEC_LENGTH (arglist)--;
10478 ++processing_template_decl;
10479 tree tinfo = TYPE_TEMPLATE_INFO (TREE_TYPE (gen_tmpl));
10480 tree partial_inst_args =
10481 tsubst (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)),
10482 arglist, complain, NULL_TREE);
10483 --processing_template_decl;
10484 TREE_VEC_LENGTH (arglist)++;
10485 if (partial_inst_args == error_mark_node)
10486 return error_mark_node;
10487 use_partial_inst_tmpl =
10488 /*...and we must not be looking at the partial instantiation
10489 itself. */
10490 !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
10491 partial_inst_args);
10494 if (!use_partial_inst_tmpl)
10495 /* This case is easy; there are no member templates involved. */
10496 found = gen_tmpl;
10497 else
10499 /* This is a full instantiation of a member template. Find
10500 the partial instantiation of which this is an instance. */
10502 /* Temporarily reduce by one the number of levels in the ARGLIST
10503 so as to avoid comparing the last set of arguments. */
10504 TREE_VEC_LENGTH (arglist)--;
10505 /* We don't use COMPLAIN in the following call because this isn't
10506 the immediate context of deduction. For instance, tf_partial
10507 could be set here as we might be at the beginning of template
10508 argument deduction when any explicitly specified template
10509 arguments are substituted into the function type. tf_partial
10510 could lead into trouble because we wouldn't find the partial
10511 instantiation that might have been created outside tf_partial
10512 context, because the levels of template parameters wouldn't
10513 match, because in a tf_partial context, tsubst doesn't reduce
10514 TEMPLATE_PARM_LEVEL. */
10515 found = tsubst (gen_tmpl, arglist, tf_none, NULL_TREE);
10516 TREE_VEC_LENGTH (arglist)++;
10517 found = (TREE_CODE (found) == TEMPLATE_DECL
10518 ? found
10519 : CLASSTYPE_TI_TEMPLATE (found));
10521 if (DECL_CLASS_TEMPLATE_P (found)
10522 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (found)))
10524 /* If this partial instantiation is specialized, we want to
10525 use it for hash table lookup. */
10526 elt.tmpl = found;
10527 elt.args = arglist = INNERMOST_TEMPLATE_ARGS (arglist);
10528 elt.hash = 0; /* Recalculate after changing tmpl/args. */
10532 /* Build template info for the new specialization. */
10533 SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
10535 elt.spec = t;
10536 slot = type_specializations->find_slot (&elt, INSERT);
10537 gcc_checking_assert (*slot == NULL);
10538 entry = ggc_alloc<spec_entry> ();
10539 *entry = elt;
10540 *slot = entry;
10542 /* Note this use of the partial instantiation so we can check it
10543 later in maybe_process_partial_specialization. */
10544 DECL_TEMPLATE_INSTANTIATIONS (found)
10545 = tree_cons (arglist, t,
10546 DECL_TEMPLATE_INSTANTIATIONS (found));
10548 if (TREE_CODE (template_type) == ENUMERAL_TYPE
10549 && !uses_template_parms (current_nonlambda_scope ()))
10550 /* Now that the type has been registered on the instantiations
10551 list, we set up the enumerators. Because the enumeration
10552 constants may involve the enumeration type itself, we make
10553 sure to register the type first, and then create the
10554 constants. That way, doing tsubst_expr for the enumeration
10555 constants won't result in recursive calls here; we'll find
10556 the instantiation and exit above. */
10557 tsubst_enum (template_type, t, arglist);
10559 if (CLASS_TYPE_P (template_type) && is_dependent_type)
10560 /* If the type makes use of template parameters, the
10561 code that generates debugging information will crash. */
10562 DECL_IGNORED_P (TYPE_MAIN_DECL (t)) = 1;
10564 /* Possibly limit visibility based on template args. */
10565 TREE_PUBLIC (type_decl) = 1;
10566 determine_visibility (type_decl);
10568 inherit_targ_abi_tags (t);
10570 return t;
10574 /* Return a TEMPLATE_ID_EXPR for the given variable template and ARGLIST. */
10576 tree
10577 lookup_template_variable (tree templ, tree arglist, tsubst_flags_t complain)
10579 tree gen_templ = most_general_template (templ);
10580 tree parms = DECL_INNERMOST_TEMPLATE_PARMS (gen_templ);
10581 arglist = add_outermost_template_args (templ, arglist);
10582 arglist = coerce_template_parms (parms, arglist, templ, complain);
10583 if (arglist == error_mark_node)
10584 return error_mark_node;
10586 /* The type of the expression is NULL_TREE since the template-id could refer
10587 to an explicit or partial specialization. */
10588 return build2 (TEMPLATE_ID_EXPR, NULL_TREE, templ, arglist);
10591 /* Instantiate a variable declaration from a TEMPLATE_ID_EXPR if it's
10592 not dependent. */
10594 tree
10595 finish_template_variable (tree var, tsubst_flags_t complain)
10597 tree templ = TREE_OPERAND (var, 0);
10598 tree arglist = TREE_OPERAND (var, 1);
10600 /* If the template or arguments are dependent, then we
10601 can't resolve the TEMPLATE_ID_EXPR yet. */
10602 if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (templ)) != 1
10603 || any_dependent_template_arguments_p (arglist))
10604 return var;
10606 if (flag_concepts && !constraints_satisfied_p (templ, arglist))
10608 if (complain & tf_error)
10610 auto_diagnostic_group d;
10611 error ("use of invalid variable template %qE", var);
10612 diagnose_constraints (location_of (var), templ, arglist);
10614 return error_mark_node;
10617 return instantiate_template (templ, arglist, complain);
10620 /* Construct a TEMPLATE_ID_EXPR for the given variable template TEMPL having
10621 TARGS template args, and instantiate it if it's not dependent. */
10623 tree
10624 lookup_and_finish_template_variable (tree templ, tree targs,
10625 tsubst_flags_t complain)
10627 tree var = lookup_template_variable (templ, targs, complain);
10628 if (var == error_mark_node)
10629 return error_mark_node;
10630 var = finish_template_variable (var, complain);
10631 mark_used (var, complain);
10632 return var;
10635 /* If the set of template parameters PARMS contains a template parameter
10636 at the given LEVEL and INDEX, then return this parameter. Otherwise
10637 return NULL_TREE. */
10639 static tree
10640 corresponding_template_parameter_list (tree parms, int level, int index)
10642 while (TMPL_PARMS_DEPTH (parms) > level)
10643 parms = TREE_CHAIN (parms);
10645 if (TMPL_PARMS_DEPTH (parms) != level
10646 || TREE_VEC_LENGTH (TREE_VALUE (parms)) <= index)
10647 return NULL_TREE;
10649 return TREE_VEC_ELT (TREE_VALUE (parms), index);
10652 /* Return the TREE_LIST for the template parameter from PARMS that positionally
10653 corresponds to the template parameter PARM, or else return NULL_TREE. */
10655 static tree
10656 corresponding_template_parameter_list (tree parms, tree parm)
10658 int level, index;
10659 template_parm_level_and_index (parm, &level, &index);
10660 return corresponding_template_parameter_list (parms, level, index);
10663 /* As above, but pull out the actual parameter. */
10665 static tree
10666 corresponding_template_parameter (tree parms, tree parm)
10668 tree list = corresponding_template_parameter_list (parms, parm);
10669 if (!list)
10670 return NULL_TREE;
10672 tree t = TREE_VALUE (list);
10673 /* As in template_parm_to_arg. */
10674 if (TREE_CODE (t) == TYPE_DECL || TREE_CODE (t) == TEMPLATE_DECL)
10675 t = TREE_TYPE (t);
10676 else
10677 t = DECL_INITIAL (t);
10679 gcc_assert (TEMPLATE_PARM_P (t));
10680 return t;
10683 struct pair_fn_data
10685 tree_fn_t fn;
10686 tree_fn_t any_fn;
10687 void *data;
10688 /* True when we should also visit template parameters that occur in
10689 non-deduced contexts. */
10690 bool include_nondeduced_p;
10691 hash_set<tree> *visited;
10694 /* Called from for_each_template_parm via walk_tree. */
10696 static tree
10697 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
10699 tree t = *tp;
10700 struct pair_fn_data *pfd = (struct pair_fn_data *) d;
10701 tree_fn_t fn = pfd->fn;
10702 void *data = pfd->data;
10703 tree result = NULL_TREE;
10705 #define WALK_SUBTREE(NODE) \
10706 do \
10708 result = for_each_template_parm (NODE, fn, data, pfd->visited, \
10709 pfd->include_nondeduced_p, \
10710 pfd->any_fn); \
10711 if (result) goto out; \
10713 while (0)
10715 if (pfd->any_fn && (*pfd->any_fn)(t, data))
10716 return t;
10718 if (TYPE_P (t)
10719 && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE))
10720 WALK_SUBTREE (TYPE_CONTEXT (t));
10722 switch (TREE_CODE (t))
10724 case RECORD_TYPE:
10725 if (TYPE_PTRMEMFUNC_P (t))
10726 break;
10727 /* Fall through. */
10729 case UNION_TYPE:
10730 case ENUMERAL_TYPE:
10731 if (!TYPE_TEMPLATE_INFO (t))
10732 *walk_subtrees = 0;
10733 else
10734 WALK_SUBTREE (TYPE_TI_ARGS (t));
10735 break;
10737 case INTEGER_TYPE:
10738 WALK_SUBTREE (TYPE_MIN_VALUE (t));
10739 WALK_SUBTREE (TYPE_MAX_VALUE (t));
10740 break;
10742 case METHOD_TYPE:
10743 /* Since we're not going to walk subtrees, we have to do this
10744 explicitly here. */
10745 WALK_SUBTREE (TYPE_METHOD_BASETYPE (t));
10746 /* Fall through. */
10748 case FUNCTION_TYPE:
10749 /* Check the return type. */
10750 WALK_SUBTREE (TREE_TYPE (t));
10752 /* Check the parameter types. Since default arguments are not
10753 instantiated until they are needed, the TYPE_ARG_TYPES may
10754 contain expressions that involve template parameters. But,
10755 no-one should be looking at them yet. And, once they're
10756 instantiated, they don't contain template parameters, so
10757 there's no point in looking at them then, either. */
10759 tree parm;
10761 for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
10762 WALK_SUBTREE (TREE_VALUE (parm));
10764 /* Since we've already handled the TYPE_ARG_TYPES, we don't
10765 want walk_tree walking into them itself. */
10766 *walk_subtrees = 0;
10769 if (flag_noexcept_type)
10771 tree spec = TYPE_RAISES_EXCEPTIONS (t);
10772 if (spec)
10773 WALK_SUBTREE (TREE_PURPOSE (spec));
10775 break;
10777 case TYPEOF_TYPE:
10778 case DECLTYPE_TYPE:
10779 if (pfd->include_nondeduced_p
10780 && for_each_template_parm (TYPE_VALUES_RAW (t), fn, data,
10781 pfd->visited,
10782 pfd->include_nondeduced_p,
10783 pfd->any_fn))
10784 return error_mark_node;
10785 *walk_subtrees = false;
10786 break;
10788 case TRAIT_TYPE:
10789 if (pfd->include_nondeduced_p)
10791 WALK_SUBTREE (TRAIT_TYPE_TYPE1 (t));
10792 WALK_SUBTREE (TRAIT_TYPE_TYPE2 (t));
10794 *walk_subtrees = false;
10795 break;
10797 case FUNCTION_DECL:
10798 case VAR_DECL:
10799 if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10800 WALK_SUBTREE (DECL_TI_ARGS (t));
10801 break;
10803 case PARM_DECL:
10804 WALK_SUBTREE (TREE_TYPE (t));
10805 break;
10807 case CONST_DECL:
10808 if (DECL_TEMPLATE_PARM_P (t))
10809 WALK_SUBTREE (DECL_INITIAL (t));
10810 if (DECL_CONTEXT (t)
10811 && pfd->include_nondeduced_p)
10812 WALK_SUBTREE (DECL_CONTEXT (t));
10813 break;
10815 case BOUND_TEMPLATE_TEMPLATE_PARM:
10816 /* Record template parameters such as `T' inside `TT<T>'. */
10817 WALK_SUBTREE (TYPE_TI_ARGS (t));
10818 /* Fall through. */
10820 case TEMPLATE_TEMPLATE_PARM:
10821 case TEMPLATE_TYPE_PARM:
10822 case TEMPLATE_PARM_INDEX:
10823 if (fn && (*fn)(t, data))
10824 return t;
10825 else if (!fn)
10826 return t;
10827 break;
10829 case TEMPLATE_DECL:
10830 /* A template template parameter is encountered. */
10831 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10832 WALK_SUBTREE (TREE_TYPE (t));
10834 /* Already substituted template template parameter */
10835 *walk_subtrees = 0;
10836 break;
10838 case TYPENAME_TYPE:
10839 /* A template-id in a TYPENAME_TYPE might be a deduced context after
10840 partial instantiation. */
10841 WALK_SUBTREE (TYPENAME_TYPE_FULLNAME (t));
10842 *walk_subtrees = 0;
10843 break;
10845 case INDIRECT_REF:
10846 case COMPONENT_REF:
10847 /* If there's no type, then this thing must be some expression
10848 involving template parameters. */
10849 if (!fn && !TREE_TYPE (t))
10850 return error_mark_node;
10851 break;
10853 case CONSTRUCTOR:
10854 case TRAIT_EXPR:
10855 case PLUS_EXPR:
10856 case MULT_EXPR:
10857 case SCOPE_REF:
10858 /* These are non-deduced contexts. */
10859 if (!pfd->include_nondeduced_p)
10860 *walk_subtrees = 0;
10861 break;
10863 case MODOP_EXPR:
10864 case CAST_EXPR:
10865 case IMPLICIT_CONV_EXPR:
10866 case REINTERPRET_CAST_EXPR:
10867 case CONST_CAST_EXPR:
10868 case STATIC_CAST_EXPR:
10869 case DYNAMIC_CAST_EXPR:
10870 case ARROW_EXPR:
10871 case DOTSTAR_EXPR:
10872 case TYPEID_EXPR:
10873 case PSEUDO_DTOR_EXPR:
10874 if (!fn)
10875 return error_mark_node;
10876 break;
10878 default:
10879 break;
10882 #undef WALK_SUBTREE
10884 /* We didn't find any template parameters we liked. */
10885 out:
10886 return result;
10889 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
10890 BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
10891 call FN with the parameter and the DATA.
10892 If FN returns nonzero, the iteration is terminated, and
10893 for_each_template_parm returns 1. Otherwise, the iteration
10894 continues. If FN never returns a nonzero value, the value
10895 returned by for_each_template_parm is 0. If FN is NULL, it is
10896 considered to be the function which always returns 1.
10898 If INCLUDE_NONDEDUCED_P, then this routine will also visit template
10899 parameters that occur in non-deduced contexts. When false, only
10900 visits those template parameters that can be deduced. */
10902 static tree
10903 for_each_template_parm (tree t, tree_fn_t fn, void* data,
10904 hash_set<tree> *visited,
10905 bool include_nondeduced_p,
10906 tree_fn_t any_fn)
10908 struct pair_fn_data pfd;
10909 tree result;
10911 /* Set up. */
10912 pfd.fn = fn;
10913 pfd.any_fn = any_fn;
10914 pfd.data = data;
10915 pfd.include_nondeduced_p = include_nondeduced_p;
10917 /* Walk the tree. (Conceptually, we would like to walk without
10918 duplicates, but for_each_template_parm_r recursively calls
10919 for_each_template_parm, so we would need to reorganize a fair
10920 bit to use walk_tree_without_duplicates, so we keep our own
10921 visited list.) */
10922 if (visited)
10923 pfd.visited = visited;
10924 else
10925 pfd.visited = new hash_set<tree>;
10926 result = cp_walk_tree (&t,
10927 for_each_template_parm_r,
10928 &pfd,
10929 pfd.visited);
10931 /* Clean up. */
10932 if (!visited)
10934 delete pfd.visited;
10935 pfd.visited = 0;
10938 return result;
10941 struct find_template_parameter_info
10943 explicit find_template_parameter_info (tree ctx_parms)
10944 : ctx_parms (ctx_parms),
10945 max_depth (TMPL_PARMS_DEPTH (ctx_parms))
10948 hash_set<tree> visited;
10949 hash_set<tree> parms;
10950 tree parm_list = NULL_TREE;
10951 tree *parm_list_tail = &parm_list;
10952 tree ctx_parms;
10953 int max_depth;
10955 tree find_in (tree);
10956 tree find_in_recursive (tree);
10957 bool found (tree);
10958 unsigned num_found () { return parms.elements (); }
10961 /* Appends the declaration of T to the list in DATA. */
10963 static int
10964 keep_template_parm (tree t, void* data)
10966 find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
10968 /* Template parameters declared within the expression are not part of
10969 the parameter mapping. For example, in this concept:
10971 template<typename T>
10972 concept C = requires { <expr> } -> same_as<int>;
10974 the return specifier same_as<int> declares a new decltype parameter
10975 that must not be part of the parameter mapping. The same is true
10976 for generic lambda parameters, lambda template parameters, etc. */
10977 int level;
10978 int index;
10979 template_parm_level_and_index (t, &level, &index);
10980 if (level == 0 || level > ftpi->max_depth)
10981 return 0;
10983 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
10984 /* We want the underlying TEMPLATE_TEMPLATE_PARM, not the
10985 BOUND_TEMPLATE_TEMPLATE_PARM itself. */
10986 t = TREE_TYPE (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (t));
10988 /* This template parameter might be an argument to a cached dependent
10989 specalization that was formed earlier inside some other template, in
10990 which case the parameter is not among the ones that are in-scope.
10991 Look in CTX_PARMS to find the corresponding in-scope template
10992 parameter, and use it instead. */
10993 if (tree in_scope = corresponding_template_parameter (ftpi->ctx_parms, t))
10994 t = in_scope;
10996 /* Arguments like const T yield parameters like const T. This means that
10997 a template-id like X<T, const T> would yield two distinct parameters:
10998 T and const T. Adjust types to their unqualified versions. */
10999 if (TYPE_P (t))
11000 t = TYPE_MAIN_VARIANT (t);
11001 if (!ftpi->parms.add (t))
11003 /* Append T to PARM_LIST. */
11004 tree node = build_tree_list (NULL_TREE, t);
11005 *ftpi->parm_list_tail = node;
11006 ftpi->parm_list_tail = &TREE_CHAIN (node);
11009 /* Verify the parameter we found has a valid index. */
11010 if (flag_checking)
11012 tree parms = ftpi->ctx_parms;
11013 while (TMPL_PARMS_DEPTH (parms) > level)
11014 parms = TREE_CHAIN (parms);
11015 if (int len = TREE_VEC_LENGTH (TREE_VALUE (parms)))
11016 gcc_assert (index < len);
11019 return 0;
11022 /* Ensure that we recursively examine certain terms that are not normally
11023 visited in for_each_template_parm_r. */
11025 static int
11026 any_template_parm_r (tree t, void *data)
11028 find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
11030 #define WALK_SUBTREE(NODE) \
11031 do \
11033 for_each_template_parm (NODE, keep_template_parm, data, \
11034 &ftpi->visited, true, \
11035 any_template_parm_r); \
11037 while (0)
11039 /* A mention of a member alias/typedef is a use of all of its template
11040 arguments, including those from the enclosing class, so we don't use
11041 alias_template_specialization_p here. */
11042 if (TYPE_P (t) && typedef_variant_p (t))
11043 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
11044 WALK_SUBTREE (TI_ARGS (tinfo));
11046 switch (TREE_CODE (t))
11048 case TEMPLATE_TYPE_PARM:
11049 /* Type constraints of a placeholder type may contain parameters. */
11050 if (is_auto (t))
11051 if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (t))
11052 WALK_SUBTREE (constr);
11053 break;
11055 case TEMPLATE_ID_EXPR:
11056 /* Search through references to variable templates. */
11057 WALK_SUBTREE (TREE_OPERAND (t, 0));
11058 WALK_SUBTREE (TREE_OPERAND (t, 1));
11059 break;
11061 case TEMPLATE_PARM_INDEX:
11062 WALK_SUBTREE (TREE_TYPE (t));
11063 break;
11065 case TEMPLATE_DECL:
11066 /* If T is a member template that shares template parameters with
11067 ctx_parms, we need to mark all those parameters for mapping.
11068 To that end, it should suffice to just walk the DECL_CONTEXT of
11069 the template (assuming the template is not overly general). */
11070 WALK_SUBTREE (DECL_CONTEXT (t));
11071 break;
11073 case LAMBDA_EXPR:
11075 /* Look in the parms and body. */
11076 tree fn = lambda_function (t);
11077 WALK_SUBTREE (TREE_TYPE (fn));
11078 WALK_SUBTREE (DECL_SAVED_TREE (fn));
11080 break;
11082 case IDENTIFIER_NODE:
11083 if (IDENTIFIER_CONV_OP_P (t))
11084 /* The conversion-type-id of a conversion operator may be dependent. */
11085 WALK_SUBTREE (TREE_TYPE (t));
11086 break;
11088 case CONVERT_EXPR:
11089 if (is_dummy_object (t))
11090 WALK_SUBTREE (TREE_TYPE (t));
11091 break;
11093 default:
11094 break;
11097 /* Keep walking. */
11098 return 0;
11101 /* Look through T for template parameters. */
11103 tree
11104 find_template_parameter_info::find_in (tree t)
11106 return for_each_template_parm (t, keep_template_parm, this, &visited,
11107 /*include_nondeduced*/true,
11108 any_template_parm_r);
11111 /* As above, but also recursively look into the default arguments of template
11112 parameters we found. Used for alias CTAD. */
11114 tree
11115 find_template_parameter_info::find_in_recursive (tree t)
11117 if (tree r = find_in (t))
11118 return r;
11119 /* Since newly found parms are added to the end of the list, we
11120 can just walk it until we reach the end. */
11121 for (tree pl = parm_list; pl; pl = TREE_CHAIN (pl))
11123 tree parm = TREE_VALUE (pl);
11124 tree list = corresponding_template_parameter_list (ctx_parms, parm);
11125 if (tree r = find_in (TREE_PURPOSE (list)))
11126 return r;
11128 return NULL_TREE;
11131 /* True if PARM was found by a previous call to find_in. PARM can be a
11132 TREE_LIST, a DECL_TEMPLATE_PARM_P, or a TEMPLATE_PARM_P. */
11134 bool
11135 find_template_parameter_info::found (tree parm)
11137 if (TREE_CODE (parm) == TREE_LIST)
11138 parm = TREE_VALUE (parm);
11139 if (TREE_CODE (parm) == TYPE_DECL
11140 || TREE_CODE (parm) == TEMPLATE_DECL)
11141 parm = TREE_TYPE (parm);
11142 else
11143 parm = DECL_INITIAL (parm);
11144 gcc_checking_assert (TEMPLATE_PARM_P (parm));
11145 return parms.contains (parm);
11148 /* Returns a list of unique template parameters found within T, where CTX_PARMS
11149 are the template parameters in scope. */
11151 tree
11152 find_template_parameters (tree t, tree ctx_parms)
11154 if (!ctx_parms)
11155 return NULL_TREE;
11157 find_template_parameter_info ftpi (ctx_parms);
11158 ftpi.find_in (t);
11159 return ftpi.parm_list;
11162 /* Returns true if T depends on any template parameter. */
11164 bool
11165 uses_template_parms (tree t)
11167 if (t == NULL_TREE || t == error_mark_node)
11168 return false;
11170 /* Namespaces can't depend on any template parameters. */
11171 if (TREE_CODE (t) == NAMESPACE_DECL)
11172 return false;
11174 processing_template_decl_sentinel ptds (/*reset*/false);
11175 ++processing_template_decl;
11177 if (TYPE_P (t))
11178 return dependent_type_p (t);
11179 else if (TREE_CODE (t) == TREE_VEC)
11180 return any_dependent_template_arguments_p (t);
11181 else if (TREE_CODE (t) == TREE_LIST)
11182 return (uses_template_parms (TREE_VALUE (t))
11183 || uses_template_parms (TREE_CHAIN (t)));
11184 else if (TREE_CODE (t) == TYPE_DECL)
11185 return dependent_type_p (TREE_TYPE (t));
11186 else
11187 return instantiation_dependent_expression_p (t);
11190 /* Returns true if T depends on any template parameter with level LEVEL. */
11192 bool
11193 uses_template_parms_level (tree t, int level)
11195 return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
11196 /*include_nondeduced_p=*/true);
11199 /* Returns true if the signature of DECL depends on any template parameter from
11200 its enclosing class. */
11202 static bool
11203 uses_outer_template_parms (tree decl)
11205 int depth;
11206 if (DECL_TEMPLATE_TEMPLATE_PARM_P (decl))
11207 depth = TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl)) - 1;
11208 else
11209 depth = template_class_depth (CP_DECL_CONTEXT (decl));
11210 if (depth == 0)
11211 return false;
11212 if (for_each_template_parm (TREE_TYPE (decl), template_parm_outer_level,
11213 &depth, NULL, /*include_nondeduced_p=*/true))
11214 return true;
11215 if (PRIMARY_TEMPLATE_P (decl)
11216 || DECL_TEMPLATE_TEMPLATE_PARM_P (decl))
11218 tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (decl));
11219 for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
11221 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
11222 tree defarg = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
11223 if (TREE_CODE (parm) == PARM_DECL
11224 && for_each_template_parm (TREE_TYPE (parm),
11225 template_parm_outer_level,
11226 &depth, NULL, /*nondeduced*/true))
11227 return true;
11228 if (TREE_CODE (parm) == TEMPLATE_DECL
11229 && uses_outer_template_parms (parm))
11230 return true;
11231 if (defarg
11232 && for_each_template_parm (defarg, template_parm_outer_level,
11233 &depth, NULL, /*nondeduced*/true))
11234 return true;
11237 if (uses_outer_template_parms_in_constraints (decl))
11238 return true;
11239 return false;
11242 /* Returns true if the constraints of DECL depend on any template parameters
11243 from its enclosing scope. */
11245 bool
11246 uses_outer_template_parms_in_constraints (tree decl, tree ctx/*=NULL_TREE*/)
11248 tree ci = get_constraints (decl);
11249 if (ci)
11250 ci = CI_ASSOCIATED_CONSTRAINTS (ci);
11251 if (!ci)
11252 return false;
11253 if (!ctx)
11255 if (tree fc = DECL_FRIEND_CONTEXT (decl))
11256 ctx = fc;
11257 else
11258 ctx = CP_DECL_CONTEXT (decl);
11260 int depth = template_class_depth (ctx);
11261 if (depth == 0)
11262 return false;
11263 return for_each_template_parm (ci, template_parm_outer_level,
11264 &depth, NULL, /*nondeduced*/true);
11267 /* Returns TRUE iff INST is an instantiation we don't need to do in an
11268 ill-formed translation unit, i.e. a variable or function that isn't
11269 usable in a constant expression. */
11271 static inline bool
11272 neglectable_inst_p (tree d)
11274 return (d && DECL_P (d)
11275 && !undeduced_auto_decl (d)
11276 && !(TREE_CODE (d) == FUNCTION_DECL
11277 ? FNDECL_MANIFESTLY_CONST_EVALUATED (d)
11278 : decl_maybe_constant_var_p (d)));
11281 /* Returns TRUE iff we should refuse to instantiate DECL because it's
11282 neglectable and instantiated from within an erroneous instantiation. */
11284 static bool
11285 limit_bad_template_recursion (tree decl)
11287 struct tinst_level *lev = current_tinst_level;
11288 int errs = errorcount + sorrycount;
11289 if (errs == 0 || !neglectable_inst_p (decl))
11290 return false;
11292 /* Avoid instantiating members of an ill-formed class. */
11293 bool refuse
11294 = (DECL_CLASS_SCOPE_P (decl)
11295 && CLASSTYPE_ERRONEOUS (DECL_CONTEXT (decl)));
11297 if (!refuse)
11299 for (; lev; lev = lev->next)
11300 if (neglectable_inst_p (lev->maybe_get_node ()))
11301 break;
11302 refuse = (lev && errs > lev->errors);
11305 if (refuse)
11307 /* Don't warn about it not being defined. */
11308 suppress_warning (decl, OPT_Wunused);
11309 tree clone;
11310 FOR_EACH_CLONE (clone, decl)
11311 suppress_warning (clone, OPT_Wunused);
11313 return refuse;
11316 static int tinst_depth;
11317 extern int max_tinst_depth;
11318 int depth_reached;
11320 static GTY(()) struct tinst_level *last_error_tinst_level;
11322 /* We're starting to instantiate D; record the template instantiation context
11323 at LOC for diagnostics and to restore it later. */
11325 bool
11326 push_tinst_level_loc (tree tldcl, tree targs, location_t loc)
11328 struct tinst_level *new_level;
11330 if (tinst_depth >= max_tinst_depth)
11332 /* Tell error.cc not to try to instantiate any templates. */
11333 at_eof = 3;
11334 fatal_error (input_location,
11335 "template instantiation depth exceeds maximum of %d"
11336 " (use %<-ftemplate-depth=%> to increase the maximum)",
11337 max_tinst_depth);
11338 return false;
11341 /* If the current instantiation caused problems, don't let it instantiate
11342 anything else. Do allow deduction substitution and decls usable in
11343 constant expressions. */
11344 if (!targs && limit_bad_template_recursion (tldcl))
11346 /* Avoid no_linkage_errors and unused function (and all other)
11347 warnings for this decl. */
11348 suppress_warning (tldcl);
11349 return false;
11352 /* When not -quiet, dump template instantiations other than functions, since
11353 announce_function will take care of those. */
11354 if (!quiet_flag && !targs
11355 && TREE_CODE (tldcl) != TREE_LIST
11356 && TREE_CODE (tldcl) != FUNCTION_DECL)
11357 fprintf (stderr, " %s", decl_as_string (tldcl, TFF_DECL_SPECIFIERS));
11359 new_level = tinst_level_freelist ().alloc ();
11360 new_level->tldcl = tldcl;
11361 new_level->targs = targs;
11362 new_level->locus = loc;
11363 new_level->errors = errorcount + sorrycount;
11364 new_level->next = NULL;
11365 new_level->refcount = 0;
11366 new_level->path = new_level->visible = nullptr;
11367 set_refcount_ptr (new_level->next, current_tinst_level);
11368 set_refcount_ptr (current_tinst_level, new_level);
11370 ++tinst_depth;
11371 if (GATHER_STATISTICS && (tinst_depth > depth_reached))
11372 depth_reached = tinst_depth;
11374 return true;
11377 /* We're starting substitution of TMPL<ARGS>; record the template
11378 substitution context for diagnostics and to restore it later. */
11380 bool
11381 push_tinst_level (tree tmpl, tree args)
11383 return push_tinst_level_loc (tmpl, args, input_location);
11386 /* We're starting to instantiate D; record INPUT_LOCATION and the
11387 template instantiation context for diagnostics and to restore it
11388 later. */
11390 bool
11391 push_tinst_level (tree d)
11393 return push_tinst_level_loc (d, input_location);
11396 /* Likewise, but record LOC as the program location. */
11398 bool
11399 push_tinst_level_loc (tree d, location_t loc)
11401 gcc_assert (TREE_CODE (d) != TREE_LIST);
11402 return push_tinst_level_loc (d, NULL, loc);
11405 /* We're done instantiating this template; return to the instantiation
11406 context. */
11408 void
11409 pop_tinst_level (void)
11411 /* Restore the filename and line number stashed away when we started
11412 this instantiation. */
11413 input_location = current_tinst_level->locus;
11414 set_refcount_ptr (current_tinst_level, current_tinst_level->next);
11415 --tinst_depth;
11418 /* We're instantiating a deferred template; restore the template
11419 instantiation context in which the instantiation was requested, which
11420 is one step out from LEVEL. Return the corresponding DECL or TYPE. */
11422 static tree
11423 reopen_tinst_level (struct tinst_level *level)
11425 struct tinst_level *t;
11427 tinst_depth = 0;
11428 for (t = level; t; t = t->next)
11429 ++tinst_depth;
11431 set_refcount_ptr (current_tinst_level, level);
11432 pop_tinst_level ();
11433 if (current_tinst_level)
11434 current_tinst_level->errors = errorcount+sorrycount;
11435 return level->maybe_get_node ();
11438 /* Returns the TINST_LEVEL which gives the original instantiation
11439 context. */
11441 struct tinst_level *
11442 outermost_tinst_level (void)
11444 struct tinst_level *level = current_tinst_level;
11445 if (level)
11446 while (level->next)
11447 level = level->next;
11448 return level;
11451 /* True iff T is a friend function declaration that is not itself a template
11452 and is not defined in a class template. */
11454 bool
11455 non_templated_friend_p (tree t)
11457 if (t && TREE_CODE (t) == FUNCTION_DECL
11458 && DECL_UNIQUE_FRIEND_P (t))
11460 tree ti = DECL_TEMPLATE_INFO (t);
11461 if (!ti)
11462 return true;
11463 /* DECL_FRIEND_CONTEXT is set for a friend defined in class. */
11464 if (DECL_FRIEND_CONTEXT (t))
11465 return false;
11466 /* Non-templated friends in a class template are still represented with a
11467 TEMPLATE_DECL; check that its primary template is the befriending
11468 class. Note that DECL_PRIMARY_TEMPLATE is null for
11469 template <class T> friend A<T>::f(); */
11470 tree tmpl = TI_TEMPLATE (ti);
11471 tree primary = DECL_PRIMARY_TEMPLATE (tmpl);
11472 return (primary && primary != tmpl);
11474 else
11475 return false;
11478 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL. ARGS is the
11479 vector of template arguments, as for tsubst.
11481 Returns an appropriate tsubst'd friend declaration. */
11483 static tree
11484 tsubst_friend_function (tree decl, tree args)
11486 tree new_friend;
11488 if (TREE_CODE (decl) == FUNCTION_DECL
11489 && DECL_TEMPLATE_INSTANTIATION (decl)
11490 && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
11491 /* This was a friend declared with an explicit template
11492 argument list, e.g.:
11494 friend void f<>(T);
11496 to indicate that f was a template instantiation, not a new
11497 function declaration. Now, we have to figure out what
11498 instantiation of what template. */
11500 tree template_id, arglist, fns;
11501 tree new_args;
11502 tree tmpl;
11503 tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
11505 /* Friend functions are looked up in the containing namespace scope.
11506 We must enter that scope, to avoid finding member functions of the
11507 current class with same name. */
11508 push_nested_namespace (ns);
11509 fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
11510 tf_warning_or_error, NULL_TREE);
11511 pop_nested_namespace (ns);
11512 arglist = tsubst (DECL_TI_ARGS (decl), args,
11513 tf_warning_or_error, NULL_TREE);
11514 template_id = lookup_template_function (fns, arglist);
11516 new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
11517 tmpl = determine_specialization (template_id, new_friend,
11518 &new_args,
11519 /*need_member_template=*/0,
11520 TREE_VEC_LENGTH (args),
11521 tsk_none);
11522 return instantiate_template (tmpl, new_args, tf_error);
11525 new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
11526 if (new_friend == error_mark_node)
11527 return error_mark_node;
11529 /* The NEW_FRIEND will look like an instantiation, to the
11530 compiler, but is not an instantiation from the point of view of
11531 the language. For example, we might have had:
11533 template <class T> struct S {
11534 template <class U> friend void f(T, U);
11537 Then, in S<int>, template <class U> void f(int, U) is not an
11538 instantiation of anything. */
11540 DECL_USE_TEMPLATE (new_friend) = 0;
11541 if (TREE_CODE (new_friend) == TEMPLATE_DECL)
11543 DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (new_friend) = false;
11544 DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
11545 DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
11546 = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
11548 /* Substitute TEMPLATE_PARMS_CONSTRAINTS so that parameter levels will
11549 match in decls_match. */
11550 tree parms = DECL_TEMPLATE_PARMS (new_friend);
11551 tree treqs = TEMPLATE_PARMS_CONSTRAINTS (parms);
11552 treqs = maybe_substitute_reqs_for (treqs, new_friend);
11553 if (treqs != TEMPLATE_PARMS_CONSTRAINTS (parms))
11555 TEMPLATE_PARMS_CONSTRAINTS (parms) = treqs;
11556 /* As well as each TEMPLATE_PARM_CONSTRAINTS. */
11557 tsubst_each_template_parm_constraints (parms, args,
11558 tf_warning_or_error);
11562 /* The mangled name for the NEW_FRIEND is incorrect. The function
11563 is not a template instantiation and should not be mangled like
11564 one. Therefore, we forget the mangling here; we'll recompute it
11565 later if we need it. */
11566 if (TREE_CODE (new_friend) != TEMPLATE_DECL)
11568 SET_DECL_RTL (new_friend, NULL);
11569 SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
11572 if (DECL_NAMESPACE_SCOPE_P (new_friend))
11574 tree old_decl;
11575 tree ns;
11577 /* We must save some information from NEW_FRIEND before calling
11578 duplicate decls since that function will free NEW_FRIEND if
11579 possible. */
11580 tree new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
11581 tree new_friend_result_template_info = NULL_TREE;
11582 bool new_friend_is_defn =
11583 (new_friend_template_info
11584 && (DECL_INITIAL (DECL_TEMPLATE_RESULT
11585 (template_for_substitution (new_friend)))
11586 != NULL_TREE));
11587 tree not_tmpl = new_friend;
11589 if (TREE_CODE (new_friend) == TEMPLATE_DECL)
11591 /* This declaration is a `primary' template. */
11592 DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
11594 not_tmpl = DECL_TEMPLATE_RESULT (new_friend);
11595 new_friend_result_template_info = DECL_TEMPLATE_INFO (not_tmpl);
11598 /* We need to propagate module attachment for the new friend from the
11599 owner of this template. */
11600 propagate_defining_module (new_friend, decl);
11602 /* Inside pushdecl_namespace_level, we will push into the
11603 current namespace. However, the friend function should go
11604 into the namespace of the template. */
11605 ns = decl_namespace_context (new_friend);
11606 push_nested_namespace (ns);
11607 old_decl = pushdecl_namespace_level (new_friend, /*hiding=*/true);
11608 pop_nested_namespace (ns);
11610 if (old_decl == error_mark_node)
11611 return error_mark_node;
11613 if (old_decl != new_friend)
11615 /* This new friend declaration matched an existing
11616 declaration. For example, given:
11618 template <class T> void f(T);
11619 template <class U> class C {
11620 template <class T> friend void f(T) {}
11623 the friend declaration actually provides the definition
11624 of `f', once C has been instantiated for some type. So,
11625 old_decl will be the out-of-class template declaration,
11626 while new_friend is the in-class definition.
11628 But, if `f' was called before this point, the
11629 instantiation of `f' will have DECL_TI_ARGS corresponding
11630 to `T' but not to `U', references to which might appear
11631 in the definition of `f'. Previously, the most general
11632 template for an instantiation of `f' was the out-of-class
11633 version; now it is the in-class version. Therefore, we
11634 run through all specialization of `f', adding to their
11635 DECL_TI_ARGS appropriately. In particular, they need a
11636 new set of outer arguments, corresponding to the
11637 arguments for this class instantiation.
11639 The same situation can arise with something like this:
11641 friend void f(int);
11642 template <class T> class C {
11643 friend void f(T) {}
11646 when `C<int>' is instantiated. Now, `f(int)' is defined
11647 in the class. */
11649 if (!new_friend_is_defn)
11650 /* On the other hand, if the in-class declaration does
11651 *not* provide a definition, then we don't want to alter
11652 existing definitions. We can just leave everything
11653 alone. */
11655 else
11657 tree old_template = most_general_template (old_decl);
11658 tree new_template = TI_TEMPLATE (new_friend_template_info);
11659 tree new_args = TI_ARGS (new_friend_template_info);
11661 /* Overwrite whatever template info was there before, if
11662 any, with the new template information pertaining to
11663 the declaration. */
11664 DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
11666 if (TREE_CODE (old_decl) != TEMPLATE_DECL)
11668 /* We should have called reregister_specialization in
11669 duplicate_decls. */
11670 gcc_assert (retrieve_specialization (new_template,
11671 new_args, 0)
11672 == old_decl);
11674 /* Instantiate it if the global has already been used. */
11675 if (DECL_ODR_USED (old_decl))
11676 instantiate_decl (old_decl, /*defer_ok=*/true,
11677 /*expl_inst_class_mem_p=*/false);
11679 else
11681 tree t;
11683 /* Indicate that the old function template is a partial
11684 instantiation. */
11685 DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
11686 = new_friend_result_template_info;
11688 gcc_assert (new_template
11689 == most_general_template (new_template));
11690 gcc_assert (new_template != old_decl);
11692 /* Reassign any specializations already in the hash table
11693 to the new more general template, and add the
11694 additional template args. */
11695 for (t = DECL_TEMPLATE_INSTANTIATIONS (old_template);
11696 t != NULL_TREE;
11697 t = TREE_CHAIN (t))
11699 tree spec = TREE_VALUE (t);
11700 spec_entry elt;
11702 elt.tmpl = old_decl;
11703 elt.args = DECL_TI_ARGS (spec);
11704 elt.spec = NULL_TREE;
11706 decl_specializations->remove_elt (&elt);
11708 tree& spec_args = DECL_TI_ARGS (spec);
11709 spec_args = add_outermost_template_args
11710 (new_args, INNERMOST_TEMPLATE_ARGS (spec_args));
11712 register_specialization
11713 (spec, new_template, spec_args, true, 0);
11716 DECL_TEMPLATE_INSTANTIATIONS (old_template) = NULL_TREE;
11720 /* The information from NEW_FRIEND has been merged into OLD_DECL
11721 by duplicate_decls. */
11722 new_friend = old_decl;
11725 /* We've just introduced a namespace-scope function in the purview
11726 without necessarily having opened the enclosing namespace, so
11727 make sure the namespace is in the purview now too. */
11728 if (modules_p ()
11729 && DECL_MODULE_PURVIEW_P (STRIP_TEMPLATE (new_friend))
11730 && TREE_CODE (DECL_CONTEXT (new_friend)) == NAMESPACE_DECL)
11731 DECL_MODULE_PURVIEW_P (DECL_CONTEXT (new_friend)) = true;
11733 else
11735 tree context = DECL_CONTEXT (new_friend);
11736 bool dependent_p;
11738 /* In the code
11739 template <class T> class C {
11740 template <class U> friend void C1<U>::f (); // case 1
11741 friend void C2<T>::f (); // case 2
11743 we only need to make sure CONTEXT is a complete type for
11744 case 2. To distinguish between the two cases, we note that
11745 CONTEXT of case 1 remains dependent type after tsubst while
11746 this isn't true for case 2. */
11747 ++processing_template_decl;
11748 dependent_p = dependent_type_p (context);
11749 --processing_template_decl;
11751 if (!dependent_p
11752 && !complete_type_or_else (context, NULL_TREE))
11753 return error_mark_node;
11755 if (COMPLETE_TYPE_P (context))
11757 tree fn = new_friend;
11758 /* do_friend adds the TEMPLATE_DECL for any member friend
11759 template even if it isn't a member template, i.e.
11760 template <class T> friend A<T>::f();
11761 Look through it in that case. */
11762 if (TREE_CODE (fn) == TEMPLATE_DECL
11763 && !PRIMARY_TEMPLATE_P (fn))
11764 fn = DECL_TEMPLATE_RESULT (fn);
11765 /* Check to see that the declaration is really present, and,
11766 possibly obtain an improved declaration. */
11767 fn = check_classfn (context, fn, NULL_TREE);
11769 if (fn)
11770 new_friend = fn;
11774 return new_friend;
11777 /* FRIEND_TMPL is a friend TEMPLATE_DECL. ARGS is the vector of
11778 template arguments, as for tsubst.
11780 Returns an appropriate tsubst'd friend type or error_mark_node on
11781 failure. */
11783 static tree
11784 tsubst_friend_class (tree friend_tmpl, tree args)
11786 tree tmpl;
11788 if (DECL_TEMPLATE_TEMPLATE_PARM_P (friend_tmpl))
11790 tmpl = tsubst (TREE_TYPE (friend_tmpl), args, tf_none, NULL_TREE);
11791 return TREE_TYPE (tmpl);
11794 if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl)) == 1)
11795 /* The template has already been fully substituted, e.g. for
11797 template <typename> friend class ::C;
11799 so we can just return it directly. */
11800 return TREE_TYPE (friend_tmpl);
11802 tree context = CP_DECL_CONTEXT (friend_tmpl);
11803 if (TREE_CODE (context) == NAMESPACE_DECL)
11804 push_nested_namespace (context);
11805 else
11807 context = tsubst (context, args, tf_error, NULL_TREE);
11808 push_nested_class (context);
11811 tmpl = lookup_name (DECL_NAME (friend_tmpl), LOOK_where::CLASS_NAMESPACE,
11812 LOOK_want::NORMAL | LOOK_want::HIDDEN_FRIEND);
11814 if (!tmpl)
11815 /* If we didn't find by name lookup, the type may still exist but as a
11816 'hidden' import; we should check for this too to avoid accidentally
11817 instantiating a duplicate. */
11818 tmpl = lookup_imported_hidden_friend (friend_tmpl);
11820 if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
11822 /* The friend template has already been declared. Just
11823 check to see that the declarations match, and install any new
11824 default parameters. We must tsubst the default parameters,
11825 of course. We only need the innermost template parameters
11826 because that is all that redeclare_class_template will look
11827 at. */
11829 if (modules_p ())
11830 /* Check that the existing declaration's module attachment is
11831 compatible with the attachment of the friend template. */
11832 module_may_redeclare (tmpl, friend_tmpl);
11834 if (DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (friend_tmpl))
11836 tree parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
11837 args, tf_warning_or_error);
11838 tsubst_each_template_parm_constraints (parms, args,
11839 tf_warning_or_error);
11840 location_t saved_input_location = input_location;
11841 input_location = DECL_SOURCE_LOCATION (friend_tmpl);
11842 tree cons = get_constraints (friend_tmpl);
11843 ++processing_template_decl;
11844 cons = tsubst_constraint_info (cons, args, tf_warning_or_error,
11845 DECL_FRIEND_CONTEXT (friend_tmpl));
11846 --processing_template_decl;
11847 redeclare_class_template (TREE_TYPE (tmpl), parms, cons);
11848 input_location = saved_input_location;
11851 else
11853 /* The friend template has not already been declared. In this
11854 case, the instantiation of the template class will cause the
11855 injection of this template into the namespace scope. */
11856 tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
11858 if (tmpl != error_mark_node)
11860 /* The new TMPL is not an instantiation of anything, so we
11861 forget its origins. It is also not a specialization of
11862 anything. We don't reset CLASSTYPE_TI_TEMPLATE
11863 for the new type because that is supposed to be the
11864 corresponding template decl, i.e., TMPL. */
11865 spec_entry elt;
11866 elt.tmpl = friend_tmpl;
11867 elt.args = CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl));
11868 elt.spec = TREE_TYPE (tmpl);
11869 type_specializations->remove_elt (&elt);
11871 DECL_USE_TEMPLATE (tmpl) = 0;
11872 DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
11873 CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
11874 CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
11875 = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
11876 DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (tmpl) = false;
11878 /* Substitute into and set the constraints on the new declaration. */
11879 if (tree ci = get_constraints (friend_tmpl))
11881 ++processing_template_decl;
11882 ci = tsubst_constraint_info (ci, args, tf_warning_or_error,
11883 DECL_FRIEND_CONTEXT (friend_tmpl));
11884 --processing_template_decl;
11885 set_constraints (tmpl, ci);
11886 tsubst_each_template_parm_constraints (DECL_TEMPLATE_PARMS (tmpl),
11887 args, tf_warning_or_error);
11890 /* We need to propagate the attachment of the original template to the
11891 newly instantiated template type. */
11892 propagate_defining_module (tmpl, friend_tmpl);
11894 /* Inject this template into the enclosing namspace scope. */
11895 tmpl = pushdecl_namespace_level (tmpl, /*hiding=*/true);
11899 if (TREE_CODE (context) == NAMESPACE_DECL)
11900 pop_nested_namespace (context);
11901 else
11902 pop_nested_class ();
11904 return TREE_TYPE (tmpl);
11907 /* Returns zero if TYPE cannot be completed later due to circularity.
11908 Otherwise returns one. */
11910 static int
11911 can_complete_type_without_circularity (tree type)
11913 if (type == NULL_TREE || type == error_mark_node)
11914 return 0;
11915 else if (COMPLETE_TYPE_P (type))
11916 return 1;
11917 else if (TREE_CODE (type) == ARRAY_TYPE)
11918 return can_complete_type_without_circularity (TREE_TYPE (type));
11919 else if (CLASS_TYPE_P (type)
11920 && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
11921 return 0;
11922 else
11923 return 1;
11926 static tree tsubst_omp_clauses (tree, enum c_omp_region_type, tree,
11927 tsubst_flags_t, tree);
11929 /* Instantiate the contract statement. */
11931 static tree
11932 tsubst_contract (tree decl, tree t, tree args, tsubst_flags_t complain,
11933 tree in_decl)
11935 tree type = decl ? TREE_TYPE (TREE_TYPE (decl)) : NULL_TREE;
11936 bool auto_p = type_uses_auto (type);
11938 tree r = copy_node (t);
11940 /* Rebuild the result variable. */
11941 if (type && POSTCONDITION_P (t) && POSTCONDITION_IDENTIFIER (t))
11943 tree oldvar = POSTCONDITION_IDENTIFIER (t);
11945 tree newvar = copy_node (oldvar);
11946 TREE_TYPE (newvar) = type;
11947 DECL_CONTEXT (newvar) = decl;
11948 POSTCONDITION_IDENTIFIER (r) = newvar;
11950 /* Make sure the postcondition is valid. */
11951 location_t loc = DECL_SOURCE_LOCATION (oldvar);
11952 if (!auto_p)
11953 if (!check_postcondition_result (decl, type, loc))
11954 return invalidate_contract (r);
11956 /* Make the variable available for lookup. */
11957 register_local_specialization (newvar, oldvar);
11960 /* Instantiate the condition. If the return type is undeduced, process
11961 the expression as if inside a template to avoid spurious type errors. */
11962 if (auto_p)
11963 ++processing_template_decl;
11964 ++processing_contract_condition;
11965 CONTRACT_CONDITION (r)
11966 = tsubst_expr (CONTRACT_CONDITION (t), args, complain, in_decl);
11967 --processing_contract_condition;
11968 if (auto_p)
11969 --processing_template_decl;
11971 /* And the comment. */
11972 CONTRACT_COMMENT (r)
11973 = tsubst_expr (CONTRACT_COMMENT (r), args, complain, in_decl);
11975 return r;
11978 /* Update T by instantiating its contract attribute. */
11980 static void
11981 tsubst_contract_attribute (tree decl, tree t, tree args,
11982 tsubst_flags_t complain, tree in_decl)
11984 /* For non-specializations, adjust the current declaration to the most general
11985 version of in_decl. Because we defer the instantiation of contracts as long
11986 as possible, they are still written in terms of the parameters (and return
11987 type) of the most general template. */
11988 tree tmpl = DECL_TI_TEMPLATE (in_decl);
11989 if (!DECL_TEMPLATE_SPECIALIZATION (tmpl))
11990 in_decl = DECL_TEMPLATE_RESULT (most_general_template (in_decl));
11991 local_specialization_stack specs (lss_copy);
11992 register_parameter_specializations (in_decl, decl);
11994 /* Get the contract to be instantiated. */
11995 tree contract = CONTRACT_STATEMENT (t);
11997 /* Use the complete set of template arguments for instantiation. The
11998 contract may not have been instantiated and still refer to outer levels
11999 of template parameters. */
12000 args = DECL_TI_ARGS (decl);
12002 /* For member functions, make this available for semantic analysis. */
12003 tree save_ccp = current_class_ptr;
12004 tree save_ccr = current_class_ref;
12005 if (DECL_IOBJ_MEMBER_FUNCTION_P (decl))
12007 tree arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
12008 tree this_type = TREE_TYPE (TREE_VALUE (arg_types));
12009 inject_this_parameter (this_type, cp_type_quals (this_type));
12012 contract = tsubst_contract (decl, contract, args, complain, in_decl);
12014 current_class_ptr = save_ccp;
12015 current_class_ref = save_ccr;
12017 /* Rebuild the attribute. */
12018 TREE_VALUE (t) = build_tree_list (NULL_TREE, contract);
12021 /* Rebuild the attribute list for DECL, substituting into contracts
12022 as needed. */
12024 void
12025 tsubst_contract_attributes (tree decl, tree args, tsubst_flags_t complain, tree in_decl)
12027 tree list = copy_list (DECL_ATTRIBUTES (decl));
12028 for (tree attr = list; attr; attr = CONTRACT_CHAIN (attr))
12030 if (cxx_contract_attribute_p (attr))
12031 tsubst_contract_attribute (decl, attr, args, complain, in_decl);
12033 DECL_ATTRIBUTES (decl) = list;
12036 /* Instantiate a single dependent attribute T (a TREE_LIST), and return either
12037 T or a new TREE_LIST, possibly a chain in the case of a pack expansion. */
12039 static tree
12040 tsubst_attribute (tree t, tree *decl_p, tree args,
12041 tsubst_flags_t complain, tree in_decl)
12043 gcc_assert (ATTR_IS_DEPENDENT (t));
12045 /* Note that contract attributes are never substituted from this function.
12046 Their instantiation is triggered by regenerate_from_template_decl when
12047 we instantiate the body of the function. */
12049 tree val = TREE_VALUE (t);
12050 if (val == NULL_TREE)
12051 /* Nothing to do. */;
12052 else if ((flag_openmp || flag_openmp_simd)
12053 && is_attribute_p ("omp declare simd",
12054 get_attribute_name (t)))
12056 tree clauses = TREE_VALUE (val);
12057 clauses = tsubst_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD, args,
12058 complain, in_decl);
12059 c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
12060 clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
12061 tree parms = DECL_ARGUMENTS (*decl_p);
12062 clauses
12063 = c_omp_declare_simd_clauses_to_numbers (parms, clauses);
12064 if (clauses)
12065 val = build_tree_list (NULL_TREE, clauses);
12066 else
12067 val = NULL_TREE;
12069 else if (flag_openmp
12070 && is_attribute_p ("omp declare variant base",
12071 get_attribute_name (t)))
12073 ++cp_unevaluated_operand;
12074 tree varid = tsubst_expr (TREE_PURPOSE (val), args, complain, in_decl);
12075 --cp_unevaluated_operand;
12076 tree chain = TREE_CHAIN (val);
12077 location_t match_loc = cp_expr_loc_or_input_loc (TREE_PURPOSE (chain));
12078 tree ctx = copy_list (TREE_VALUE (val));
12079 for (tree tss = ctx; tss; tss = TREE_CHAIN (tss))
12081 enum omp_tss_code set = OMP_TSS_CODE (tss);
12082 tree selectors = NULL_TREE;
12083 for (tree ts = OMP_TSS_TRAIT_SELECTORS (tss); ts;
12084 ts = TREE_CHAIN (ts))
12086 tree properties = NULL_TREE;
12087 tree scoreval = NULL_TREE;
12088 /* FIXME: The body of this loop should really be dispatching
12089 according to omp_ts_map[OMP_TS_CODE (TS)].tp_type instead
12090 of having hard-wired knowledge of specific selectors. */
12091 if (OMP_TS_CODE (ts) == OMP_TRAIT_CONSTRUCT_SIMD
12092 && set == OMP_TRAIT_SET_CONSTRUCT)
12094 tree clauses = OMP_TS_PROPERTIES (ts);
12095 clauses = tsubst_omp_clauses (clauses,
12096 C_ORT_OMP_DECLARE_SIMD, args,
12097 complain, in_decl);
12098 c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
12099 clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
12100 properties = clauses;
12102 else
12104 tree v = OMP_TS_SCORE (ts);
12105 if (v)
12107 v = tsubst_expr (v, args, complain, in_decl);
12108 v = fold_non_dependent_expr (v);
12109 if (!INTEGRAL_TYPE_P (TREE_TYPE (v))
12110 || TREE_CODE (v) != INTEGER_CST)
12112 location_t loc
12113 = cp_expr_loc_or_loc (OMP_TS_SCORE (ts),
12114 match_loc);
12115 error_at (loc, "score argument must be "
12116 "constant integer expression");
12117 return NULL_TREE;
12119 else if (tree_int_cst_sgn (v) < 0)
12121 location_t loc
12122 = cp_expr_loc_or_loc (OMP_TS_SCORE (ts),
12123 match_loc);
12124 error_at (loc, "score argument must be "
12125 "non-negative");
12126 return NULL_TREE;
12128 scoreval = v;
12130 properties = copy_list (OMP_TS_PROPERTIES (ts));
12131 for (tree p = properties; p; p = TREE_CHAIN (p))
12132 if (OMP_TP_NAME (p) == OMP_TP_NAMELIST_NODE)
12133 continue;
12134 else if (OMP_TP_VALUE (p))
12136 bool allow_string
12137 = (OMP_TS_CODE (ts) != OMP_TRAIT_USER_CONDITION
12138 || set != OMP_TRAIT_SET_USER);
12139 tree v = OMP_TP_VALUE (p);
12140 if (TREE_CODE (v) == STRING_CST && allow_string)
12141 continue;
12142 v = tsubst_expr (v, args, complain, in_decl);
12143 v = fold_non_dependent_expr (v);
12144 if (!INTEGRAL_TYPE_P (TREE_TYPE (v))
12145 || !tree_fits_shwi_p (v))
12147 location_t loc
12148 = cp_expr_loc_or_loc (OMP_TP_VALUE (p),
12149 match_loc);
12150 if (allow_string)
12151 error_at (loc, "property must be constant "
12152 "integer expression or string "
12153 "literal");
12154 else
12155 error_at (loc, "property must be constant "
12156 "integer expression");
12157 return NULL_TREE;
12159 OMP_TP_VALUE (p) = v;
12162 selectors = make_trait_selector (OMP_TS_CODE (ts), scoreval,
12163 properties, selectors);
12165 OMP_TSS_TRAIT_SELECTORS (tss) = nreverse (selectors);
12167 val = tree_cons (varid, ctx, chain);
12169 /* If the first attribute argument is an identifier, don't
12170 pass it through tsubst. Attributes like mode, format,
12171 cleanup and several target specific attributes expect it
12172 unmodified. */
12173 else if (attribute_takes_identifier_p (get_attribute_name (t)))
12175 tree chain
12176 = tsubst_expr (TREE_CHAIN (val), args, complain, in_decl);
12177 if (chain != TREE_CHAIN (val))
12178 val = tree_cons (NULL_TREE, TREE_VALUE (val), chain);
12180 else if (PACK_EXPANSION_P (val))
12182 /* An attribute pack expansion. */
12183 tree purp = TREE_PURPOSE (t);
12184 tree pack = tsubst_pack_expansion (val, args, complain, in_decl);
12185 if (pack == error_mark_node)
12186 return error_mark_node;
12187 int len = TREE_VEC_LENGTH (pack);
12188 tree list = NULL_TREE;
12189 tree *q = &list;
12190 for (int i = 0; i < len; ++i)
12192 tree elt = TREE_VEC_ELT (pack, i);
12193 *q = build_tree_list (purp, elt);
12194 q = &TREE_CHAIN (*q);
12196 return list;
12198 else
12199 val = tsubst_expr (val, args, complain, in_decl);
12201 if (val == error_mark_node)
12202 return error_mark_node;
12203 if (val != TREE_VALUE (t))
12204 return build_tree_list (TREE_PURPOSE (t), val);
12205 return t;
12208 /* Instantiate any dependent attributes in ATTRIBUTES, returning either it
12209 unchanged or a new TREE_LIST chain. */
12211 static tree
12212 tsubst_attributes (tree attributes, tree args,
12213 tsubst_flags_t complain, tree in_decl)
12215 tree last_dep = NULL_TREE;
12217 for (tree t = attributes; t; t = TREE_CHAIN (t))
12218 if (ATTR_IS_DEPENDENT (t))
12220 last_dep = t;
12221 attributes = copy_list (attributes);
12222 break;
12225 if (last_dep)
12226 for (tree *p = &attributes; *p; )
12228 tree t = *p;
12229 if (ATTR_IS_DEPENDENT (t))
12231 tree subst = tsubst_attribute (t, NULL, args, complain, in_decl);
12232 if (subst != t)
12234 *p = subst;
12235 while (*p)
12236 p = &TREE_CHAIN (*p);
12237 *p = TREE_CHAIN (t);
12238 continue;
12241 p = &TREE_CHAIN (*p);
12244 return attributes;
12247 /* Apply any attributes which had to be deferred until instantiation
12248 time. DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
12249 ARGS, COMPLAIN, IN_DECL are as tsubst. Returns true normally,
12250 false on error. */
12252 static bool
12253 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
12254 tree args, tsubst_flags_t complain, tree in_decl)
12256 tree t;
12257 tree *p;
12259 if (attributes == NULL_TREE)
12260 return true;
12262 if (DECL_P (*decl_p))
12264 if (TREE_TYPE (*decl_p) == error_mark_node)
12265 return false;
12266 p = &DECL_ATTRIBUTES (*decl_p);
12267 /* DECL_ATTRIBUTES comes from copy_node in tsubst_decl, and is identical
12268 to our attributes parameter. */
12269 gcc_assert (*p == attributes);
12271 else if (FUNC_OR_METHOD_TYPE_P (*decl_p))
12272 p = NULL;
12273 else
12275 p = &TYPE_ATTRIBUTES (*decl_p);
12276 /* TYPE_ATTRIBUTES was set up (with abi_tag and may_alias) in
12277 lookup_template_class_1, and should be preserved. */
12278 gcc_assert (*p != attributes);
12279 while (*p)
12280 p = &TREE_CHAIN (*p);
12283 /* save_template_attributes puts the dependent attributes at the beginning of
12284 the list; find the non-dependent ones. */
12285 for (t = attributes; t; t = TREE_CHAIN (t))
12286 if (!ATTR_IS_DEPENDENT (t))
12287 break;
12288 tree nondep = t;
12290 /* Apply any non-dependent attributes. */
12291 if (p)
12292 *p = nondep;
12293 else if (nondep)
12294 *decl_p = cp_build_type_attribute_variant (*decl_p, nondep);
12296 if (nondep == attributes)
12297 return true;
12299 /* And then any dependent ones. */
12300 tree late_attrs = NULL_TREE;
12301 tree *q = &late_attrs;
12302 for (t = attributes; t != nondep; t = TREE_CHAIN (t))
12304 *q = tsubst_attribute (t, decl_p, args, complain, in_decl);
12305 if (*q == error_mark_node)
12306 return false;
12307 if (*q == t)
12309 *q = copy_node (t);
12310 TREE_CHAIN (*q) = NULL_TREE;
12312 while (*q)
12313 q = &TREE_CHAIN (*q);
12316 /* cplus_decl_attributes can add some attributes implicitly. For templates,
12317 those attributes should have been added already when those templates were
12318 parsed, and shouldn't be added based on from which context they are
12319 first time instantiated. */
12320 auto o1 = make_temp_override (current_optimize_pragma, NULL_TREE);
12321 auto o2 = make_temp_override (optimization_current_node,
12322 optimization_default_node);
12323 auto o3 = make_temp_override (current_target_pragma, NULL_TREE);
12324 auto o4 = make_temp_override (scope_chain->omp_declare_target_attribute,
12325 NULL);
12326 auto o5 = make_temp_override (scope_chain->omp_begin_assumes, NULL);
12328 cplus_decl_attributes (decl_p, late_attrs, attr_flags);
12330 return true;
12333 /* The template TMPL is being instantiated with the template arguments TARGS.
12334 Perform the access checks that we deferred when parsing the template. */
12336 static void
12337 perform_instantiation_time_access_checks (tree tmpl, tree targs)
12339 unsigned i;
12340 deferred_access_check *chk;
12342 if (!CLASS_TYPE_P (tmpl) && TREE_CODE (tmpl) != FUNCTION_DECL)
12343 return;
12345 if (vec<deferred_access_check, va_gc> *access_checks
12346 = TI_DEFERRED_ACCESS_CHECKS (get_template_info (tmpl)))
12347 FOR_EACH_VEC_ELT (*access_checks, i, chk)
12349 tree decl = chk->decl;
12350 tree diag_decl = chk->diag_decl;
12351 tree type_scope = TREE_TYPE (chk->binfo);
12353 if (uses_template_parms (type_scope))
12354 type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
12356 /* Make access check error messages point to the location
12357 of the use of the typedef. */
12358 iloc_sentinel ils (chk->loc);
12359 perform_or_defer_access_check (TYPE_BINFO (type_scope),
12360 decl, diag_decl, tf_warning_or_error);
12364 /* If the template T that we're about to instantiate contained errors at
12365 parse time that we downgraded into warnings or suppressed, diagnose the
12366 error now to render the TU ill-formed (if the TU has not already been
12367 deemed ill-formed by an earlier error). */
12369 static void
12370 maybe_diagnose_erroneous_template (tree t)
12372 if (erroneous_templates && !(seen_error) ())
12373 if (location_t *error_loc = erroneous_templates->get (t))
12375 auto_diagnostic_group d;
12376 location_t decl_loc = location_of (t);
12377 error_at (decl_loc, "instantiating erroneous template");
12378 inform (*error_loc, "first error appeared here");
12382 tree
12383 instantiate_class_template (tree type)
12385 auto_timevar tv (TV_TEMPLATE_INST);
12387 tree templ, args, pattern, t, member;
12388 tree typedecl;
12389 tree pbinfo;
12390 tree base_list;
12391 unsigned int saved_maximum_field_alignment;
12392 tree fn_context;
12394 if (type == error_mark_node)
12395 return error_mark_node;
12397 if (COMPLETE_OR_OPEN_TYPE_P (type)
12398 || uses_template_parms (type))
12399 return type;
12401 /* Figure out which template is being instantiated. */
12402 templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
12403 gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
12405 /* Mark the type as in the process of being defined. */
12406 TYPE_BEING_DEFINED (type) = 1;
12408 /* We may be in the middle of deferred access check. Disable
12409 it now. */
12410 deferring_access_check_sentinel acs (dk_no_deferred);
12412 /* Determine what specialization of the original template to
12413 instantiate. */
12414 t = most_specialized_partial_spec (type, tf_warning_or_error);
12415 if (t == error_mark_node)
12416 return error_mark_node;
12417 else if (t)
12419 /* This TYPE is actually an instantiation of a partial
12420 specialization. We replace the innermost set of ARGS with
12421 the arguments appropriate for substitution. For example,
12422 given:
12424 template <class T> struct S {};
12425 template <class T> struct S<T*> {};
12427 and supposing that we are instantiating S<int*>, ARGS will
12428 presently be {int*} -- but we need {int}. */
12429 pattern = TREE_TYPE (TI_TEMPLATE (t));
12430 args = TI_ARGS (t);
12432 else
12434 pattern = TREE_TYPE (templ);
12435 args = CLASSTYPE_TI_ARGS (type);
12438 /* If the template we're instantiating is incomplete, then clearly
12439 there's nothing we can do. */
12440 if (!COMPLETE_TYPE_P (pattern))
12442 /* We can try again later. */
12443 TYPE_BEING_DEFINED (type) = 0;
12444 return type;
12447 /* If we've recursively instantiated too many templates, stop. */
12448 if (! push_tinst_level (type))
12449 return type;
12451 maybe_diagnose_erroneous_template (t ? TI_TEMPLATE (t) : templ);
12453 int saved_unevaluated_operand = cp_unevaluated_operand;
12454 int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
12456 fn_context = decl_function_context (TYPE_MAIN_DECL (type));
12457 /* Also avoid push_to_top_level for a lambda in an NSDMI. */
12458 if (!fn_context && LAMBDA_TYPE_P (type) && TYPE_CLASS_SCOPE_P (type))
12459 fn_context = error_mark_node;
12460 if (!fn_context)
12461 push_to_top_level ();
12462 else
12464 cp_unevaluated_operand = 0;
12465 c_inhibit_evaluation_warnings = 0;
12468 mark_template_arguments_used (templ, CLASSTYPE_TI_ARGS (type));
12470 /* Use #pragma pack from the template context. */
12471 saved_maximum_field_alignment = maximum_field_alignment;
12472 maximum_field_alignment = TYPE_PRECISION (pattern);
12474 SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
12476 /* Set the input location to the most specialized template definition.
12477 This is needed if tsubsting causes an error. */
12478 typedecl = TYPE_MAIN_DECL (pattern);
12479 input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
12480 DECL_SOURCE_LOCATION (typedecl);
12482 set_instantiating_module (TYPE_NAME (type));
12484 TYPE_PACKED (type) = TYPE_PACKED (pattern);
12485 SET_TYPE_ALIGN (type, TYPE_ALIGN (pattern));
12486 TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
12487 CLASSTYPE_NON_AGGREGATE (type) = CLASSTYPE_NON_AGGREGATE (pattern);
12488 if (ANON_AGGR_TYPE_P (pattern))
12489 SET_ANON_AGGR_TYPE_P (type);
12490 if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
12492 CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
12493 CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
12494 /* Adjust visibility for template arguments. */
12495 determine_visibility (TYPE_MAIN_DECL (type));
12497 if (CLASS_TYPE_P (type))
12498 CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
12500 pbinfo = TYPE_BINFO (pattern);
12502 /* We should never instantiate a nested class before its enclosing
12503 class; we need to look up the nested class by name before we can
12504 instantiate it, and that lookup should instantiate the enclosing
12505 class. */
12506 gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
12507 || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
12509 base_list = NULL_TREE;
12510 /* Defer access checking while we substitute into the types named in
12511 the base-clause. */
12512 push_deferring_access_checks (dk_deferred);
12513 if (BINFO_N_BASE_BINFOS (pbinfo))
12515 tree pbase_binfo;
12516 int i;
12518 /* Substitute into each of the bases to determine the actual
12519 basetypes. */
12520 for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
12522 tree base;
12523 tree access = BINFO_BASE_ACCESS (pbinfo, i);
12524 tree expanded_bases = NULL_TREE;
12525 int idx, len = 1;
12527 if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
12529 expanded_bases =
12530 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
12531 args, tf_error, NULL_TREE);
12532 if (expanded_bases == error_mark_node)
12533 continue;
12535 len = TREE_VEC_LENGTH (expanded_bases);
12538 for (idx = 0; idx < len; idx++)
12540 if (expanded_bases)
12541 /* Extract the already-expanded base class. */
12542 base = TREE_VEC_ELT (expanded_bases, idx);
12543 else
12544 /* Substitute to figure out the base class. */
12545 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error,
12546 NULL_TREE);
12548 if (base == error_mark_node)
12549 continue;
12551 base_list = tree_cons (access, base, base_list);
12552 if (BINFO_VIRTUAL_P (pbase_binfo))
12553 TREE_TYPE (base_list) = integer_type_node;
12557 /* The list is now in reverse order; correct that. */
12558 base_list = nreverse (base_list);
12560 /* Now call xref_basetypes to set up all the base-class
12561 information. */
12562 xref_basetypes (type, base_list);
12564 apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
12565 (int) ATTR_FLAG_TYPE_IN_PLACE,
12566 args, tf_error, NULL_TREE);
12567 fixup_attribute_variants (type);
12569 /* Now that our base classes are set up, enter the scope of the
12570 class, so that name lookups into base classes, etc. will work
12571 correctly. This is precisely analogous to what we do in
12572 begin_class_definition when defining an ordinary non-template
12573 class, except we also need to push the enclosing classes. */
12574 push_nested_class (type);
12576 /* Now check accessibility of the types named in its base-clause,
12577 relative to the scope of the class. */
12578 pop_to_parent_deferring_access_checks ();
12580 /* A vector to hold members marked with attribute used. */
12581 auto_vec<tree> used;
12583 /* Now members are processed in the order of declaration. */
12584 for (member = CLASSTYPE_DECL_LIST (pattern);
12585 member; member = TREE_CHAIN (member))
12587 tree t = TREE_VALUE (member);
12589 if (TREE_PURPOSE (member))
12591 if (TYPE_P (t))
12593 if (LAMBDA_TYPE_P (t))
12594 /* A closure type for a lambda in an NSDMI or default argument.
12595 Ignore it; it will be regenerated when needed. */
12596 continue;
12598 /* If the member is a class template, we've
12599 already substituted its type. */
12600 if (CLASS_TYPE_P (t)
12601 && CLASSTYPE_IS_TEMPLATE (t))
12602 continue;
12604 tree newtag = tsubst (t, args, tf_error, NULL_TREE);
12605 if (newtag == error_mark_node)
12606 continue;
12608 if (TREE_CODE (newtag) != ENUMERAL_TYPE)
12610 tree name = TYPE_IDENTIFIER (t);
12612 /* Now, install the tag. We don't use pushtag
12613 because that does too much work -- creating an
12614 implicit typedef, which we've already done. */
12615 set_identifier_type_value (name, TYPE_NAME (newtag));
12616 maybe_add_class_template_decl_list (type, newtag, false);
12617 TREE_PUBLIC (TYPE_NAME (newtag)) = true;
12618 determine_visibility (TYPE_NAME (newtag));
12621 else if (DECL_DECLARES_FUNCTION_P (t))
12623 tree r;
12625 if (TREE_CODE (t) == TEMPLATE_DECL)
12626 ++processing_template_decl;
12627 r = tsubst (t, args, tf_error, NULL_TREE);
12628 if (TREE_CODE (t) == TEMPLATE_DECL)
12629 --processing_template_decl;
12631 set_current_access_from_decl (r);
12632 finish_member_declaration (r);
12633 /* Instantiate members marked with attribute used. */
12634 if (r != error_mark_node && DECL_PRESERVE_P (r))
12635 used.safe_push (r);
12636 if (TREE_CODE (r) == FUNCTION_DECL
12637 && DECL_OMP_DECLARE_REDUCTION_P (r))
12638 cp_check_omp_declare_reduction (r);
12640 else if ((DECL_CLASS_TEMPLATE_P (t) || DECL_IMPLICIT_TYPEDEF_P (t))
12641 && LAMBDA_TYPE_P (TREE_TYPE (t)))
12642 /* A closure type for a lambda in an NSDMI or default argument.
12643 Ignore it; it will be regenerated when needed. */;
12644 else
12646 /* Build new TYPE_FIELDS. */
12647 if (TREE_CODE (t) == STATIC_ASSERT)
12648 tsubst_stmt (t, args, tf_warning_or_error, NULL_TREE);
12649 else if (TREE_CODE (t) != CONST_DECL)
12651 tree r;
12652 tree vec = NULL_TREE;
12653 int len = 1;
12655 gcc_checking_assert (TREE_CODE (t) != CONST_DECL);
12656 /* The file and line for this declaration, to
12657 assist in error message reporting. Since we
12658 called push_tinst_level above, we don't need to
12659 restore these. */
12660 input_location = DECL_SOURCE_LOCATION (t);
12662 if (TREE_CODE (t) == TEMPLATE_DECL)
12663 ++processing_template_decl;
12664 r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
12665 if (TREE_CODE (t) == TEMPLATE_DECL)
12666 --processing_template_decl;
12668 if (TREE_CODE (r) == TREE_VEC)
12670 /* A capture pack became multiple fields. */
12671 vec = r;
12672 len = TREE_VEC_LENGTH (vec);
12675 for (int i = 0; i < len; ++i)
12677 if (vec)
12678 r = TREE_VEC_ELT (vec, i);
12679 if (VAR_P (r))
12681 /* In [temp.inst]:
12683 [t]he initialization (and any associated
12684 side-effects) of a static data member does
12685 not occur unless the static data member is
12686 itself used in a way that requires the
12687 definition of the static data member to
12688 exist.
12690 Therefore, we do not substitute into the
12691 initialized for the static data member here. */
12692 finish_static_data_member_decl
12694 /*init=*/NULL_TREE,
12695 /*init_const_expr_p=*/false,
12696 /*asmspec_tree=*/NULL_TREE,
12697 /*flags=*/0);
12698 /* Instantiate members marked with attribute used. */
12699 if (r != error_mark_node && DECL_PRESERVE_P (r))
12700 used.safe_push (r);
12702 else if (TREE_CODE (r) == FIELD_DECL)
12704 /* Determine whether R has a valid type and can be
12705 completed later. If R is invalid, then its type
12706 is replaced by error_mark_node. */
12707 tree rtype = TREE_TYPE (r);
12708 if (can_complete_type_without_circularity (rtype))
12709 complete_type (rtype);
12711 if (!complete_or_array_type_p (rtype))
12713 /* If R's type couldn't be completed and
12714 it isn't a flexible array member (whose
12715 type is incomplete by definition) give
12716 an error. */
12717 cxx_incomplete_type_error (r, rtype);
12718 TREE_TYPE (r) = error_mark_node;
12720 else if (TREE_CODE (rtype) == ARRAY_TYPE
12721 && TYPE_DOMAIN (rtype) == NULL_TREE
12722 && (TREE_CODE (type) == UNION_TYPE
12723 || TREE_CODE (type) == QUAL_UNION_TYPE))
12725 error ("flexible array member %qD in union", r);
12726 TREE_TYPE (r) = error_mark_node;
12728 else if (!verify_type_context (input_location,
12729 TCTX_FIELD, rtype))
12730 TREE_TYPE (r) = error_mark_node;
12733 /* If it is a TYPE_DECL for a class-scoped
12734 ENUMERAL_TYPE, such a thing will already have
12735 been added to the field list by tsubst_enum
12736 in finish_member_declaration case above. */
12737 if (!(TREE_CODE (r) == TYPE_DECL
12738 && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
12739 && DECL_ARTIFICIAL (r)))
12741 set_current_access_from_decl (r);
12742 finish_member_declaration (r);
12748 else
12750 if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t)
12751 || DECL_TEMPLATE_TEMPLATE_PARM_P (t))
12753 /* Build new CLASSTYPE_FRIEND_CLASSES. */
12755 tree friend_type = t;
12756 if (TREE_CODE (friend_type) == TEMPLATE_DECL)
12758 /* template <class T> friend class C; */
12759 friend_type = tsubst_friend_class (friend_type, args);
12761 else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
12763 /* template <class T> friend class C::D; */
12764 friend_type = tsubst (friend_type, args,
12765 tf_warning_or_error, NULL_TREE);
12766 if (TREE_CODE (friend_type) == TEMPLATE_DECL)
12767 friend_type = TREE_TYPE (friend_type);
12769 else if (TREE_CODE (friend_type) == TYPENAME_TYPE
12770 || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
12772 /* This could be either
12774 friend class T::C;
12776 when dependent_type_p is false or
12778 template <class U> friend class T::C;
12780 otherwise. */
12781 /* Bump processing_template_decl in case this is something like
12782 template <class T> friend struct A<T>::B. */
12783 ++processing_template_decl;
12784 friend_type = tsubst (friend_type, args,
12785 tf_warning_or_error, NULL_TREE);
12786 --processing_template_decl;
12788 else if (PACK_EXPANSION_P (friend_type))
12790 friend_type = tsubst_pack_expansion (friend_type, args,
12791 tf_warning_or_error,
12792 NULL_TREE);
12793 if (friend_type != error_mark_node)
12795 unsigned int len = TREE_VEC_LENGTH (friend_type);
12796 for (unsigned int idx = 0; idx < len; ++idx)
12797 if (TREE_VEC_ELT (friend_type, idx) != error_mark_node)
12798 make_friend_class (type,
12799 TREE_VEC_ELT (friend_type, idx),
12800 /*complain=*/false);
12802 friend_type = error_mark_node;
12804 else if (uses_template_parms (friend_type))
12805 /* friend class C<T>; */
12806 friend_type = tsubst (friend_type, args,
12807 tf_warning_or_error, NULL_TREE);
12809 /* Otherwise it's
12811 friend class C;
12813 where C is already declared or
12815 friend class C<int>;
12817 We don't have to do anything in these cases. */
12819 if (friend_type != error_mark_node)
12820 make_friend_class (type, friend_type, /*complain=*/false);
12822 else
12824 /* Build new DECL_FRIENDLIST. */
12825 tree r;
12827 /* The file and line for this declaration, to
12828 assist in error message reporting. Since we
12829 called push_tinst_level above, we don't need to
12830 restore these. */
12831 input_location = DECL_SOURCE_LOCATION (t);
12833 if (TREE_CODE (t) == TEMPLATE_DECL)
12835 ++processing_template_decl;
12836 push_deferring_access_checks (dk_no_check);
12839 r = tsubst_friend_function (t, args);
12840 add_friend (type, r, /*complain=*/false);
12841 if (TREE_CODE (t) == TEMPLATE_DECL)
12843 pop_deferring_access_checks ();
12844 --processing_template_decl;
12850 if (fn_context)
12852 /* Restore these before substituting into the lambda capture
12853 initializers. */
12854 cp_unevaluated_operand = saved_unevaluated_operand;
12855 c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
12858 /* Set the file and line number information to whatever is given for
12859 the class itself. This puts error messages involving generated
12860 implicit functions at a predictable point, and the same point
12861 that would be used for non-template classes. */
12862 input_location = DECL_SOURCE_LOCATION (typedecl);
12864 unreverse_member_declarations (type);
12865 finish_struct_1 (type);
12866 TYPE_BEING_DEFINED (type) = 0;
12868 /* Remember if instantiating this class ran into errors, so we can avoid
12869 instantiating member functions in limit_bad_template_recursion. We set
12870 this flag even if the problem was in another instantiation triggered by
12871 this one, as that will likely also cause trouble for member functions. */
12872 if (errorcount + sorrycount > current_tinst_level->errors)
12873 CLASSTYPE_ERRONEOUS (type) = true;
12875 /* We don't instantiate default arguments for member functions. 14.7.1:
12877 The implicit instantiation of a class template specialization causes
12878 the implicit instantiation of the declarations, but not of the
12879 definitions or default arguments, of the class member functions,
12880 member classes, static data members and member templates.... */
12882 perform_instantiation_time_access_checks (pattern, args);
12883 perform_deferred_access_checks (tf_warning_or_error);
12885 /* Now that we've gone through all the members, instantiate those
12886 marked with attribute used. We must do this in the context of
12887 the class -- not the context we pushed from, as that might be
12888 inside a template and change the behaviour of mark_used. */
12889 for (tree x : used)
12890 mark_used (x);
12892 pop_nested_class ();
12893 maximum_field_alignment = saved_maximum_field_alignment;
12894 if (!fn_context)
12895 pop_from_top_level ();
12896 pop_tinst_level ();
12898 /* The vtable for a template class can be emitted in any translation
12899 unit in which the class is instantiated. When there is no key
12900 method, however, finish_struct_1 will already have added TYPE to
12901 the keyed_classes. */
12902 if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
12903 vec_safe_push (keyed_classes, type);
12905 return type;
12908 tree
12909 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12911 tree r;
12913 if (!t)
12914 r = t;
12915 else if (TYPE_P (t))
12916 r = tsubst (t, args, complain, in_decl);
12917 else
12919 if (!(complain & tf_warning))
12920 ++c_inhibit_evaluation_warnings;
12921 r = tsubst_expr (t, args, complain, in_decl);
12922 if (!(complain & tf_warning))
12923 --c_inhibit_evaluation_warnings;
12926 return r;
12929 /* Given a function parameter pack TMPL_PARM and some function parameters
12930 instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
12931 and set *SPEC_P to point at the next point in the list. */
12933 tree
12934 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
12936 /* Collect all of the extra "packed" parameters into an
12937 argument pack. */
12938 tree argpack;
12939 tree spec_parm = *spec_p;
12940 int len;
12942 for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
12943 if (tmpl_parm
12944 && !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
12945 break;
12947 spec_parm = *spec_p;
12948 if (len == 1 && DECL_PACK_P (spec_parm))
12950 /* The instantiation is still a parameter pack; don't wrap it in a
12951 NONTYPE_ARGUMENT_PACK. */
12952 argpack = spec_parm;
12953 spec_parm = DECL_CHAIN (spec_parm);
12955 else
12957 /* Fill in PARMVEC with all of the parameters. */
12958 tree parmvec = make_tree_vec (len);
12959 argpack = make_node (NONTYPE_ARGUMENT_PACK);
12960 for (int i = 0; i < len; i++)
12962 tree elt = spec_parm;
12963 if (DECL_PACK_P (elt))
12964 elt = make_pack_expansion (elt);
12965 TREE_VEC_ELT (parmvec, i) = elt;
12966 spec_parm = DECL_CHAIN (spec_parm);
12969 /* Build the argument packs. */
12970 ARGUMENT_PACK_ARGS (argpack) = parmvec;
12972 *spec_p = spec_parm;
12974 return argpack;
12977 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
12978 NONTYPE_ARGUMENT_PACK. */
12980 static tree
12981 make_fnparm_pack (tree spec_parm)
12983 return extract_fnparm_pack (NULL_TREE, &spec_parm);
12986 /* Return 1 if the Ith element of the argument pack ARG_PACK is a
12987 pack expansion with no extra args, 2 if it has extra args, or 0
12988 if it is not a pack expansion. */
12990 static int
12991 argument_pack_element_is_expansion_p (tree arg_pack, int i)
12993 if (TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
12994 /* We're being called before this happens in tsubst_pack_expansion. */
12995 arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
12996 tree vec = ARGUMENT_PACK_ARGS (arg_pack);
12997 if (i >= TREE_VEC_LENGTH (vec))
12998 return 0;
12999 tree elt = TREE_VEC_ELT (vec, i);
13000 if (DECL_P (elt))
13001 /* A decl pack is itself an expansion. */
13002 elt = TREE_TYPE (elt);
13003 if (!PACK_EXPANSION_P (elt))
13004 return 0;
13005 if (PACK_EXPANSION_EXTRA_ARGS (elt))
13006 return 2;
13007 return 1;
13011 /* Creates and return an ARGUMENT_PACK_SELECT tree node. */
13013 static tree
13014 make_argument_pack_select (tree arg_pack, unsigned index)
13016 tree aps = make_node (ARGUMENT_PACK_SELECT);
13018 ARGUMENT_PACK_SELECT_FROM_PACK (aps) = arg_pack;
13019 ARGUMENT_PACK_SELECT_INDEX (aps) = index;
13021 return aps;
13024 /* This is a subroutine of tsubst_pack_expansion.
13026 It returns TRUE if we need to use the PACK_EXPANSION_EXTRA_ARGS
13027 mechanism to store the (non complete list of) arguments of the
13028 substitution and return a non substituted pack expansion, in order
13029 to wait for when we have enough arguments to really perform the
13030 substitution. */
13032 static bool
13033 use_pack_expansion_extra_args_p (tree t,
13034 tree parm_packs,
13035 int arg_pack_len,
13036 bool has_empty_arg)
13038 if (has_empty_arg
13039 && PACK_EXPANSION_FORCE_EXTRA_ARGS_P (t))
13040 return true;
13042 /* If one pack has an expansion and another pack has a normal
13043 argument or if one pack has an empty argument and an another
13044 one hasn't then tsubst_pack_expansion cannot perform the
13045 substitution and need to fall back on the
13046 PACK_EXPANSION_EXTRA mechanism. */
13047 if (parm_packs == NULL_TREE)
13048 return false;
13049 else if (has_empty_arg)
13051 /* If all the actual packs are pack expansions, we can still
13052 subsitute directly. */
13053 for (tree p = parm_packs; p; p = TREE_CHAIN (p))
13055 tree a = TREE_VALUE (p);
13056 if (TREE_CODE (a) == ARGUMENT_PACK_SELECT)
13057 a = ARGUMENT_PACK_SELECT_FROM_PACK (a);
13058 a = ARGUMENT_PACK_ARGS (a);
13059 if (TREE_VEC_LENGTH (a) == 1)
13060 a = TREE_VEC_ELT (a, 0);
13061 if (PACK_EXPANSION_P (a))
13062 continue;
13063 return true;
13065 return false;
13068 for (int i = 0 ; i < arg_pack_len; ++i)
13070 bool has_expansion_arg = false;
13071 bool has_non_expansion_arg = false;
13072 for (tree parm_pack = parm_packs;
13073 parm_pack;
13074 parm_pack = TREE_CHAIN (parm_pack))
13076 tree arg = TREE_VALUE (parm_pack);
13078 int exp = argument_pack_element_is_expansion_p (arg, i);
13079 if (exp == 2)
13080 /* We can't substitute a pack expansion with extra args into
13081 our pattern. */
13082 return true;
13083 else if (exp)
13084 has_expansion_arg = true;
13085 else
13086 has_non_expansion_arg = true;
13089 if (has_expansion_arg && has_non_expansion_arg)
13091 gcc_checking_assert (false);
13092 return true;
13095 return false;
13098 /* [temp.variadic]/6 says that:
13100 The instantiation of a pack expansion [...]
13101 produces a list E1,E2, ..., En, where N is the number of elements
13102 in the pack expansion parameters.
13104 This subroutine of tsubst_pack_expansion produces one of these Ei.
13106 PATTERN is the pattern of the pack expansion. PARM_PACKS is a
13107 TREE_LIST in which each TREE_PURPOSE is a parameter pack of
13108 PATTERN, and each TREE_VALUE is its corresponding argument pack.
13109 INDEX is the index 'i' of the element Ei to produce. ARGS,
13110 COMPLAIN, and IN_DECL are the same parameters as for the
13111 tsubst_pack_expansion function.
13113 The function returns the resulting Ei upon successful completion,
13114 or error_mark_node.
13116 Note that this function possibly modifies the ARGS parameter, so
13117 it's the responsibility of the caller to restore it. */
13119 static tree
13120 gen_elem_of_pack_expansion_instantiation (tree pattern,
13121 tree parm_packs,
13122 unsigned index,
13123 tree args /* This parm gets
13124 modified. */,
13125 tsubst_flags_t complain,
13126 tree in_decl)
13128 tree t;
13129 bool ith_elem_is_expansion = false;
13131 /* For each parameter pack, change the substitution of the parameter
13132 pack to the ith argument in its argument pack, then expand the
13133 pattern. */
13134 for (tree pack = parm_packs; pack; pack = TREE_CHAIN (pack))
13136 tree parm = TREE_PURPOSE (pack);
13137 tree arg_pack = TREE_VALUE (pack);
13138 tree aps; /* instance of ARGUMENT_PACK_SELECT. */
13140 ith_elem_is_expansion |=
13141 argument_pack_element_is_expansion_p (arg_pack, index);
13143 /* Select the Ith argument from the pack. */
13144 if (TREE_CODE (parm) == PARM_DECL
13145 || VAR_P (parm)
13146 || TREE_CODE (parm) == FIELD_DECL)
13148 if (index == 0)
13150 aps = make_argument_pack_select (arg_pack, index);
13151 if (!mark_used (parm, complain) && !(complain & tf_error))
13152 return error_mark_node;
13153 register_local_specialization (aps, parm);
13155 else
13156 aps = retrieve_local_specialization (parm);
13158 else
13160 int idx, level;
13161 template_parm_level_and_index (parm, &level, &idx);
13163 if (index == 0)
13165 aps = make_argument_pack_select (arg_pack, index);
13166 /* Update the corresponding argument. */
13167 TMPL_ARG (args, level, idx) = aps;
13169 else
13170 /* Re-use the ARGUMENT_PACK_SELECT. */
13171 aps = TMPL_ARG (args, level, idx);
13173 ARGUMENT_PACK_SELECT_INDEX (aps) = index;
13176 /* Substitute into the PATTERN with the (possibly altered)
13177 arguments. */
13178 if (pattern == in_decl)
13179 /* Expanding a fixed parameter pack from
13180 coerce_template_parameter_pack. */
13181 t = tsubst_decl (pattern, args, complain);
13182 else if (pattern == error_mark_node)
13183 t = error_mark_node;
13184 else if (!TYPE_P (pattern))
13185 t = tsubst_expr (pattern, args, complain, in_decl);
13186 else
13188 t = tsubst (pattern, args, complain, in_decl);
13189 if (is_auto (t) && !ith_elem_is_expansion)
13190 /* When expanding the fake auto... pack expansion from add_capture, we
13191 need to mark that the expansion is no longer a pack. */
13192 TEMPLATE_TYPE_PARAMETER_PACK (t) = false;
13195 /* If the Ith argument pack element is a pack expansion, then
13196 the Ith element resulting from the substituting is going to
13197 be a pack expansion as well. */
13198 if (ith_elem_is_expansion)
13199 t = make_pack_expansion (t, complain);
13201 return t;
13204 /* When the unexpanded parameter pack in a fold expression expands to an empty
13205 sequence, the value of the expression is as follows; the program is
13206 ill-formed if the operator is not listed in this table.
13208 && true
13209 || false
13210 , void() */
13212 tree
13213 expand_empty_fold (tree t, tsubst_flags_t complain)
13215 tree_code code = (tree_code)TREE_INT_CST_LOW (TREE_OPERAND (t, 0));
13216 if (!FOLD_EXPR_MODIFY_P (t))
13217 switch (code)
13219 case TRUTH_ANDIF_EXPR:
13220 return boolean_true_node;
13221 case TRUTH_ORIF_EXPR:
13222 return boolean_false_node;
13223 case COMPOUND_EXPR:
13224 return void_node;
13225 default:
13226 break;
13229 if (complain & tf_error)
13230 error_at (location_of (t),
13231 "fold of empty expansion over %O", code);
13232 return error_mark_node;
13235 /* Given a fold-expression T and a current LEFT and RIGHT operand,
13236 form an expression that combines the two terms using the
13237 operator of T. */
13239 static tree
13240 fold_expression (tree t, tree left, tree right, tsubst_flags_t complain)
13242 tree_code code = FOLD_EXPR_OP (t);
13244 tree lookups = templated_operator_saved_lookups (t);
13246 // Handle compound assignment operators.
13247 if (FOLD_EXPR_MODIFY_P (t))
13248 return build_x_modify_expr (input_location, left, code, right,
13249 lookups, complain);
13251 warning_sentinel s(warn_parentheses);
13252 switch (code)
13254 case COMPOUND_EXPR:
13255 return build_x_compound_expr (input_location, left, right,
13256 lookups, complain);
13257 default:
13258 return build_x_binary_op (input_location, code,
13259 left, TREE_CODE (left),
13260 right, TREE_CODE (right),
13261 lookups, /*overload=*/NULL,
13262 complain);
13266 /* Substitute ARGS into the pack of a fold expression T. */
13268 static inline tree
13269 tsubst_fold_expr_pack (tree t, tree args, tsubst_flags_t complain, tree in_decl)
13271 return tsubst_pack_expansion (FOLD_EXPR_PACK (t), args, complain, in_decl);
13274 /* Substitute ARGS into the pack of a fold expression T. */
13276 static inline tree
13277 tsubst_fold_expr_init (tree t, tree args, tsubst_flags_t complain, tree in_decl)
13279 return tsubst_expr (FOLD_EXPR_INIT (t), args, complain, in_decl);
13282 /* Expand a PACK of arguments into a grouped as left fold.
13283 Given a pack containing elements A0, A1, ..., An and an
13284 operator @, this builds the expression:
13286 ((A0 @ A1) @ A2) ... @ An
13288 Note that PACK must not be empty.
13290 The operator is defined by the original fold expression T. */
13292 static tree
13293 expand_left_fold (tree t, tree pack, tsubst_flags_t complain)
13295 tree left = TREE_VEC_ELT (pack, 0);
13296 for (int i = 1; i < TREE_VEC_LENGTH (pack); ++i)
13298 tree right = TREE_VEC_ELT (pack, i);
13299 left = fold_expression (t, left, right, complain);
13301 return left;
13304 /* Substitute into a unary left fold expression. */
13306 static tree
13307 tsubst_unary_left_fold (tree t, tree args, tsubst_flags_t complain,
13308 tree in_decl)
13310 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
13311 if (pack == error_mark_node)
13312 return error_mark_node;
13313 if (PACK_EXPANSION_P (pack))
13315 tree r = copy_node (t);
13316 FOLD_EXPR_PACK (r) = pack;
13317 return r;
13319 if (TREE_VEC_LENGTH (pack) == 0)
13320 return expand_empty_fold (t, complain);
13321 else
13322 return expand_left_fold (t, pack, complain);
13325 /* Substitute into a binary left fold expression.
13327 Do ths by building a single (non-empty) vector of argumnts and
13328 building the expression from those elements. */
13330 static tree
13331 tsubst_binary_left_fold (tree t, tree args, tsubst_flags_t complain,
13332 tree in_decl)
13334 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
13335 if (pack == error_mark_node)
13336 return error_mark_node;
13337 tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
13338 if (init == error_mark_node)
13339 return error_mark_node;
13341 if (PACK_EXPANSION_P (pack))
13343 tree r = copy_node (t);
13344 FOLD_EXPR_PACK (r) = pack;
13345 FOLD_EXPR_INIT (r) = init;
13346 return r;
13349 tree vec = make_tree_vec (TREE_VEC_LENGTH (pack) + 1);
13350 TREE_VEC_ELT (vec, 0) = init;
13351 for (int i = 0; i < TREE_VEC_LENGTH (pack); ++i)
13352 TREE_VEC_ELT (vec, i + 1) = TREE_VEC_ELT (pack, i);
13354 return expand_left_fold (t, vec, complain);
13357 /* Expand a PACK of arguments into a grouped as right fold.
13358 Given a pack containing elementns A0, A1, ..., and an
13359 operator @, this builds the expression:
13361 A0@ ... (An-2 @ (An-1 @ An))
13363 Note that PACK must not be empty.
13365 The operator is defined by the original fold expression T. */
13367 tree
13368 expand_right_fold (tree t, tree pack, tsubst_flags_t complain)
13370 // Build the expression.
13371 int n = TREE_VEC_LENGTH (pack);
13372 tree right = TREE_VEC_ELT (pack, n - 1);
13373 for (--n; n != 0; --n)
13375 tree left = TREE_VEC_ELT (pack, n - 1);
13376 right = fold_expression (t, left, right, complain);
13378 return right;
13381 /* Substitute into a unary right fold expression. */
13383 static tree
13384 tsubst_unary_right_fold (tree t, tree args, tsubst_flags_t complain,
13385 tree in_decl)
13387 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
13388 if (pack == error_mark_node)
13389 return error_mark_node;
13390 if (PACK_EXPANSION_P (pack))
13392 tree r = copy_node (t);
13393 FOLD_EXPR_PACK (r) = pack;
13394 return r;
13396 if (TREE_VEC_LENGTH (pack) == 0)
13397 return expand_empty_fold (t, complain);
13398 else
13399 return expand_right_fold (t, pack, complain);
13402 /* Substitute into a binary right fold expression.
13404 Do ths by building a single (non-empty) vector of arguments and
13405 building the expression from those elements. */
13407 static tree
13408 tsubst_binary_right_fold (tree t, tree args, tsubst_flags_t complain,
13409 tree in_decl)
13411 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
13412 if (pack == error_mark_node)
13413 return error_mark_node;
13414 tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
13415 if (init == error_mark_node)
13416 return error_mark_node;
13418 if (PACK_EXPANSION_P (pack))
13420 tree r = copy_node (t);
13421 FOLD_EXPR_PACK (r) = pack;
13422 FOLD_EXPR_INIT (r) = init;
13423 return r;
13426 int n = TREE_VEC_LENGTH (pack);
13427 tree vec = make_tree_vec (n + 1);
13428 for (int i = 0; i < n; ++i)
13429 TREE_VEC_ELT (vec, i) = TREE_VEC_ELT (pack, i);
13430 TREE_VEC_ELT (vec, n) = init;
13432 return expand_right_fold (t, vec, complain);
13435 /* Walk through the pattern of a pack expansion, adding everything in
13436 local_specializations to a list. */
13438 class el_data
13440 public:
13441 /* Set of variables declared within the pattern. */
13442 hash_set<tree> internal;
13443 /* Set of AST nodes that have been visited by the traversal. */
13444 hash_set<tree> visited;
13445 /* List of local_specializations used within the pattern. */
13446 tree extra;
13447 tsubst_flags_t complain;
13448 /* True iff we don't want to walk into unevaluated contexts. */
13449 bool skip_unevaluated_operands = false;
13450 /* The unevaluated contexts that we avoided walking. */
13451 auto_vec<tree> skipped_trees;
13453 el_data (tsubst_flags_t c)
13454 : extra (NULL_TREE), complain (c) {}
13456 static tree
13457 extract_locals_r (tree *tp, int *walk_subtrees, void *data_)
13459 el_data &data = *reinterpret_cast<el_data*>(data_);
13460 tree *extra = &data.extra;
13461 tsubst_flags_t complain = data.complain;
13463 if (data.skip_unevaluated_operands
13464 && unevaluated_p (TREE_CODE (*tp)))
13466 data.skipped_trees.safe_push (*tp);
13467 *walk_subtrees = 0;
13468 return NULL_TREE;
13471 if (TYPE_P (*tp) && typedef_variant_p (*tp))
13472 /* Remember local typedefs (85214). */
13473 tp = &TYPE_NAME (*tp);
13475 if (has_extra_args_mechanism_p (*tp))
13476 /* Assert *_EXTRA_ARGS is empty, because we don't want to walk it and
13477 potentially see a previously captured local in an evaluated context
13478 that's really only used in an unevaluated context (PR114303). This
13479 means callers of build_extra_args need to clear *_EXTRA_ARGS of the
13480 outermost tree. Nested *_EXTRA_ARGS should naturally be empty since
13481 the outermost (extra-args) tree will intercept any substitution before
13482 a nested tree can. */
13483 gcc_checking_assert (tree_extra_args (*tp) == NULL_TREE
13484 /* Except a lambda nested inside an extra-args tree
13485 can have extra args if we deferred partial
13486 substitution into it at template parse time. But
13487 we don't walk LAMBDA_EXPR_EXTRA_ARGS anyway. */
13488 || TREE_CODE (*tp) == LAMBDA_EXPR);
13490 if (TREE_CODE (*tp) == DECL_EXPR)
13492 tree decl = DECL_EXPR_DECL (*tp);
13493 data.internal.add (decl);
13494 if (DECL_DECOMPOSITION_P (decl)
13495 && TREE_TYPE (decl) != error_mark_node)
13497 gcc_assert (DECL_NAME (decl) == NULL_TREE);
13498 for (tree decl2 = DECL_CHAIN (decl);
13499 decl2
13500 && DECL_DECOMPOSITION_P (decl2)
13501 && DECL_NAME (decl2)
13502 && TREE_TYPE (decl2) != error_mark_node;
13503 decl2 = DECL_CHAIN (decl2))
13505 gcc_assert (DECL_DECOMP_BASE (decl2) == decl);
13506 data.internal.add (decl2);
13510 else if (TREE_CODE (*tp) == LAMBDA_EXPR)
13512 /* Since we defer implicit capture, look in the parms and body. */
13513 tree fn = lambda_function (*tp);
13514 cp_walk_tree (&TREE_TYPE (fn), &extract_locals_r, &data,
13515 &data.visited);
13516 cp_walk_tree (&DECL_SAVED_TREE (fn), &extract_locals_r, &data,
13517 &data.visited);
13519 else if (tree spec = retrieve_local_specialization (*tp))
13521 if (data.internal.contains (*tp))
13522 /* Don't mess with variables declared within the pattern. */
13523 return NULL_TREE;
13524 if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
13526 /* Maybe pull out the PARM_DECL for a partial instantiation. */
13527 tree args = ARGUMENT_PACK_ARGS (spec);
13528 if (TREE_VEC_LENGTH (args) == 1)
13530 tree elt = TREE_VEC_ELT (args, 0);
13531 if (PACK_EXPANSION_P (elt))
13532 elt = PACK_EXPANSION_PATTERN (elt);
13533 if (DECL_PACK_P (elt))
13534 spec = elt;
13536 if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
13538 /* Handle lambda capture here, since we aren't doing any
13539 substitution now, and so tsubst_copy won't call
13540 process_outer_var_ref. */
13541 tree args = ARGUMENT_PACK_ARGS (spec);
13542 int len = TREE_VEC_LENGTH (args);
13543 for (int i = 0; i < len; ++i)
13545 tree arg = TREE_VEC_ELT (args, i);
13546 tree carg = arg;
13547 if (outer_automatic_var_p (arg))
13548 carg = process_outer_var_ref (arg, complain);
13549 if (carg != arg)
13551 /* Make a new NONTYPE_ARGUMENT_PACK of the capture
13552 proxies. */
13553 if (i == 0)
13555 spec = copy_node (spec);
13556 args = copy_node (args);
13557 ARGUMENT_PACK_ARGS (spec) = args;
13558 register_local_specialization (spec, *tp);
13560 TREE_VEC_ELT (args, i) = carg;
13565 if (outer_automatic_var_p (spec))
13566 spec = process_outer_var_ref (spec, complain);
13567 *extra = tree_cons (*tp, spec, *extra);
13569 return NULL_TREE;
13571 static tree
13572 extract_local_specs (tree pattern, tsubst_flags_t complain)
13574 el_data data (complain);
13575 /* Walk the pattern twice, ignoring unevaluated operands the first time
13576 around, so that if a local specialization appears in both an evaluated
13577 and unevaluated context we prefer to process it in the evaluated context
13578 (since e.g. process_outer_var_ref is a no-op inside an unevaluated
13579 context). */
13580 data.skip_unevaluated_operands = true;
13581 cp_walk_tree (&pattern, extract_locals_r, &data, &data.visited);
13582 /* Now walk the unevaluated contexts we skipped the first time around. */
13583 data.skip_unevaluated_operands = false;
13584 for (tree t : data.skipped_trees)
13586 data.visited.remove (t);
13587 cp_walk_tree (&t, extract_locals_r, &data, &data.visited);
13589 return data.extra;
13592 /* Extract any uses of local_specializations from PATTERN and add them to ARGS
13593 for use in PACK_EXPANSION_EXTRA_ARGS. */
13595 tree
13596 build_extra_args (tree pattern, tree args, tsubst_flags_t complain)
13598 /* Make a copy of the extra arguments so that they won't get changed
13599 out from under us. */
13600 tree extra = preserve_args (copy_template_args (args), /*cow_p=*/false);
13601 if (complain & tf_partial)
13602 /* Remember whether this is a partial substitution. */
13603 TREE_STATIC (extra) = true;
13604 if (local_specializations)
13605 if (tree locals = extract_local_specs (pattern, complain))
13606 extra = tree_cons (NULL_TREE, extra, locals);
13607 return extra;
13610 /* Apply any local specializations from PACK_EXPANSION_EXTRA_ARGS and add the
13611 normal template args to ARGS. */
13613 tree
13614 add_extra_args (tree extra, tree args, tsubst_flags_t complain, tree in_decl)
13616 if (!extra)
13617 return args;
13619 if (TREE_CODE (extra) == TREE_LIST)
13621 for (tree elt = TREE_CHAIN (extra); elt; elt = TREE_CHAIN (elt))
13623 /* The partial instantiation involved local declarations collected in
13624 extract_local_specs; map from the general template to our local
13625 context. */
13626 tree gen = TREE_PURPOSE (elt);
13627 tree inst = TREE_VALUE (elt);
13628 if (DECL_P (inst))
13629 if (tree local = retrieve_local_specialization (inst))
13630 inst = local;
13631 /* else inst is already a full instantiation of the pack. */
13632 register_local_specialization (inst, gen);
13634 gcc_assert (!TREE_PURPOSE (extra));
13635 extra = TREE_VALUE (extra);
13637 gcc_checking_assert (TREE_STATIC (extra) == uses_template_parms (extra));
13638 if (TREE_STATIC (extra))
13639 /* This is a partial substitution into e.g. a requires-expr or lambda-expr
13640 inside a default template argument; we expect 'extra' to be a full set
13641 of template arguments for the template context, so it suffices to just
13642 substitute into them. */
13643 args = tsubst_template_args (extra, args, complain, in_decl);
13644 else
13645 args = add_to_template_args (extra, args);
13646 return args;
13649 /* Substitute ARGS into T, which is an pack expansion
13650 (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
13651 TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
13652 (if only a partial substitution could be performed) or
13653 ERROR_MARK_NODE if there was an error. */
13654 tree
13655 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
13656 tree in_decl)
13658 tree pattern;
13659 tree pack, packs = NULL_TREE;
13660 bool unsubstituted_packs = false;
13661 int i, len = -1;
13662 tree result;
13663 bool need_local_specializations = false;
13664 int levels;
13666 gcc_assert (PACK_EXPANSION_P (t));
13667 pattern = PACK_EXPANSION_PATTERN (t);
13669 /* Add in any args remembered from an earlier partial instantiation. */
13670 args = add_extra_args (PACK_EXPANSION_EXTRA_ARGS (t), args, complain, in_decl);
13672 levels = TMPL_ARGS_DEPTH (args);
13674 /* Determine the argument packs that will instantiate the parameter
13675 packs used in the expansion expression. While we're at it,
13676 compute the number of arguments to be expanded and make sure it
13677 is consistent. */
13678 for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
13679 pack = TREE_CHAIN (pack))
13681 tree parm_pack = TREE_VALUE (pack);
13682 tree arg_pack = NULL_TREE;
13683 tree orig_arg = NULL_TREE;
13684 int level = 0;
13686 if (TREE_CODE (parm_pack) == BASES)
13688 gcc_assert (parm_pack == pattern);
13689 tree type = tsubst (BASES_TYPE (parm_pack), args, complain, in_decl);
13690 if (BASES_DIRECT (parm_pack))
13691 return calculate_direct_bases (type, complain);
13692 else
13693 return calculate_bases (type, complain);
13695 else if (builtin_pack_call_p (parm_pack))
13697 if (parm_pack != pattern)
13699 if (complain & tf_error)
13700 sorry ("%qE is not the entire pattern of the pack expansion",
13701 parm_pack);
13702 return error_mark_node;
13704 return expand_builtin_pack_call (parm_pack, args,
13705 complain, in_decl);
13707 else if (TREE_CODE (parm_pack) == PARM_DECL)
13709 /* We know we have correct local_specializations if this
13710 expansion is at function scope, or if we're dealing with a
13711 local parameter in a requires expression; for the latter,
13712 tsubst_requires_expr set it up appropriately. */
13713 if (PACK_EXPANSION_LOCAL_P (t) || CONSTRAINT_VAR_P (parm_pack))
13714 arg_pack = retrieve_local_specialization (parm_pack);
13715 else
13716 /* We can't rely on local_specializations for a parameter
13717 name used later in a function declaration (such as in a
13718 late-specified return type). Even if it exists, it might
13719 have the wrong value for a recursive call. */
13720 need_local_specializations = true;
13722 if (!arg_pack)
13724 /* This parameter pack was used in an unevaluated context. Just
13725 make a dummy decl, since it's only used for its type. */
13726 ++cp_unevaluated_operand;
13727 arg_pack = tsubst_decl (parm_pack, args, complain);
13728 --cp_unevaluated_operand;
13729 if (arg_pack && DECL_PACK_P (arg_pack))
13730 /* Partial instantiation of the parm_pack, we can't build
13731 up an argument pack yet. */
13732 arg_pack = NULL_TREE;
13733 else
13734 arg_pack = make_fnparm_pack (arg_pack);
13736 else if (DECL_PACK_P (arg_pack))
13737 /* This argument pack isn't fully instantiated yet. */
13738 arg_pack = NULL_TREE;
13740 else if (is_capture_proxy (parm_pack))
13742 arg_pack = retrieve_local_specialization (parm_pack);
13743 if (DECL_PACK_P (arg_pack))
13744 arg_pack = NULL_TREE;
13746 else
13748 int idx;
13749 template_parm_level_and_index (parm_pack, &level, &idx);
13750 if (level <= levels)
13751 arg_pack = TMPL_ARG (args, level, idx);
13753 if (arg_pack && TREE_CODE (arg_pack) == TEMPLATE_TYPE_PARM
13754 && TEMPLATE_TYPE_PARAMETER_PACK (arg_pack))
13755 arg_pack = NULL_TREE;
13758 orig_arg = arg_pack;
13759 if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
13760 arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
13762 if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
13763 /* This can only happen if we forget to expand an argument
13764 pack somewhere else. Just return an error, silently. */
13766 result = make_tree_vec (1);
13767 TREE_VEC_ELT (result, 0) = error_mark_node;
13768 return result;
13771 if (arg_pack)
13773 int my_len =
13774 TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
13776 /* Don't bother trying to do a partial substitution with
13777 incomplete packs; we'll try again after deduction. */
13778 if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
13779 return t;
13781 if (len < 0)
13782 len = my_len;
13783 else if (len != my_len)
13785 if (!(complain & tf_error))
13786 /* Fail quietly. */;
13787 else if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
13788 error ("mismatched argument pack lengths while expanding %qT",
13789 pattern);
13790 else
13791 error ("mismatched argument pack lengths while expanding %qE",
13792 pattern);
13793 return error_mark_node;
13796 /* Keep track of the parameter packs and their corresponding
13797 argument packs. */
13798 packs = tree_cons (parm_pack, arg_pack, packs);
13799 TREE_TYPE (packs) = orig_arg;
13801 else
13803 /* We can't substitute for this parameter pack. We use a flag as
13804 well as the missing_level counter because function parameter
13805 packs don't have a level. */
13806 gcc_assert (processing_template_decl || is_auto (parm_pack));
13807 unsubstituted_packs = true;
13811 /* If the expansion is just T..., return the matching argument pack, unless
13812 we need to call convert_from_reference on all the elements. This is an
13813 important optimization; see c++/68422. */
13814 if (!unsubstituted_packs
13815 && TREE_PURPOSE (packs) == pattern)
13817 tree args = ARGUMENT_PACK_ARGS (TREE_VALUE (packs));
13819 /* If the argument pack is a single pack expansion, pull it out. */
13820 if (TREE_VEC_LENGTH (args) == 1
13821 && pack_expansion_args_count (args))
13823 tree arg = TREE_VEC_ELT (args, 0);
13824 if (PACK_EXPANSION_SIZEOF_P (t)
13825 && !TEMPLATE_PARM_P (PACK_EXPANSION_PATTERN (arg)))
13826 /* Except if this isn't a simple sizeof...(T) which gets sZ
13827 mangling, keep the TREE_VEC to get sP mangling. */;
13828 else
13829 return TREE_VEC_ELT (args, 0);
13832 /* Types need no adjustment, nor does sizeof..., and if we still have
13833 some pack expansion args we won't do anything yet. */
13834 if (TREE_CODE (t) == TYPE_PACK_EXPANSION
13835 || PACK_EXPANSION_SIZEOF_P (t)
13836 || pack_expansion_args_count (args))
13837 return args;
13838 /* Also optimize expression pack expansions if we can tell that the
13839 elements won't have reference type. */
13840 tree type = TREE_TYPE (pattern);
13841 if (type && !TYPE_REF_P (type)
13842 && !PACK_EXPANSION_P (type)
13843 && !WILDCARD_TYPE_P (type))
13844 return args;
13845 /* Otherwise use the normal path so we get convert_from_reference. */
13848 /* We cannot expand this expansion expression, because we don't have
13849 all of the argument packs we need. */
13850 if (use_pack_expansion_extra_args_p (t, packs, len, unsubstituted_packs))
13852 /* We got some full packs, but we can't substitute them in until we
13853 have values for all the packs. So remember these until then. */
13855 t = make_pack_expansion (pattern, complain);
13856 PACK_EXPANSION_EXTRA_ARGS (t)
13857 = build_extra_args (pattern, args, complain);
13858 return t;
13861 /* If NEED_LOCAL_SPECIALIZATIONS then we're in a late-specified return
13862 type, so create our own local specializations map; the current map is
13863 either NULL or (in the case of recursive unification) might have
13864 bindings that we don't want to use or alter. */
13865 local_specialization_stack lss (need_local_specializations
13866 ? lss_blank : lss_nop);
13868 if (unsubstituted_packs)
13870 /* There were no real arguments, we're just replacing a parameter
13871 pack with another version of itself. Substitute into the
13872 pattern and return a PACK_EXPANSION_*. The caller will need to
13873 deal with that. */
13874 if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
13875 result = tsubst_expr (pattern, args, complain, in_decl);
13876 else
13877 result = tsubst (pattern, args, complain, in_decl);
13878 result = make_pack_expansion (result, complain);
13879 if (result == error_mark_node)
13880 return error_mark_node;
13881 PACK_EXPANSION_LOCAL_P (result) = PACK_EXPANSION_LOCAL_P (t);
13882 PACK_EXPANSION_SIZEOF_P (result) = PACK_EXPANSION_SIZEOF_P (t);
13883 if (PACK_EXPANSION_AUTO_P (t))
13885 /* This is a fake auto... pack expansion created in add_capture with
13886 _PACKS that don't appear in the pattern. Copy one over. */
13887 packs = PACK_EXPANSION_PARAMETER_PACKS (t);
13888 pack = retrieve_local_specialization (TREE_VALUE (packs));
13889 gcc_checking_assert (DECL_PACK_P (pack));
13890 PACK_EXPANSION_PARAMETER_PACKS (result)
13891 = build_tree_list (NULL_TREE, pack);
13892 PACK_EXPANSION_AUTO_P (result) = true;
13894 return result;
13897 gcc_assert (len >= 0);
13899 /* For each argument in each argument pack, substitute into the
13900 pattern. */
13901 result = make_tree_vec (len);
13902 tree elem_args = copy_template_args (args);
13903 for (i = 0; i < len; ++i)
13905 t = gen_elem_of_pack_expansion_instantiation (pattern, packs,
13907 elem_args, complain,
13908 in_decl);
13909 TREE_VEC_ELT (result, i) = t;
13910 if (t == error_mark_node)
13912 result = error_mark_node;
13913 break;
13917 /* Update ARGS to restore the substitution from parameter packs to
13918 their argument packs. */
13919 for (pack = packs; pack; pack = TREE_CHAIN (pack))
13921 tree parm = TREE_PURPOSE (pack);
13923 if (TREE_CODE (parm) == PARM_DECL
13924 || VAR_P (parm)
13925 || TREE_CODE (parm) == FIELD_DECL)
13926 register_local_specialization (TREE_TYPE (pack), parm);
13927 else
13929 int idx, level;
13931 if (TREE_VALUE (pack) == NULL_TREE)
13932 continue;
13934 template_parm_level_and_index (parm, &level, &idx);
13936 /* Update the corresponding argument. */
13937 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
13938 TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
13939 TREE_TYPE (pack);
13940 else
13941 TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
13945 /* If the dependent pack arguments were such that we end up with only a
13946 single pack expansion again, there's no need to keep it in a TREE_VEC. */
13947 if (len == 1 && TREE_CODE (result) == TREE_VEC
13948 && PACK_EXPANSION_P (TREE_VEC_ELT (result, 0)))
13949 return TREE_VEC_ELT (result, 0);
13951 return result;
13954 /* Make an argument pack out of the TREE_VEC VEC. */
13956 static tree
13957 make_argument_pack (tree vec)
13959 tree pack;
13961 if (TYPE_P (TREE_VEC_ELT (vec, 0)))
13962 pack = cxx_make_type (TYPE_ARGUMENT_PACK);
13963 else
13965 pack = make_node (NONTYPE_ARGUMENT_PACK);
13966 TREE_CONSTANT (pack) = 1;
13968 ARGUMENT_PACK_ARGS (pack) = vec;
13969 return pack;
13972 /* Return an exact copy of template args T that can be modified
13973 independently. */
13975 static tree
13976 copy_template_args (tree t)
13978 if (t == error_mark_node)
13979 return t;
13981 int len = TREE_VEC_LENGTH (t);
13982 tree new_vec = make_tree_vec (len);
13984 for (int i = 0; i < len; ++i)
13986 tree elt = TREE_VEC_ELT (t, i);
13987 if (elt && TREE_CODE (elt) == TREE_VEC)
13988 elt = copy_template_args (elt);
13989 TREE_VEC_ELT (new_vec, i) = elt;
13992 NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_vec)
13993 = NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
13995 return new_vec;
13998 /* Substitute ARGS into the *_ARGUMENT_PACK orig_arg. */
14000 tree
14001 tsubst_argument_pack (tree orig_arg, tree args, tsubst_flags_t complain,
14002 tree in_decl)
14004 /* This flag is used only during deduction, and we don't expect to
14005 substitute such ARGUMENT_PACKs. */
14006 gcc_assert (!ARGUMENT_PACK_INCOMPLETE_P (orig_arg));
14008 /* Substitute into each of the arguments. */
14009 tree pack_args = tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
14010 args, complain, in_decl);
14011 if (pack_args == error_mark_node)
14012 return error_mark_node;
14014 if (pack_args == ARGUMENT_PACK_ARGS (orig_arg))
14015 return orig_arg;
14017 /* If we're substituting into a generic ARGUMENT_PACK for a variadic
14018 template parameter, we might be able to avoid allocating a new
14019 ARGUMENT_PACK and reuse the corresponding ARGUMENT_PACK from ARGS
14020 if the substituted result is identical to it. */
14021 if (tree parm = template_arg_to_parm (orig_arg))
14023 int level, index;
14024 template_parm_level_and_index (parm, &level, &index);
14025 if (TMPL_ARGS_DEPTH (args) >= level)
14026 if (tree arg = TMPL_ARG (args, level, index))
14027 if (TREE_CODE (arg) == TREE_CODE (orig_arg)
14028 && ARGUMENT_PACK_ARGS (arg) == pack_args)
14030 gcc_assert (!ARGUMENT_PACK_INCOMPLETE_P (arg));
14031 return arg;
14035 tree new_arg;
14036 if (TYPE_P (orig_arg))
14038 new_arg = cxx_make_type (TREE_CODE (orig_arg));
14039 SET_TYPE_STRUCTURAL_EQUALITY (new_arg);
14041 else
14043 new_arg = make_node (TREE_CODE (orig_arg));
14044 TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
14046 ARGUMENT_PACK_ARGS (new_arg) = pack_args;
14047 return new_arg;
14050 /* Substitute ARGS into the vector or list of template arguments T. */
14052 tree
14053 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
14055 if (t == error_mark_node)
14056 return error_mark_node;
14058 /* In "sizeof(X<I>)" we need to evaluate "I". */
14059 cp_evaluated ev;
14061 const int len = TREE_VEC_LENGTH (t);
14062 tree *elts = XALLOCAVEC (tree, len);
14063 int expanded_len_adjust = 0;
14065 /* True iff the substituted result is identical to T. */
14066 bool const_subst_p = true;
14068 for (int i = 0; i < len; i++)
14070 tree orig_arg = TREE_VEC_ELT (t, i);
14071 tree new_arg;
14073 if (!orig_arg)
14074 new_arg = NULL_TREE;
14075 else if (TREE_CODE (orig_arg) == TREE_VEC)
14076 new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
14077 else if (PACK_EXPANSION_P (orig_arg))
14079 /* Substitute into an expansion expression. */
14080 new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
14082 if (TREE_CODE (new_arg) == TREE_VEC)
14083 /* Add to the expanded length adjustment the number of
14084 expanded arguments. We subtract one from this
14085 measurement, because the argument pack expression
14086 itself is already counted as 1 in
14087 LEN. EXPANDED_LEN_ADJUST can actually be negative, if
14088 the argument pack is empty. */
14089 expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
14091 else if (ARGUMENT_PACK_P (orig_arg))
14092 new_arg = tsubst_argument_pack (orig_arg, args, complain, in_decl);
14093 else
14094 new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
14096 if (new_arg == error_mark_node)
14097 return error_mark_node;
14099 elts[i] = new_arg;
14100 if (new_arg != orig_arg)
14101 const_subst_p = false;
14104 if (const_subst_p)
14105 return t;
14107 tree maybe_reuse = NULL_TREE;
14109 /* If ARGS and T are both multi-level, the substituted result may be
14110 identical to ARGS. */
14111 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (t)
14112 && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args)
14113 && TMPL_ARGS_DEPTH (t) == TMPL_ARGS_DEPTH (args))
14114 maybe_reuse = args;
14115 /* If T appears to be a vector of generic template arguments, the
14116 substituted result may be identical to the corresponding level
14117 from ARGS. */
14118 else if (tree parm = template_arg_to_parm (TREE_VEC_ELT (t, 0)))
14120 int level, index;
14121 template_parm_level_and_index (parm, &level, &index);
14122 if (index == 0 && TMPL_ARGS_DEPTH (args) >= level)
14123 maybe_reuse = TMPL_ARGS_LEVEL (args, level);
14126 /* If the substituted result is identical to MAYBE_REUSE, return
14127 it and avoid allocating a new TREE_VEC, as an optimization. */
14128 if (maybe_reuse != NULL_TREE
14129 && TREE_VEC_LENGTH (maybe_reuse) == len
14130 && std::equal (elts, elts+len, TREE_VEC_BEGIN (maybe_reuse)))
14131 return maybe_reuse;
14133 /* If T consists of only a pack expansion for which substitution yielded
14134 a TREE_VEC of the expanded elements, then reuse that TREE_VEC instead
14135 of effectively making a copy. */
14136 if (len == 1
14137 && PACK_EXPANSION_P (TREE_VEC_ELT (t, 0))
14138 && TREE_CODE (elts[0]) == TREE_VEC)
14139 return elts[0];
14141 /* Make space for the expanded arguments coming from template
14142 argument packs. */
14143 tree r = make_tree_vec (len + expanded_len_adjust);
14144 /* T can contain TREE_VECs. That happens if T contains the
14145 arguments for a member template.
14146 In that case each TREE_VEC in T represents a level of template
14147 arguments, and T won't carry any non defaulted argument count.
14148 It will rather be the nested TREE_VECs that will carry one.
14149 In other words, T carries a non defaulted argument count only
14150 if it doesn't contain any nested TREE_VEC. */
14151 if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (t))
14153 int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
14154 count += expanded_len_adjust;
14155 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (r, count);
14158 int out = 0;
14159 for (int i = 0; i < len; i++)
14161 tree orig_arg = TREE_VEC_ELT (t, i);
14162 if (orig_arg
14163 && PACK_EXPANSION_P (orig_arg)
14164 && TREE_CODE (elts[i]) == TREE_VEC)
14166 /* Now expand the template argument pack "in place". */
14167 for (int idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
14168 TREE_VEC_ELT (r, out) = TREE_VEC_ELT (elts[i], idx);
14170 else
14172 TREE_VEC_ELT (r, out) = elts[i];
14173 out++;
14176 gcc_assert (out == TREE_VEC_LENGTH (r));
14178 return r;
14181 /* Substitute ARGS into one level PARMS of template parameters. */
14183 static tree
14184 tsubst_template_parms_level (tree parms, tree args, tsubst_flags_t complain)
14186 if (parms == error_mark_node)
14187 return error_mark_node;
14189 tree new_vec = make_tree_vec (TREE_VEC_LENGTH (parms));
14191 for (int i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
14193 tree tuple = TREE_VEC_ELT (parms, i);
14195 if (tuple == error_mark_node)
14196 continue;
14198 TREE_VEC_ELT (new_vec, i) =
14199 tsubst_template_parm (tuple, args, complain);
14202 return new_vec;
14205 /* Return the result of substituting ARGS into the template parameters
14206 given by PARMS. If there are m levels of ARGS and m + n levels of
14207 PARMS, then the result will contain n levels of PARMS. For
14208 example, if PARMS is `template <class T> template <class U>
14209 template <T*, U, class V>' and ARGS is {{int}, {double}} then the
14210 result will be `template <int*, double, class V>'. */
14212 static tree
14213 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
14215 tree r = NULL_TREE;
14216 tree* new_parms;
14218 /* When substituting into a template, we must set
14219 PROCESSING_TEMPLATE_DECL as the template parameters may be
14220 dependent if they are based on one-another, and the dependency
14221 predicates are short-circuit outside of templates. */
14222 ++processing_template_decl;
14224 for (new_parms = &r;
14225 parms && TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
14226 new_parms = &(TREE_CHAIN (*new_parms)),
14227 parms = TREE_CHAIN (parms))
14229 tree new_vec = tsubst_template_parms_level (TREE_VALUE (parms),
14230 args, complain);
14231 *new_parms =
14232 tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
14233 - TMPL_ARGS_DEPTH (args)),
14234 new_vec, NULL_TREE);
14235 TEMPLATE_PARMS_CONSTRAINTS (*new_parms)
14236 = TEMPLATE_PARMS_CONSTRAINTS (parms);
14239 --processing_template_decl;
14241 return r;
14244 /* Return the result of substituting ARGS into one template parameter
14245 given by T. T Must be a TREE_LIST which TREE_VALUE is the template
14246 parameter and which TREE_PURPOSE is the default argument of the
14247 template parameter. */
14249 static tree
14250 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
14252 tree default_value, parm_decl;
14254 if (args == NULL_TREE
14255 || t == NULL_TREE
14256 || t == error_mark_node)
14257 return t;
14259 gcc_assert (TREE_CODE (t) == TREE_LIST);
14261 default_value = TREE_PURPOSE (t);
14262 parm_decl = TREE_VALUE (t);
14264 parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
14265 if (TREE_CODE (parm_decl) == PARM_DECL
14266 && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
14267 parm_decl = error_mark_node;
14268 default_value = tsubst_template_arg (default_value, args,
14269 complain, NULL_TREE);
14271 tree r = build_tree_list (default_value, parm_decl);
14272 TEMPLATE_PARM_CONSTRAINTS (r) = TEMPLATE_PARM_CONSTRAINTS (t);
14273 return r;
14276 /* Substitute in-place the TEMPLATE_PARM_CONSTRAINTS of each template
14277 parameter in PARMS for sake of declaration matching. */
14279 static void
14280 tsubst_each_template_parm_constraints (tree parms, tree args,
14281 tsubst_flags_t complain)
14283 ++processing_template_decl;
14284 for (; parms; parms = TREE_CHAIN (parms))
14286 tree level = TREE_VALUE (parms);
14287 for (tree parm : tree_vec_range (level))
14288 TEMPLATE_PARM_CONSTRAINTS (parm)
14289 = tsubst_constraint (TEMPLATE_PARM_CONSTRAINTS (parm), args,
14290 complain, NULL_TREE);
14292 --processing_template_decl;
14295 /* Map from a FUNCTION_DECL to a vec of default argument instantiations,
14296 indexed in reverse order of the parameters. */
14298 static GTY((cache)) hash_table<tree_vec_map_cache_hasher> *defarg_inst;
14300 /* Return a reference to the vec* of defarg insts for FN. */
14302 static vec<tree,va_gc> *&
14303 defarg_insts_for (tree fn)
14305 if (!defarg_inst)
14306 defarg_inst = hash_table<tree_vec_map_cache_hasher>::create_ggc (13);
14307 tree_vec_map in = { { fn }, nullptr };
14308 tree_vec_map **slot
14309 = defarg_inst->find_slot_with_hash (&in, DECL_UID (fn), INSERT);
14310 if (!*slot)
14312 *slot = ggc_alloc<tree_vec_map> ();
14313 **slot = in;
14315 return (*slot)->to;
14318 /* Substitute into the default argument ARG (a default argument for
14319 FN), which has the indicated TYPE. */
14321 tree
14322 tsubst_default_argument (tree fn, int parmnum, tree type, tree arg,
14323 tsubst_flags_t complain)
14325 int errs = errorcount + sorrycount;
14327 /* This can happen in invalid code. */
14328 if (TREE_CODE (arg) == DEFERRED_PARSE)
14329 return arg;
14331 /* Shortcut {}. */
14332 if (BRACE_ENCLOSED_INITIALIZER_P (arg)
14333 && CONSTRUCTOR_NELTS (arg) == 0)
14334 return arg;
14336 tree parm = FUNCTION_FIRST_USER_PARM (fn);
14337 parm = chain_index (parmnum, parm);
14338 tree parmtype = TREE_TYPE (parm);
14339 if (DECL_BY_REFERENCE (parm))
14340 parmtype = TREE_TYPE (parmtype);
14341 if (parmtype == error_mark_node)
14342 return error_mark_node;
14344 gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, parmtype));
14346 /* Remember the location of the pointer to the vec rather than the location
14347 of the particular element, in case the vec grows in tsubst_expr. */
14348 vec<tree,va_gc> *&defs = defarg_insts_for (fn);
14349 /* Index in reverse order to avoid allocating space for initial parameters
14350 that don't have default arguments. */
14351 unsigned ridx = list_length (parm);
14352 if (vec_safe_length (defs) < ridx)
14353 vec_safe_grow_cleared (defs, ridx);
14354 else if (tree inst = (*defs)[ridx - 1])
14355 return inst;
14357 /* This default argument came from a template. Instantiate the
14358 default argument here, not in tsubst. In the case of
14359 something like:
14361 template <class T>
14362 struct S {
14363 static T t();
14364 void f(T = t());
14367 we must be careful to do name lookup in the scope of S<T>,
14368 rather than in the current class. */
14369 push_to_top_level ();
14370 push_access_scope (fn);
14371 push_deferring_access_checks (dk_no_deferred);
14372 /* So in_immediate_context knows this is a default argument. */
14373 begin_scope (sk_function_parms, fn);
14374 start_lambda_scope (parm);
14376 /* The default argument expression may cause implicitly defined
14377 member functions to be synthesized, which will result in garbage
14378 collection. We must treat this situation as if we were within
14379 the body of function so as to avoid collecting live data on the
14380 stack. */
14381 ++function_depth;
14382 arg = tsubst_expr (arg, DECL_TI_ARGS (fn), complain, NULL_TREE);
14383 --function_depth;
14385 finish_lambda_scope ();
14387 /* Make sure the default argument is reasonable. */
14388 arg = check_default_argument (type, arg, complain);
14390 if (errorcount+sorrycount > errs
14391 && (complain & tf_warning_or_error))
14392 inform (input_location,
14393 " when instantiating default argument for call to %qD", fn);
14395 leave_scope ();
14396 pop_deferring_access_checks ();
14397 pop_access_scope (fn);
14398 pop_from_top_level ();
14400 if (arg != error_mark_node && !cp_unevaluated_operand)
14401 (*defs)[ridx - 1] = arg;
14403 return arg;
14406 /* Substitute into all the default arguments for FN. */
14408 static void
14409 tsubst_default_arguments (tree fn, tsubst_flags_t complain)
14411 tree arg;
14412 tree tmpl_args;
14414 tmpl_args = DECL_TI_ARGS (fn);
14416 /* If this function is not yet instantiated, we certainly don't need
14417 its default arguments. */
14418 if (uses_template_parms (tmpl_args))
14419 return;
14420 /* Don't do this again for clones. */
14421 if (DECL_CLONED_FUNCTION_P (fn))
14422 return;
14424 int i = 0;
14425 for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
14426 arg;
14427 arg = TREE_CHAIN (arg), ++i)
14428 if (TREE_PURPOSE (arg))
14429 TREE_PURPOSE (arg) = tsubst_default_argument (fn, i,
14430 TREE_VALUE (arg),
14431 TREE_PURPOSE (arg),
14432 complain);
14435 /* Hash table mapping a FUNCTION_DECL to its dependent explicit-specifier. */
14436 static GTY((cache)) decl_tree_cache_map *explicit_specifier_map;
14438 /* Store a pair to EXPLICIT_SPECIFIER_MAP. */
14440 void
14441 store_explicit_specifier (tree v, tree t)
14443 if (!explicit_specifier_map)
14444 explicit_specifier_map = decl_tree_cache_map::create_ggc (37);
14445 DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (v) = true;
14446 explicit_specifier_map->put (v, t);
14449 /* Lookup an element in EXPLICIT_SPECIFIER_MAP. */
14451 tree
14452 lookup_explicit_specifier (tree v)
14454 return *explicit_specifier_map->get (v);
14457 /* Given T, a FUNCTION_TYPE or METHOD_TYPE, construct and return a corresponding
14458 FUNCTION_TYPE or METHOD_TYPE whose return type is RETURN_TYPE, argument types
14459 are ARG_TYPES, and exception specification is RAISES, and otherwise is
14460 identical to T. */
14462 static tree
14463 rebuild_function_or_method_type (tree t, tree args, tree return_type,
14464 tree arg_types, tree raises,
14465 tsubst_flags_t complain)
14467 gcc_assert (FUNC_OR_METHOD_TYPE_P (t));
14469 tree new_type;
14470 if (TREE_CODE (t) == FUNCTION_TYPE)
14472 new_type = build_function_type (return_type, arg_types);
14473 new_type = apply_memfn_quals (new_type, type_memfn_quals (t));
14475 else
14477 tree r = TREE_TYPE (TREE_VALUE (arg_types));
14478 /* Don't pick up extra function qualifiers from the basetype. */
14479 r = cp_build_qualified_type (r, type_memfn_quals (t), complain);
14480 if (! MAYBE_CLASS_TYPE_P (r))
14482 /* [temp.deduct]
14484 Type deduction may fail for any of the following
14485 reasons:
14487 -- Attempting to create "pointer to member of T" when T
14488 is not a class type. */
14489 if (complain & tf_error)
14490 error ("creating pointer to member function of non-class type %qT",
14492 return error_mark_node;
14495 new_type = build_method_type_directly (r, return_type,
14496 TREE_CHAIN (arg_types));
14498 if (!apply_late_template_attributes (&new_type, TYPE_ATTRIBUTES (t), 0,
14499 args, complain, NULL_TREE))
14500 return error_mark_node;
14502 cp_ref_qualifier rqual = type_memfn_rqual (t);
14503 bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
14504 return build_cp_fntype_variant (new_type, rqual, raises, late_return_type_p);
14507 /* Check if the function type of DECL, a FUNCTION_DECL, agrees with the type of
14508 each of its formal parameters. If there is a disagreement then rebuild
14509 DECL's function type according to its formal parameter types, as part of a
14510 resolution for Core issues 1001/1322. */
14512 static void
14513 maybe_rebuild_function_decl_type (tree decl, tree args)
14515 bool function_type_needs_rebuilding = false;
14516 if (tree parm_list = FUNCTION_FIRST_USER_PARM (decl))
14518 tree parm_type_list = FUNCTION_FIRST_USER_PARMTYPE (decl);
14519 while (parm_type_list && parm_type_list != void_list_node)
14521 tree parm_type = TREE_VALUE (parm_type_list);
14522 tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
14523 if (!same_type_p (parm_type, formal_parm_type_unqual))
14525 function_type_needs_rebuilding = true;
14526 break;
14529 parm_list = DECL_CHAIN (parm_list);
14530 parm_type_list = TREE_CHAIN (parm_type_list);
14534 if (!function_type_needs_rebuilding)
14535 return;
14537 const tree fntype = TREE_TYPE (decl);
14538 tree parm_list = DECL_ARGUMENTS (decl);
14539 tree old_parm_type_list = TYPE_ARG_TYPES (fntype);
14540 tree new_parm_type_list = NULL_TREE;
14541 tree *q = &new_parm_type_list;
14542 for (int skip = num_artificial_parms_for (decl); skip > 0; skip--)
14544 *q = copy_node (old_parm_type_list);
14545 parm_list = DECL_CHAIN (parm_list);
14546 old_parm_type_list = TREE_CHAIN (old_parm_type_list);
14547 q = &TREE_CHAIN (*q);
14549 while (old_parm_type_list && old_parm_type_list != void_list_node)
14551 *q = copy_node (old_parm_type_list);
14552 tree *new_parm_type = &TREE_VALUE (*q);
14553 tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
14554 if (!same_type_p (*new_parm_type, formal_parm_type_unqual))
14555 *new_parm_type = formal_parm_type_unqual;
14557 parm_list = DECL_CHAIN (parm_list);
14558 old_parm_type_list = TREE_CHAIN (old_parm_type_list);
14559 q = &TREE_CHAIN (*q);
14561 if (old_parm_type_list == void_list_node)
14562 *q = void_list_node;
14564 TREE_TYPE (decl)
14565 = rebuild_function_or_method_type (fntype, args,
14566 TREE_TYPE (fntype), new_parm_type_list,
14567 TYPE_RAISES_EXCEPTIONS (fntype), tf_none);
14570 /* Subroutine of tsubst_decl for the case when T is a FUNCTION_DECL. */
14572 static tree
14573 tsubst_function_decl (tree t, tree args, tsubst_flags_t complain,
14574 tree lambda_fntype, bool use_spec_table = true)
14576 tree gen_tmpl = NULL_TREE, argvec = NULL_TREE;
14577 hashval_t hash = 0;
14578 tree in_decl = t;
14580 /* Nobody should be tsubst'ing into non-template functions. */
14581 gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE
14582 || DECL_LOCAL_DECL_P (t));
14584 if (DECL_LOCAL_DECL_P (t))
14586 if (tree spec = retrieve_local_specialization (t))
14587 return spec;
14589 else if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
14591 /* If T is not dependent, just return it. */
14592 if (!uses_template_parms (DECL_TI_ARGS (t))
14593 && !LAMBDA_FUNCTION_P (t))
14594 return t;
14596 /* A non-templated friend doesn't get DECL_TEMPLATE_INFO. */
14597 if (non_templated_friend_p (t))
14598 goto friend_case;
14600 /* Calculate the most general template of which R is a
14601 specialization. */
14602 gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
14604 /* We're substituting a lambda function under tsubst_lambda_expr but not
14605 directly from it; find the matching function we're already inside.
14606 But don't do this if T is a generic lambda with a single level of
14607 template parms, as in that case we're doing a normal instantiation. */
14608 if (LAMBDA_FUNCTION_P (t) && !lambda_fntype
14609 && (!generic_lambda_fn_p (t)
14610 || TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)) > 1))
14611 return enclosing_instantiation_of (t);
14613 /* Calculate the complete set of arguments used to
14614 specialize R. */
14615 if (use_spec_table && !lambda_fntype)
14617 argvec = tsubst_template_args (DECL_TI_ARGS
14618 (DECL_TEMPLATE_RESULT
14619 (DECL_TI_TEMPLATE (t))),
14620 args, complain, in_decl);
14621 if (argvec == error_mark_node)
14622 return error_mark_node;
14624 /* Check to see if we already have this specialization. */
14625 hash = spec_hasher::hash (gen_tmpl, argvec);
14626 if (tree spec = retrieve_specialization (gen_tmpl, argvec, hash))
14627 /* The spec for these args might be a partial instantiation of the
14628 template, but here what we want is the FUNCTION_DECL. */
14629 return STRIP_TEMPLATE (spec);
14631 else
14632 argvec = args;
14634 else
14636 /* This special case arises when we have something like this:
14638 template <class T> struct S {
14639 friend void f<int>(int, double);
14642 Here, the DECL_TI_TEMPLATE for the friend declaration
14643 will be an IDENTIFIER_NODE. We are being called from
14644 tsubst_friend_function, and we want only to create a
14645 new decl (R) with appropriate types so that we can call
14646 determine_specialization. */
14647 friend_case:
14648 gen_tmpl = NULL_TREE;
14649 argvec = NULL_TREE;
14652 tree closure = (lambda_fntype ? TYPE_METHOD_BASETYPE (lambda_fntype)
14653 : NULL_TREE);
14654 tree ctx = closure ? closure : DECL_CONTEXT (t);
14655 bool member = ctx && TYPE_P (ctx);
14657 /* If this is a static or xobj lambda, remove the 'this' pointer added in
14658 tsubst_lambda_expr now that we know the closure type. */
14659 if (lambda_fntype && !DECL_IOBJ_MEMBER_FUNCTION_P (t))
14660 lambda_fntype = static_fn_type (lambda_fntype);
14662 if (member && !closure)
14663 ctx = tsubst_entering_scope (ctx, args, complain, t);
14665 tree type = (lambda_fntype ? lambda_fntype
14666 : tsubst (TREE_TYPE (t), args,
14667 complain | tf_fndecl_type, in_decl));
14668 if (type == error_mark_node)
14669 return error_mark_node;
14671 /* If we hit excessive deduction depth, the type is bogus even if
14672 it isn't error_mark_node, so don't build a decl. */
14673 if (excessive_deduction_depth)
14674 return error_mark_node;
14676 /* We do NOT check for matching decls pushed separately at this
14677 point, as they may not represent instantiations of this
14678 template, and in any case are considered separate under the
14679 discrete model. */
14680 tree r = copy_decl (t);
14681 DECL_USE_TEMPLATE (r) = 0;
14682 TREE_TYPE (r) = type;
14683 /* Clear out the mangled name and RTL for the instantiation. */
14684 SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
14685 SET_DECL_RTL (r, NULL);
14686 /* Leave DECL_INITIAL set on deleted instantiations. */
14687 if (!DECL_DELETED_FN (r))
14688 DECL_INITIAL (r) = NULL_TREE;
14689 DECL_CONTEXT (r) = ctx;
14690 set_instantiating_module (r);
14692 /* Handle explicit(dependent-expr). */
14693 if (DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (t))
14695 tree spec = lookup_explicit_specifier (t);
14696 spec = tsubst_expr (spec, args, complain, in_decl);
14697 spec = build_explicit_specifier (spec, complain);
14698 if (spec == error_mark_node)
14699 return error_mark_node;
14700 if (instantiation_dependent_expression_p (spec))
14701 store_explicit_specifier (r, spec);
14702 else
14704 DECL_NONCONVERTING_P (r) = (spec == boolean_true_node);
14705 DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (r) = false;
14709 /* OpenMP UDRs have the only argument a reference to the declared
14710 type. We want to diagnose if the declared type is a reference,
14711 which is invalid, but as references to references are usually
14712 quietly merged, diagnose it here. */
14713 if (DECL_OMP_DECLARE_REDUCTION_P (t))
14715 tree argtype
14716 = TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (t))));
14717 argtype = tsubst (argtype, args, complain, in_decl);
14718 if (TYPE_REF_P (argtype))
14719 error_at (DECL_SOURCE_LOCATION (t),
14720 "reference type %qT in "
14721 "%<#pragma omp declare reduction%>", argtype);
14722 if (strchr (IDENTIFIER_POINTER (DECL_NAME (t)), '~') == NULL)
14723 DECL_NAME (r) = omp_reduction_id (ERROR_MARK, DECL_NAME (t),
14724 argtype);
14727 if (member && DECL_CONV_FN_P (r))
14728 /* Type-conversion operator. Reconstruct the name, in
14729 case it's the name of one of the template's parameters. */
14730 DECL_NAME (r) = make_conv_op_name (TREE_TYPE (type));
14732 tree parms = DECL_ARGUMENTS (t);
14733 if (closure && DECL_IOBJ_MEMBER_FUNCTION_P (t))
14734 parms = DECL_CHAIN (parms);
14735 parms = tsubst (parms, args, complain, t);
14736 for (tree parm = parms; parm; parm = DECL_CHAIN (parm))
14737 DECL_CONTEXT (parm) = r;
14738 if (closure && DECL_IOBJ_MEMBER_FUNCTION_P (t))
14740 tree tparm = build_this_parm (r, closure, type_memfn_quals (type));
14741 DECL_NAME (tparm) = closure_identifier;
14742 DECL_CHAIN (tparm) = parms;
14743 parms = tparm;
14745 DECL_ARGUMENTS (r) = parms;
14746 DECL_RESULT (r) = NULL_TREE;
14748 maybe_rebuild_function_decl_type (r, args);
14750 TREE_STATIC (r) = 0;
14751 TREE_PUBLIC (r) = TREE_PUBLIC (t);
14752 DECL_EXTERNAL (r) = 1;
14753 /* If this is an instantiation of a function with internal
14754 linkage, we already know what object file linkage will be
14755 assigned to the instantiation. */
14756 DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
14757 DECL_DEFER_OUTPUT (r) = 0;
14758 DECL_CHAIN (r) = NULL_TREE;
14759 DECL_PENDING_INLINE_INFO (r) = 0;
14760 DECL_PENDING_INLINE_P (r) = 0;
14761 DECL_SAVED_TREE (r) = NULL_TREE;
14762 DECL_STRUCT_FUNCTION (r) = NULL;
14763 TREE_USED (r) = 0;
14764 /* We'll re-clone as appropriate in instantiate_template. */
14765 DECL_CLONED_FUNCTION (r) = NULL_TREE;
14767 /* If we aren't complaining now, return on error before we register
14768 the specialization so that we'll complain eventually. */
14769 if ((complain & tf_error) == 0
14770 && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
14771 && !grok_op_properties (r, /*complain=*/false))
14772 return error_mark_node;
14774 /* If we are looking at an xobj lambda, we might need to check the type of
14775 its xobj parameter. */
14776 if (LAMBDA_FUNCTION_P (r) && DECL_XOBJ_MEMBER_FUNCTION_P (r))
14778 tree closure_obj = DECL_CONTEXT (r);
14779 tree lambda_expr = CLASSTYPE_LAMBDA_EXPR (closure_obj);
14780 tree obj_param = TREE_TYPE (DECL_ARGUMENTS (r));
14782 if (!(LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (lambda_expr) != CPLD_NONE
14783 || LAMBDA_EXPR_CAPTURE_LIST (lambda_expr)))
14784 /* If a lambda has an empty capture clause, an xobj parameter of
14785 unrelated type is not an error. */;
14786 else if (dependent_type_p (obj_param))
14787 /* If we are coming from tsubst_lambda_expr we might not have
14788 substituted into our xobj parameter yet. We can't error out until
14789 we know what the type really is so do nothing...
14790 ...but if we are instantiating the call op for real and we don't
14791 have a real type then something has gone incredibly wrong. */
14792 gcc_assert (lambda_fntype);
14793 else
14795 /* We have a lambda with captures, and know the type of the xobj
14796 parameter, time to check it. */
14797 tree obj_param_type = TYPE_MAIN_VARIANT (non_reference (obj_param));
14798 if (!same_or_base_type_p (closure_obj, obj_param_type))
14800 /* This error does not emit when the lambda's call operator
14801 template is instantiated by taking its address, such as in
14802 the following case:
14804 auto f = [x = 0](this auto&&){};
14805 int (*fp)(int&) = &decltype(f)::operator();
14807 It only emits when explicitly calling the call operator with
14808 an explicit template parameter:
14810 template<typename T>
14811 struct S : T {
14812 using T::operator();
14813 operator int() const {return {};}
14816 auto s = S{[x = 0](this auto&&) {}};
14817 s.operator()<int>();
14819 This is due to resolve_address_of_overloaded_function being
14820 deficient at reporting candidates when overload resolution
14821 fails.
14823 This diagnostic will be active in the first case if/when
14824 resolve_address_of_overloaded_function is fixed to properly
14825 emit candidates upon failure to resolve to an overload. */
14826 if (complain & tf_error)
14827 error ("a lambda with captures may not have an explicit "
14828 "object parameter of an unrelated type");
14829 return error_mark_node;
14834 /* Associate the constraints directly with the instantiation. We
14835 don't substitute through the constraints; that's only done when
14836 they are checked. */
14837 if (tree ci = get_constraints (t))
14838 set_constraints (r, ci);
14840 if (DECL_FRIEND_CONTEXT (t))
14841 SET_DECL_FRIEND_CONTEXT (r,
14842 tsubst (DECL_FRIEND_CONTEXT (t),
14843 args, complain, in_decl));
14845 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14846 args, complain, in_decl))
14847 return error_mark_node;
14849 /* Set up the DECL_TEMPLATE_INFO for R. There's no need to do
14850 this in the special friend case mentioned above where
14851 GEN_TMPL is NULL. */
14852 if (gen_tmpl && !closure)
14854 DECL_TEMPLATE_INFO (r)
14855 = build_template_info (gen_tmpl, argvec);
14856 SET_DECL_IMPLICIT_INSTANTIATION (r);
14858 if (use_spec_table)
14860 tree new_r
14861 = register_specialization (r, gen_tmpl, argvec, false, hash);
14862 if (new_r != r)
14863 /* We instantiated this while substituting into
14864 the type earlier (template/friend54.C). */
14865 return new_r;
14868 /* We're not supposed to instantiate default arguments
14869 until they are called, for a template. But, for a
14870 declaration like:
14872 template <class T> void f ()
14873 { extern void g(int i = T()); }
14875 we should do the substitution when the template is
14876 instantiated. We handle the member function case in
14877 instantiate_class_template since the default arguments
14878 might refer to other members of the class. */
14879 if (!member
14880 && !PRIMARY_TEMPLATE_P (gen_tmpl)
14881 && !uses_template_parms (argvec))
14882 tsubst_default_arguments (r, complain);
14884 else if (DECL_LOCAL_DECL_P (r))
14886 if (!cp_unevaluated_operand)
14887 register_local_specialization (r, t);
14889 else
14890 DECL_TEMPLATE_INFO (r) = NULL_TREE;
14892 /* Copy the list of befriending classes. */
14893 for (tree *friends = &DECL_BEFRIENDING_CLASSES (r);
14894 *friends;
14895 friends = &TREE_CHAIN (*friends))
14897 *friends = copy_node (*friends);
14898 TREE_VALUE (*friends)
14899 = tsubst (TREE_VALUE (*friends), args, complain, in_decl);
14902 if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
14904 maybe_retrofit_in_chrg (r);
14905 if (DECL_CONSTRUCTOR_P (r) && !grok_ctor_properties (ctx, r))
14906 return error_mark_node;
14907 /* If this is an instantiation of a member template, clone it.
14908 If it isn't, that'll be handled by
14909 clone_constructors_and_destructors. */
14910 if (gen_tmpl && PRIMARY_TEMPLATE_P (gen_tmpl))
14911 clone_cdtor (r, /*update_methods=*/false);
14913 else if ((complain & tf_error) != 0
14914 && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
14915 && !grok_op_properties (r, /*complain=*/true))
14916 return error_mark_node;
14918 /* Possibly limit visibility based on template args. */
14919 DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
14920 if (DECL_VISIBILITY_SPECIFIED (t))
14922 DECL_VISIBILITY_SPECIFIED (r) = 0;
14923 DECL_ATTRIBUTES (r)
14924 = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
14926 determine_visibility (r);
14927 if (DECL_SECTION_NAME (t))
14928 set_decl_section_name (r, t);
14929 if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
14930 && COMPLETE_TYPE_P (DECL_CONTEXT (r))
14931 && !processing_template_decl)
14932 defaulted_late_check (r);
14934 if (flag_openmp)
14935 if (tree attr = lookup_attribute ("omp declare variant base",
14936 DECL_ATTRIBUTES (r)))
14937 omp_declare_variant_finalize (r, attr);
14939 return r;
14942 /* Subroutine of tsubst_decl for the case when T is a TEMPLATE_DECL. */
14944 static tree
14945 tsubst_template_decl (tree t, tree args, tsubst_flags_t complain,
14946 tree lambda_fntype, tree lambda_tparms)
14948 /* We can get here when processing a member function template,
14949 member class template, or template template parameter. */
14950 tree decl = DECL_TEMPLATE_RESULT (t);
14951 tree in_decl = t;
14952 tree spec;
14953 tree tmpl_args;
14954 tree full_args = NULL_TREE;
14955 tree r;
14956 hashval_t hash = 0;
14958 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
14960 /* Template template parameter is treated here. */
14961 tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14962 if (new_type == error_mark_node)
14963 r = error_mark_node;
14964 /* If we get a real template back, return it. This can happen in
14965 the context of most_specialized_partial_spec. */
14966 else if (TREE_CODE (new_type) == TEMPLATE_DECL)
14967 r = new_type;
14968 else
14969 /* The new TEMPLATE_DECL was built in
14970 reduce_template_parm_level. */
14971 r = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (new_type);
14972 return r;
14975 if (!lambda_fntype)
14977 /* We might already have an instance of this template.
14978 The ARGS are for the surrounding class type, so the
14979 full args contain the tsubst'd args for the context,
14980 plus the innermost args from the template decl. */
14981 tmpl_args = DECL_CLASS_TEMPLATE_P (t)
14982 ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
14983 : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
14984 /* Because this is a template, the arguments will still be
14985 dependent, even after substitution. If
14986 PROCESSING_TEMPLATE_DECL is not set, the dependency
14987 predicates will short-circuit. */
14988 ++processing_template_decl;
14989 full_args = tsubst_template_args (tmpl_args, args,
14990 complain, in_decl);
14991 --processing_template_decl;
14992 if (full_args == error_mark_node)
14993 return error_mark_node;
14995 /* If this is a default template template argument,
14996 tsubst might not have changed anything. */
14997 if (full_args == tmpl_args)
14998 return t;
15000 hash = spec_hasher::hash (t, full_args);
15001 spec = retrieve_specialization (t, full_args, hash);
15002 if (spec != NULL_TREE)
15004 if (TYPE_P (spec))
15005 /* Type partial instantiations are stored as the type by
15006 lookup_template_class_1, not here as the template. */
15007 spec = CLASSTYPE_TI_TEMPLATE (spec);
15008 else if (TREE_CODE (spec) != TEMPLATE_DECL)
15009 spec = DECL_TI_TEMPLATE (spec);
15010 return spec;
15014 /* Make a new template decl. It will be similar to the
15015 original, but will record the current template arguments.
15016 We also create a new function declaration, which is just
15017 like the old one, but points to this new template, rather
15018 than the old one. */
15019 r = copy_decl (t);
15020 gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
15021 DECL_CHAIN (r) = NULL_TREE;
15023 // Build new template info linking to the original template decl.
15024 if (!lambda_fntype)
15026 DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
15027 SET_DECL_IMPLICIT_INSTANTIATION (r);
15029 else
15030 DECL_TEMPLATE_INFO (r) = NULL_TREE;
15032 /* The template parameters for this new template are all the
15033 template parameters for the old template, except the
15034 outermost level of parameters. */
15035 auto tparm_guard = make_temp_override (current_template_parms);
15036 DECL_TEMPLATE_PARMS (r)
15037 = current_template_parms
15038 = (lambda_tparms
15039 ? lambda_tparms
15040 : tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
15041 complain));
15043 bool class_p = false;
15044 tree inner = decl;
15045 ++processing_template_decl;
15046 if (TREE_CODE (inner) == FUNCTION_DECL)
15047 inner = tsubst_function_decl (inner, args, complain, lambda_fntype,
15048 /*use_spec_table=*/false);
15049 else
15051 if (TREE_CODE (inner) == TYPE_DECL && !TYPE_DECL_ALIAS_P (inner))
15053 class_p = true;
15054 inner = TREE_TYPE (inner);
15056 if (class_p)
15057 inner = tsubst_entering_scope (inner, args, complain, in_decl);
15058 else
15059 inner = tsubst_decl (inner, args, complain, /*use_spec_table=*/false);
15061 --processing_template_decl;
15062 if (inner == error_mark_node)
15063 return error_mark_node;
15065 if (class_p)
15067 /* For a partial specialization, we need to keep pointing to
15068 the primary template. */
15069 if (!DECL_TEMPLATE_SPECIALIZATION (t))
15071 CLASSTYPE_TI_TEMPLATE (inner) = r;
15072 CLASSTYPE_USE_TEMPLATE (inner) = 0;
15075 DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (inner);
15076 inner = TYPE_MAIN_DECL (inner);
15078 else if (lambda_fntype)
15080 tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (r));
15081 DECL_TEMPLATE_INFO (inner) = build_template_info (r, args);
15083 else
15085 DECL_TI_TEMPLATE (inner) = r;
15086 /* Set DECL_TI_ARGS to the full set of template arguments,
15087 which tsubst_function_decl / tsubst_decl didn't do due to
15088 use_spec_table=false. */
15089 DECL_TI_ARGS (inner) = full_args;
15090 DECL_TI_ARGS (r) = DECL_TI_ARGS (inner);
15093 DECL_TEMPLATE_RESULT (r) = inner;
15094 TREE_TYPE (r) = TREE_TYPE (inner);
15095 DECL_CONTEXT (r) = DECL_CONTEXT (inner);
15097 if (modules_p ())
15099 /* Propagate module information from the decl. */
15100 DECL_MODULE_EXPORT_P (r) = DECL_MODULE_EXPORT_P (inner);
15101 if (DECL_LANG_SPECIFIC (inner))
15102 /* If this is a constrained template, the above tsubst of
15103 inner can find the unconstrained template, which may have
15104 come from an import. This is ok, because we don't
15105 register this instantiation (see below). */
15106 gcc_checking_assert (!DECL_MODULE_IMPORT_P (inner)
15107 || (TEMPLATE_PARMS_CONSTRAINTS
15108 (DECL_TEMPLATE_PARMS (t))));
15111 DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
15112 DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
15114 if (PRIMARY_TEMPLATE_P (t))
15115 DECL_PRIMARY_TEMPLATE (r) = r;
15117 if (!lambda_fntype && !class_p)
15119 /* Record this non-type partial instantiation. */
15120 /* FIXME we'd like to always register the TEMPLATE_DECL, or always
15121 the DECL_TEMPLATE_RESULT, but it seems the modules code relies
15122 on this current behavior. */
15123 if (TREE_CODE (inner) == FUNCTION_DECL)
15124 register_specialization (r, t, full_args, false, hash);
15125 else
15126 register_specialization (inner, t, full_args, false, hash);
15129 return r;
15132 /* True if FN is the op() for a lambda in an uninstantiated template. */
15134 bool
15135 lambda_fn_in_template_p (tree fn)
15137 if (!fn || !LAMBDA_FUNCTION_P (fn))
15138 return false;
15139 tree closure = DECL_CONTEXT (fn);
15140 return CLASSTYPE_TEMPLATE_INFO (closure) != NULL_TREE;
15143 /* True if FN is the substitution (via tsubst_lambda_expr) of a function for
15144 which the above is true. */
15146 bool
15147 regenerated_lambda_fn_p (tree fn)
15149 if (!fn || !LAMBDA_FUNCTION_P (fn))
15150 return false;
15151 tree closure = DECL_CONTEXT (fn);
15152 tree lam = CLASSTYPE_LAMBDA_EXPR (closure);
15153 return LAMBDA_EXPR_REGEN_INFO (lam) != NULL_TREE;
15156 /* Return the LAMBDA_EXPR from which T was ultimately regenerated.
15157 If T is not a regenerated LAMBDA_EXPR, return T. */
15159 tree
15160 most_general_lambda (tree t)
15162 while (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
15163 t = TI_TEMPLATE (ti);
15164 return t;
15167 /* Return the set of template arguments used to regenerate the lambda T
15168 from its most general lambda. */
15170 tree
15171 lambda_regenerating_args (tree t)
15173 if (LAMBDA_FUNCTION_P (t))
15174 t = CLASSTYPE_LAMBDA_EXPR (DECL_CONTEXT (t));
15175 gcc_assert (TREE_CODE (t) == LAMBDA_EXPR);
15176 if (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
15177 return TI_ARGS (ti);
15178 else
15179 return NULL_TREE;
15182 /* We're instantiating a variable from template function TCTX. Return the
15183 corresponding current enclosing scope. We can match them up using
15184 DECL_SOURCE_LOCATION because lambdas only ever have one source location, and
15185 the DECL_SOURCE_LOCATION for a function instantiation is updated to match
15186 the template definition in regenerate_decl_from_template. */
15188 static tree
15189 enclosing_instantiation_of (tree tctx)
15191 tree fn = current_function_decl;
15193 /* We shouldn't ever need to do this for other artificial functions. */
15194 gcc_assert (!DECL_ARTIFICIAL (tctx) || LAMBDA_FUNCTION_P (tctx));
15196 for (; fn; fn = decl_function_context (fn))
15197 if (DECL_SOURCE_LOCATION (fn) == DECL_SOURCE_LOCATION (tctx))
15198 return fn;
15199 gcc_unreachable ();
15202 /* Substitute the ARGS into the T, which is a _DECL. Return the
15203 result of the substitution. Issue error and warning messages under
15204 control of COMPLAIN. The flag USE_SPEC_TABLE controls if we look up
15205 and insert into the specializations table or if we can assume it's
15206 the caller's responsibility; this is used by instantiate_template
15207 to avoid doing some redundant work. */
15209 static tree
15210 tsubst_decl (tree t, tree args, tsubst_flags_t complain,
15211 bool use_spec_table /* = true */)
15213 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
15214 location_t saved_loc;
15215 tree r = NULL_TREE;
15216 tree in_decl = t;
15217 hashval_t hash = 0;
15219 if (t == error_mark_node)
15220 return error_mark_node;
15222 /* Set the filename and linenumber to improve error-reporting. */
15223 saved_loc = input_location;
15224 input_location = DECL_SOURCE_LOCATION (t);
15226 switch (TREE_CODE (t))
15228 case TEMPLATE_DECL:
15229 r = tsubst_template_decl (t, args, complain,
15230 /*lambda_fntype=*/NULL_TREE,
15231 /*lambda_tparms=*/NULL_TREE);
15232 break;
15234 case FUNCTION_DECL:
15235 r = tsubst_function_decl (t, args, complain, /*lambda*/NULL_TREE,
15236 use_spec_table);
15237 break;
15239 case PARM_DECL:
15241 tree type = NULL_TREE;
15242 int i, len = 1;
15243 tree expanded_types = NULL_TREE;
15244 tree prev_r = NULL_TREE;
15245 tree first_r = NULL_TREE;
15247 if (DECL_PACK_P (t))
15249 /* If there is a local specialization that isn't a
15250 parameter pack, it means that we're doing a "simple"
15251 substitution from inside tsubst_pack_expansion. Just
15252 return the local specialization (which will be a single
15253 parm). */
15254 tree spec = retrieve_local_specialization (t);
15255 if (spec
15256 && TREE_CODE (spec) == PARM_DECL
15257 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
15258 RETURN (spec);
15260 /* Expand the TYPE_PACK_EXPANSION that provides the types for
15261 the parameters in this function parameter pack. */
15262 expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
15263 complain, in_decl);
15264 if (TREE_CODE (expanded_types) == TREE_VEC)
15266 len = TREE_VEC_LENGTH (expanded_types);
15268 /* Zero-length parameter packs are boring. Just substitute
15269 into the chain. */
15270 if (len == 0 && !cp_unevaluated_operand)
15271 RETURN (tsubst (TREE_CHAIN (t), args, complain,
15272 TREE_CHAIN (t)));
15274 else
15276 /* All we did was update the type. Make a note of that. */
15277 type = expanded_types;
15278 expanded_types = NULL_TREE;
15282 /* Loop through all of the parameters we'll build. When T is
15283 a function parameter pack, LEN is the number of expanded
15284 types in EXPANDED_TYPES; otherwise, LEN is 1. */
15285 r = NULL_TREE;
15286 for (i = 0; i < len; ++i)
15288 prev_r = r;
15289 r = copy_node (t);
15290 if (DECL_TEMPLATE_PARM_P (t))
15291 SET_DECL_TEMPLATE_PARM_P (r);
15293 if (expanded_types)
15294 /* We're on the Ith parameter of the function parameter
15295 pack. */
15297 /* Get the Ith type. */
15298 type = TREE_VEC_ELT (expanded_types, i);
15300 /* Rename the parameter to include the index. */
15301 DECL_NAME (r)
15302 = make_ith_pack_parameter_name (DECL_NAME (r), i);
15304 else if (!type)
15305 /* We're dealing with a normal parameter. */
15306 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15308 type = type_decays_to (type);
15309 TREE_TYPE (r) = type;
15310 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
15312 if (DECL_INITIAL (r))
15314 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
15315 DECL_INITIAL (r) = TREE_TYPE (r);
15316 else
15317 DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
15318 complain, in_decl);
15321 DECL_CONTEXT (r) = NULL_TREE;
15323 if (!DECL_TEMPLATE_PARM_P (r))
15324 DECL_ARG_TYPE (r) = type_passed_as (type);
15326 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
15327 args, complain, in_decl))
15328 return error_mark_node;
15330 /* Keep track of the first new parameter we
15331 generate. That's what will be returned to the
15332 caller. */
15333 if (!first_r)
15334 first_r = r;
15336 /* Build a proper chain of parameters when substituting
15337 into a function parameter pack. */
15338 if (prev_r)
15339 DECL_CHAIN (prev_r) = r;
15342 /* If cp_unevaluated_operand is set, we're just looking for a
15343 single dummy parameter, so don't keep going. */
15344 if (DECL_CHAIN (t) && !cp_unevaluated_operand)
15345 DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
15346 complain, DECL_CHAIN (t));
15348 /* FIRST_R contains the start of the chain we've built. */
15349 r = first_r;
15351 break;
15353 case FIELD_DECL:
15355 tree type = NULL_TREE;
15356 tree vec = NULL_TREE;
15357 tree expanded_types = NULL_TREE;
15358 int len = 1;
15360 if (PACK_EXPANSION_P (TREE_TYPE (t)))
15362 /* This field is a lambda capture pack. Return a TREE_VEC of
15363 the expanded fields to instantiate_class_template_1. */
15364 expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
15365 complain, in_decl);
15366 if (TREE_CODE (expanded_types) == TREE_VEC)
15368 len = TREE_VEC_LENGTH (expanded_types);
15369 vec = make_tree_vec (len);
15371 else
15373 /* All we did was update the type. Make a note of that. */
15374 type = expanded_types;
15375 expanded_types = NULL_TREE;
15379 for (int i = 0; i < len; ++i)
15381 r = copy_decl (t);
15382 if (expanded_types)
15384 type = TREE_VEC_ELT (expanded_types, i);
15385 DECL_NAME (r)
15386 = make_ith_pack_parameter_name (DECL_NAME (r), i);
15388 else if (!type)
15389 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15391 if (type == error_mark_node)
15392 RETURN (error_mark_node);
15393 TREE_TYPE (r) = type;
15394 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
15396 if (DECL_C_BIT_FIELD (r))
15397 /* For bit-fields, DECL_BIT_FIELD_REPRESENTATIVE gives the
15398 number of bits. */
15399 DECL_BIT_FIELD_REPRESENTATIVE (r)
15400 = tsubst_expr (DECL_BIT_FIELD_REPRESENTATIVE (t), args,
15401 complain, in_decl);
15402 if (DECL_INITIAL (t))
15404 /* Set up DECL_TEMPLATE_INFO so that we can get at the
15405 NSDMI in perform_member_init. Still set DECL_INITIAL
15406 so that we know there is one. */
15407 DECL_INITIAL (r) = void_node;
15408 gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
15409 retrofit_lang_decl (r);
15410 DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
15412 /* We don't have to set DECL_CONTEXT here; it is set by
15413 finish_member_declaration. */
15414 DECL_CHAIN (r) = NULL_TREE;
15416 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
15417 args, complain, in_decl))
15418 return error_mark_node;
15420 if (vec)
15421 TREE_VEC_ELT (vec, i) = r;
15424 if (vec)
15425 r = vec;
15427 break;
15429 case USING_DECL:
15430 /* We reach here only for member using decls. We also need to check
15431 uses_template_parms because DECL_DEPENDENT_P is not set for a
15432 using-declaration that designates a member of the current
15433 instantiation (c++/53549). */
15434 if (DECL_DEPENDENT_P (t)
15435 || uses_template_parms (USING_DECL_SCOPE (t)))
15437 /* True iff this using-decl was written as a pack expansion
15438 (and a pack appeared in its scope or name). If a pack
15439 appeared in both, we expand the packs separately and
15440 manually merge them. */
15441 bool variadic_p = false;
15443 tree scope = USING_DECL_SCOPE (t);
15444 if (PACK_EXPANSION_P (scope))
15446 scope = tsubst_pack_expansion (scope, args,
15447 complain | tf_qualifying_scope,
15448 in_decl);
15449 variadic_p = true;
15451 else
15452 scope = tsubst_scope (scope, args, complain, in_decl);
15454 tree name = DECL_NAME (t);
15455 if (IDENTIFIER_CONV_OP_P (name)
15456 && PACK_EXPANSION_P (TREE_TYPE (name)))
15458 name = tsubst_pack_expansion (TREE_TYPE (name), args,
15459 complain, in_decl);
15460 if (name == error_mark_node)
15462 r = error_mark_node;
15463 break;
15465 for (tree& elt : tree_vec_range (name))
15466 elt = make_conv_op_name (elt);
15467 variadic_p = true;
15469 else
15470 name = tsubst_name (name, args, complain, in_decl);
15472 int len;
15473 if (!variadic_p)
15474 len = 1;
15475 else if (TREE_CODE (scope) == TREE_VEC
15476 && TREE_CODE (name) == TREE_VEC)
15478 if (TREE_VEC_LENGTH (scope) != TREE_VEC_LENGTH (name))
15480 error ("mismatched argument pack lengths (%d vs %d)",
15481 TREE_VEC_LENGTH (scope), TREE_VEC_LENGTH (name));
15482 r = error_mark_node;
15483 break;
15485 len = TREE_VEC_LENGTH (scope);
15487 else if (TREE_CODE (scope) == TREE_VEC)
15488 len = TREE_VEC_LENGTH (scope);
15489 else /* TREE_CODE (name) == TREE_VEC */
15490 len = TREE_VEC_LENGTH (name);
15492 r = make_tree_vec (len);
15493 for (int i = 0; i < len; ++i)
15495 tree escope = (TREE_CODE (scope) == TREE_VEC
15496 ? TREE_VEC_ELT (scope, i)
15497 : scope);
15498 tree ename = (TREE_CODE (name) == TREE_VEC
15499 ? TREE_VEC_ELT (name, i)
15500 : name);
15501 tree elt = do_class_using_decl (escope, ename);
15502 if (!elt)
15504 r = error_mark_node;
15505 break;
15507 TREE_PROTECTED (elt) = TREE_PROTECTED (t);
15508 TREE_PRIVATE (elt) = TREE_PRIVATE (t);
15509 TREE_VEC_ELT (r, i) = elt;
15512 if (!variadic_p && r != error_mark_node)
15513 r = TREE_VEC_ELT (r, 0);
15515 else
15517 r = copy_node (t);
15518 DECL_CHAIN (r) = NULL_TREE;
15520 break;
15522 case TYPE_DECL:
15523 case VAR_DECL:
15525 tree argvec = NULL_TREE;
15526 tree gen_tmpl = NULL_TREE;
15527 tree tmpl = NULL_TREE;
15528 tree type = NULL_TREE;
15530 if (TREE_TYPE (t) == error_mark_node)
15531 RETURN (error_mark_node);
15533 if (TREE_CODE (t) == TYPE_DECL
15534 && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
15536 /* If this is the canonical decl, we don't have to
15537 mess with instantiations, and often we can't (for
15538 typename, template type parms and such). Note that
15539 TYPE_NAME is not correct for the above test if
15540 we've copied the type for a typedef. */
15541 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15542 if (type == error_mark_node)
15543 RETURN (error_mark_node);
15544 r = TYPE_NAME (type);
15545 break;
15548 /* Check to see if we already have the specialization we
15549 need. */
15550 tree spec = NULL_TREE;
15551 bool local_p = false;
15552 tree ctx = DECL_CONTEXT (t);
15553 if (!(VAR_P (t) && DECL_LOCAL_DECL_P (t))
15554 && (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t)))
15556 local_p = false;
15557 if (DECL_CLASS_SCOPE_P (t))
15559 ctx = tsubst_entering_scope (ctx, args, complain, in_decl);
15560 if (DECL_SELF_REFERENCE_P (t))
15561 /* The context and type of an injected-class-name are
15562 the same, so we don't need to substitute both. */
15563 type = ctx;
15564 /* If CTX is unchanged, then T is in fact the
15565 specialization we want. That situation occurs when
15566 referencing a static data member within in its own
15567 class. We can use pointer equality, rather than
15568 same_type_p, because DECL_CONTEXT is always
15569 canonical... */
15570 if (ctx == DECL_CONTEXT (t)
15571 /* ... unless T is a member template; in which
15572 case our caller can be willing to create a
15573 specialization of that template represented
15574 by T. */
15575 && !(DECL_TI_TEMPLATE (t)
15576 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (t))))
15577 spec = t;
15580 if (!spec)
15582 tmpl = DECL_TI_TEMPLATE (t);
15583 if (use_spec_table)
15585 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
15586 if (argvec == error_mark_node)
15587 RETURN (error_mark_node);
15588 gen_tmpl = most_general_template (tmpl);
15589 hash = spec_hasher::hash (gen_tmpl, argvec);
15590 spec = retrieve_specialization (gen_tmpl, argvec, hash);
15592 else
15593 argvec = args;
15596 else
15598 if (!(VAR_P (t) && DECL_LOCAL_DECL_P (t)))
15599 /* Subsequent calls to pushdecl will fill this in. */
15600 ctx = NULL_TREE;
15601 /* A local variable. */
15602 local_p = true;
15603 /* Unless this is a reference to a static variable from an
15604 enclosing function, in which case we need to fill it in now. */
15605 if (TREE_STATIC (t))
15607 tree fn = enclosing_instantiation_of (DECL_CONTEXT (t));
15608 if (fn != current_function_decl)
15609 ctx = fn;
15611 spec = retrieve_local_specialization (t);
15613 /* If we already have the specialization we need, there is
15614 nothing more to do. */
15615 if (spec)
15617 r = spec;
15618 break;
15621 /* Create a new node for the specialization we need. */
15622 if (type == NULL_TREE)
15624 if (is_typedef_decl (t))
15625 type = DECL_ORIGINAL_TYPE (t);
15626 else
15627 type = TREE_TYPE (t);
15628 if (VAR_P (t)
15629 && VAR_HAD_UNKNOWN_BOUND (t)
15630 && type != error_mark_node)
15631 type = strip_array_domain (type);
15632 tsubst_flags_t tcomplain = complain;
15633 if (VAR_P (t))
15634 tcomplain |= tf_tst_ok;
15635 type = tsubst (type, args, tcomplain, in_decl);
15636 /* Substituting the type might have recursively instantiated this
15637 same alias (c++/86171). */
15638 if (use_spec_table && gen_tmpl && DECL_ALIAS_TEMPLATE_P (gen_tmpl)
15639 && (spec = retrieve_specialization (gen_tmpl, argvec, hash)))
15641 r = spec;
15642 break;
15645 if (type == error_mark_node && !(complain & tf_error))
15646 RETURN (error_mark_node);
15647 r = copy_decl (t);
15648 if (VAR_P (r))
15650 DECL_INITIALIZED_P (r) = 0;
15651 DECL_TEMPLATE_INSTANTIATED (r) = 0;
15652 if (TREE_CODE (type) == FUNCTION_TYPE)
15654 /* It may seem that this case cannot occur, since:
15656 typedef void f();
15657 void g() { f x; }
15659 declares a function, not a variable. However:
15661 typedef void f();
15662 template <typename T> void g() { T t; }
15663 template void g<f>();
15665 is an attempt to declare a variable with function
15666 type. */
15667 error ("variable %qD has function type",
15668 /* R is not yet sufficiently initialized, so we
15669 just use its name. */
15670 DECL_NAME (r));
15671 RETURN (error_mark_node);
15673 type = complete_type (type);
15674 /* Wait until cp_finish_decl to set this again, to handle
15675 circular dependency (template/instantiate6.C). */
15676 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
15677 type = check_var_type (DECL_NAME (r), type,
15678 DECL_SOURCE_LOCATION (r));
15679 if (DECL_HAS_VALUE_EXPR_P (t))
15681 tree ve = DECL_VALUE_EXPR (t);
15682 /* If the DECL_VALUE_EXPR is converted to the declared type,
15683 preserve the identity so that gimplify_type_sizes works. */
15684 bool nop = (TREE_CODE (ve) == NOP_EXPR);
15685 if (nop)
15686 ve = TREE_OPERAND (ve, 0);
15687 ve = tsubst_expr (ve, args, complain, in_decl);
15688 if (REFERENCE_REF_P (ve))
15690 gcc_assert (TYPE_REF_P (type));
15691 ve = TREE_OPERAND (ve, 0);
15693 if (nop)
15694 ve = build_nop (type, ve);
15695 else if (DECL_LANG_SPECIFIC (t)
15696 && DECL_OMP_PRIVATIZED_MEMBER (t)
15697 && TREE_CODE (ve) == COMPONENT_REF
15698 && TREE_CODE (TREE_OPERAND (ve, 1)) == FIELD_DECL
15699 && DECL_BIT_FIELD_TYPE (TREE_OPERAND (ve, 1)) == type)
15700 type = TREE_TYPE (ve);
15701 else
15702 gcc_checking_assert (TYPE_MAIN_VARIANT (TREE_TYPE (ve))
15703 == TYPE_MAIN_VARIANT (type));
15704 SET_DECL_VALUE_EXPR (r, ve);
15706 if (CP_DECL_THREAD_LOCAL_P (r)
15707 && !processing_template_decl)
15708 set_decl_tls_model (r, decl_default_tls_model (r));
15710 else if (DECL_SELF_REFERENCE_P (t))
15711 SET_DECL_SELF_REFERENCE_P (r);
15712 TREE_TYPE (r) = type;
15713 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
15714 DECL_CONTEXT (r) = ctx;
15715 /* Clear out the mangled name and RTL for the instantiation. */
15716 SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
15717 if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
15718 SET_DECL_RTL (r, NULL);
15719 set_instantiating_module (r);
15721 /* The initializer must not be expanded until it is required;
15722 see [temp.inst]. */
15723 DECL_INITIAL (r) = NULL_TREE;
15724 DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
15725 if (VAR_P (r))
15727 if (DECL_LANG_SPECIFIC (r))
15728 SET_DECL_DEPENDENT_INIT_P (r, false);
15730 SET_DECL_MODE (r, VOIDmode);
15732 /* Possibly limit visibility based on template args. */
15733 DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
15734 if (DECL_VISIBILITY_SPECIFIED (t))
15736 DECL_VISIBILITY_SPECIFIED (r) = 0;
15737 DECL_ATTRIBUTES (r)
15738 = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
15740 determine_visibility (r);
15741 if ((!local_p || TREE_STATIC (t)) && DECL_SECTION_NAME (t))
15742 set_decl_section_name (r, t);
15745 if (!local_p)
15747 /* A static data member declaration is always marked
15748 external when it is declared in-class, even if an
15749 initializer is present. We mimic the non-template
15750 processing here. */
15751 DECL_EXTERNAL (r) = 1;
15752 if (DECL_NAMESPACE_SCOPE_P (t))
15753 DECL_NOT_REALLY_EXTERN (r) = 1;
15755 DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
15756 SET_DECL_IMPLICIT_INSTANTIATION (r);
15757 if (use_spec_table)
15758 register_specialization (r, gen_tmpl, argvec, false, hash);
15760 else
15762 if (DECL_LANG_SPECIFIC (r))
15763 DECL_TEMPLATE_INFO (r) = NULL_TREE;
15764 if (!cp_unevaluated_operand)
15765 register_local_specialization (r, t);
15768 DECL_CHAIN (r) = NULL_TREE;
15770 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
15771 /*flags=*/0,
15772 args, complain, in_decl))
15773 return error_mark_node;
15775 /* Preserve a typedef that names a type. */
15776 if (is_typedef_decl (r) && type != error_mark_node)
15778 DECL_ORIGINAL_TYPE (r) = NULL_TREE;
15779 set_underlying_type (r);
15781 /* common_handle_aligned_attribute doesn't apply the alignment
15782 to DECL_ORIGINAL_TYPE. */
15783 if (TYPE_USER_ALIGN (TREE_TYPE (t)))
15784 TREE_TYPE (r) = build_aligned_type (TREE_TYPE (r),
15785 TYPE_ALIGN (TREE_TYPE (t)));
15788 layout_decl (r, 0);
15790 break;
15792 default:
15793 gcc_unreachable ();
15795 #undef RETURN
15797 out:
15798 /* Restore the file and line information. */
15799 input_location = saved_loc;
15801 return r;
15804 /* Substitute into the complete parameter type list PARMS. */
15806 tree
15807 tsubst_function_parms (tree parms,
15808 tree args,
15809 tsubst_flags_t complain,
15810 tree in_decl)
15812 return tsubst_arg_types (parms, args, NULL_TREE, complain, in_decl);
15815 /* Substitute into the ARG_TYPES of a function type.
15816 If END is a TREE_CHAIN, leave it and any following types
15817 un-substituted. */
15819 static tree
15820 tsubst_arg_types (tree arg_types,
15821 tree args,
15822 tree end,
15823 tsubst_flags_t complain,
15824 tree in_decl)
15826 tree type = NULL_TREE;
15827 int len = 1;
15828 tree expanded_args = NULL_TREE;
15830 if (!arg_types || arg_types == void_list_node || arg_types == end)
15831 return arg_types;
15833 if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
15835 /* For a pack expansion, perform substitution on the
15836 entire expression. Later on, we'll handle the arguments
15837 one-by-one. */
15838 expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
15839 args, complain, in_decl);
15841 if (TREE_CODE (expanded_args) == TREE_VEC)
15842 /* So that we'll spin through the parameters, one by one. */
15843 len = TREE_VEC_LENGTH (expanded_args);
15844 else
15846 /* We only partially substituted into the parameter
15847 pack. Our type is TYPE_PACK_EXPANSION. */
15848 type = expanded_args;
15849 expanded_args = NULL_TREE;
15852 else
15853 type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
15855 /* Check if a substituted type is erroneous before substituting into
15856 the rest of the chain. */
15857 for (int i = 0; i < len; i++)
15859 if (expanded_args)
15860 type = TREE_VEC_ELT (expanded_args, i);
15862 if (type == error_mark_node)
15863 return error_mark_node;
15864 if (VOID_TYPE_P (type))
15866 if (complain & tf_error)
15868 error ("invalid parameter type %qT", type);
15869 if (in_decl)
15870 error ("in declaration %q+D", in_decl);
15872 return error_mark_node;
15876 /* We do not substitute into default arguments here. The standard
15877 mandates that they be instantiated only when needed, which is
15878 done in build_over_call. */
15879 tree default_arg = TREE_PURPOSE (arg_types);
15881 /* Except that we do substitute default arguments under tsubst_lambda_expr,
15882 since the new op() won't have any associated template arguments for us
15883 to refer to later. */
15884 if (lambda_fn_in_template_p (in_decl)
15885 || (in_decl && TREE_CODE (in_decl) == FUNCTION_DECL
15886 && DECL_LOCAL_DECL_P (in_decl)))
15887 default_arg = tsubst_expr (default_arg, args, complain, in_decl);
15889 tree remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
15890 args, end, complain, in_decl);
15891 if (remaining_arg_types == error_mark_node)
15892 return error_mark_node;
15894 for (int i = len-1; i >= 0; i--)
15896 if (expanded_args)
15897 type = TREE_VEC_ELT (expanded_args, i);
15899 /* Do array-to-pointer, function-to-pointer conversion, and ignore
15900 top-level qualifiers as required. */
15901 type = cv_unqualified (type_decays_to (type));
15903 if (default_arg && TREE_CODE (default_arg) == DEFERRED_PARSE)
15905 /* We've instantiated a template before its default arguments
15906 have been parsed. This can happen for a nested template
15907 class, and is not an error unless we require the default
15908 argument in a call of this function. */
15909 remaining_arg_types
15910 = tree_cons (default_arg, type, remaining_arg_types);
15911 vec_safe_push (DEFPARSE_INSTANTIATIONS (default_arg),
15912 remaining_arg_types);
15914 else
15915 remaining_arg_types
15916 = hash_tree_cons (default_arg, type, remaining_arg_types);
15919 return remaining_arg_types;
15922 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE. This routine does
15923 *not* handle the exception-specification for FNTYPE, because the
15924 initial substitution of explicitly provided template parameters
15925 during argument deduction forbids substitution into the
15926 exception-specification:
15928 [temp.deduct]
15930 All references in the function type of the function template to the
15931 corresponding template parameters are replaced by the specified tem-
15932 plate argument values. If a substitution in a template parameter or
15933 in the function type of the function template results in an invalid
15934 type, type deduction fails. [Note: The equivalent substitution in
15935 exception specifications is done only when the function is instanti-
15936 ated, at which point a program is ill-formed if the substitution
15937 results in an invalid type.] */
15939 static tree
15940 tsubst_function_type (tree t,
15941 tree args,
15942 tsubst_flags_t complain,
15943 tree in_decl)
15945 tree return_type;
15946 tree arg_types = NULL_TREE;
15948 /* The TYPE_CONTEXT is not used for function/method types. */
15949 gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
15951 /* DR 1227: Mixing immediate and non-immediate contexts in deduction
15952 failure. */
15953 bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
15955 if (late_return_type_p)
15957 /* Substitute the argument types. */
15958 arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
15959 complain, in_decl);
15960 if (arg_types == error_mark_node)
15961 return error_mark_node;
15963 tree save_ccp = current_class_ptr;
15964 tree save_ccr = current_class_ref;
15965 tree this_type = (TREE_CODE (t) == METHOD_TYPE
15966 ? TREE_TYPE (TREE_VALUE (arg_types)) : NULL_TREE);
15967 bool do_inject = this_type && CLASS_TYPE_P (this_type);
15968 if (do_inject)
15970 /* DR 1207: 'this' is in scope in the trailing return type. */
15971 inject_this_parameter (this_type, cp_type_quals (this_type));
15974 /* Substitute the return type. */
15975 return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15977 if (do_inject)
15979 current_class_ptr = save_ccp;
15980 current_class_ref = save_ccr;
15983 else
15984 /* Substitute the return type. */
15985 return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15987 if (return_type == error_mark_node)
15988 return error_mark_node;
15989 /* DR 486 clarifies that creation of a function type with an
15990 invalid return type is a deduction failure. */
15991 if (TREE_CODE (return_type) == ARRAY_TYPE
15992 || TREE_CODE (return_type) == FUNCTION_TYPE)
15994 if (complain & tf_error)
15996 if (TREE_CODE (return_type) == ARRAY_TYPE)
15997 error ("function returning an array");
15998 else
15999 error ("function returning a function");
16001 return error_mark_node;
16004 if (!late_return_type_p)
16006 /* Substitute the argument types. */
16007 arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
16008 complain, in_decl);
16009 if (arg_types == error_mark_node)
16010 return error_mark_node;
16013 /* Construct a new type node and return it. */
16014 return rebuild_function_or_method_type (t, args, return_type, arg_types,
16015 /*raises=*/NULL_TREE, complain);
16018 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE. Substitute the template
16019 ARGS into that specification, and return the substituted
16020 specification. If there is no specification, return NULL_TREE. */
16022 static tree
16023 tsubst_exception_specification (tree fntype,
16024 tree args,
16025 tsubst_flags_t complain,
16026 tree in_decl,
16027 bool defer_ok)
16029 tree specs;
16030 tree new_specs;
16032 specs = TYPE_RAISES_EXCEPTIONS (fntype);
16033 new_specs = NULL_TREE;
16034 if (specs && TREE_PURPOSE (specs))
16036 /* A noexcept-specifier. */
16037 tree expr = TREE_PURPOSE (specs);
16038 if (TREE_CODE (expr) == INTEGER_CST)
16039 new_specs = expr;
16040 else if (defer_ok)
16042 /* Defer instantiation of noexcept-specifiers to avoid
16043 excessive instantiations (c++/49107). */
16044 new_specs = make_node (DEFERRED_NOEXCEPT);
16045 if (DEFERRED_NOEXCEPT_SPEC_P (specs))
16047 /* We already partially instantiated this member template,
16048 so combine the new args with the old. */
16049 DEFERRED_NOEXCEPT_PATTERN (new_specs)
16050 = DEFERRED_NOEXCEPT_PATTERN (expr);
16051 DEFERRED_NOEXCEPT_ARGS (new_specs)
16052 = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
16054 else
16056 DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
16057 DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
16060 else
16062 if (DEFERRED_NOEXCEPT_SPEC_P (specs))
16064 args = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr),
16065 args);
16066 expr = DEFERRED_NOEXCEPT_PATTERN (expr);
16068 new_specs = tsubst_expr (expr, args, complain, in_decl);
16070 new_specs = build_noexcept_spec (new_specs, complain);
16071 /* We've instantiated a template before a noexcept-specifier
16072 contained therein has been parsed. This can happen for
16073 a nested template class:
16075 struct S {
16076 template<typename> struct B { B() noexcept(...); };
16077 struct A : B<int> { ... use B() ... };
16080 where completing B<int> will trigger instantiating the
16081 noexcept, even though we only parse it at the end of S. */
16082 if (UNPARSED_NOEXCEPT_SPEC_P (specs))
16084 gcc_checking_assert (defer_ok);
16085 vec_safe_push (DEFPARSE_INSTANTIATIONS (expr), new_specs);
16088 else if (specs)
16090 if (! TREE_VALUE (specs))
16091 new_specs = specs;
16092 else
16093 while (specs)
16095 tree spec;
16096 int i, len = 1;
16097 tree expanded_specs = NULL_TREE;
16099 if (PACK_EXPANSION_P (TREE_VALUE (specs)))
16101 /* Expand the pack expansion type. */
16102 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
16103 args, complain,
16104 in_decl);
16106 if (expanded_specs == error_mark_node)
16107 return error_mark_node;
16108 else if (TREE_CODE (expanded_specs) == TREE_VEC)
16109 len = TREE_VEC_LENGTH (expanded_specs);
16110 else
16112 /* We're substituting into a member template, so
16113 we got a TYPE_PACK_EXPANSION back. Add that
16114 expansion and move on. */
16115 gcc_assert (TREE_CODE (expanded_specs)
16116 == TYPE_PACK_EXPANSION);
16117 new_specs = add_exception_specifier (new_specs,
16118 expanded_specs,
16119 complain);
16120 specs = TREE_CHAIN (specs);
16121 continue;
16125 for (i = 0; i < len; ++i)
16127 if (expanded_specs)
16128 spec = TREE_VEC_ELT (expanded_specs, i);
16129 else
16130 spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
16131 if (spec == error_mark_node)
16132 return spec;
16133 new_specs = add_exception_specifier (new_specs, spec,
16134 complain);
16137 specs = TREE_CHAIN (specs);
16140 return new_specs;
16143 /* Substitute through a TREE_LIST of types or expressions, handling pack
16144 expansions. */
16146 tree
16147 tsubst_tree_list (tree t, tree args, tsubst_flags_t complain, tree in_decl)
16149 if (t == void_list_node)
16150 return t;
16152 tree purpose = TREE_PURPOSE (t);
16153 tree purposevec = NULL_TREE;
16154 if (!purpose)
16156 else if (PACK_EXPANSION_P (purpose))
16158 purpose = tsubst_pack_expansion (purpose, args, complain, in_decl);
16159 if (TREE_CODE (purpose) == TREE_VEC)
16160 purposevec = purpose;
16162 else if (TYPE_P (purpose))
16163 purpose = tsubst (purpose, args, complain, in_decl);
16164 else
16165 purpose = tsubst_expr (purpose, args, complain, in_decl);
16166 if (purpose == error_mark_node || purposevec == error_mark_node)
16167 return error_mark_node;
16169 tree value = TREE_VALUE (t);
16170 tree valuevec = NULL_TREE;
16171 if (!value)
16173 else if (PACK_EXPANSION_P (value))
16175 value = tsubst_pack_expansion (value, args, complain, in_decl);
16176 if (TREE_CODE (value) == TREE_VEC)
16177 valuevec = value;
16179 else if (TYPE_P (value))
16180 value = tsubst (value, args, complain, in_decl);
16181 else
16182 value = tsubst_expr (value, args, complain, in_decl);
16183 if (value == error_mark_node || valuevec == error_mark_node)
16184 return error_mark_node;
16186 tree chain = TREE_CHAIN (t);
16187 if (!chain)
16189 else if (TREE_CODE (chain) == TREE_LIST)
16190 chain = tsubst_tree_list (chain, args, complain, in_decl);
16191 else if (TYPE_P (chain))
16192 chain = tsubst (chain, args, complain, in_decl);
16193 else
16194 chain = tsubst_expr (chain, args, complain, in_decl);
16195 if (chain == error_mark_node)
16196 return error_mark_node;
16198 if (purpose == TREE_PURPOSE (t)
16199 && value == TREE_VALUE (t)
16200 && chain == TREE_CHAIN (t))
16201 return t;
16203 int len;
16204 /* Determine the number of arguments. */
16205 if (purposevec)
16207 len = TREE_VEC_LENGTH (purposevec);
16208 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
16210 else if (valuevec)
16211 len = TREE_VEC_LENGTH (valuevec);
16212 else
16213 len = 1;
16215 for (int i = len; i-- > 0; )
16217 if (purposevec)
16218 purpose = TREE_VEC_ELT (purposevec, i);
16219 if (valuevec)
16220 value = TREE_VEC_ELT (valuevec, i);
16222 if (value && TYPE_P (value))
16223 chain = hash_tree_cons (purpose, value, chain);
16224 else
16225 chain = tree_cons (purpose, value, chain);
16228 return chain;
16231 /* Take the tree structure T and replace template parameters used
16232 therein with the argument vector ARGS. IN_DECL is an associated
16233 decl for diagnostics. If an error occurs, returns ERROR_MARK_NODE.
16234 Issue error and warning messages under control of COMPLAIN. Note
16235 that we must be relatively non-tolerant of extensions here, in
16236 order to preserve conformance; if we allow substitutions that
16237 should not be allowed, we may allow argument deductions that should
16238 not succeed, and therefore report ambiguous overload situations
16239 where there are none. In theory, we could allow the substitution,
16240 but indicate that it should have failed, and allow our caller to
16241 make sure that the right thing happens, but we don't try to do this
16242 yet.
16244 This function is used for dealing with types, decls and the like;
16245 for expressions, use tsubst_expr or tsubst_copy. */
16247 tree
16248 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
16250 enum tree_code code;
16251 tree type, r = NULL_TREE;
16253 if (t == NULL_TREE || t == error_mark_node
16254 || t == integer_type_node
16255 || t == void_type_node
16256 || t == char_type_node
16257 || t == unknown_type_node
16258 || TREE_CODE (t) == NAMESPACE_DECL
16259 || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
16260 return t;
16262 tsubst_flags_t tst_ok_flag = (complain & tf_tst_ok);
16263 complain &= ~tf_tst_ok;
16265 tsubst_flags_t qualifying_scope_flag = (complain & tf_qualifying_scope);
16266 complain &= ~tf_qualifying_scope;
16268 if (DECL_P (t))
16269 return tsubst_decl (t, args, complain);
16271 if (args == NULL_TREE)
16272 return t;
16274 code = TREE_CODE (t);
16276 gcc_assert (code != IDENTIFIER_NODE);
16277 type = TREE_TYPE (t);
16279 gcc_assert (type != unknown_type_node);
16281 if (tree d = maybe_dependent_member_ref (t, args, complain, in_decl))
16282 return d;
16284 /* Reuse typedefs. We need to do this to handle dependent attributes,
16285 such as attribute aligned. */
16286 if (TYPE_P (t)
16287 && typedef_variant_p (t))
16289 tree decl = TYPE_NAME (t);
16291 if (alias_template_specialization_p (t, nt_opaque))
16293 /* DECL represents an alias template and we want to
16294 instantiate it. */
16295 tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
16296 tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
16297 r = instantiate_alias_template (tmpl, gen_args, complain);
16299 else if (DECL_CLASS_SCOPE_P (decl)
16300 && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
16301 && uses_template_parms (DECL_CONTEXT (decl)))
16303 tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
16304 tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
16305 r = retrieve_specialization (tmpl, gen_args, 0);
16307 else if (DECL_FUNCTION_SCOPE_P (decl)
16308 && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
16309 && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
16310 r = retrieve_local_specialization (decl);
16311 else
16312 /* The typedef is from a non-template context. */
16313 return t;
16315 if (r)
16317 r = TREE_TYPE (r);
16318 r = cp_build_qualified_type
16319 (r, cp_type_quals (t) | cp_type_quals (r),
16320 complain | tf_ignore_bad_quals);
16321 return r;
16323 else
16325 /* We don't have an instantiation yet, so drop the typedef. */
16326 int quals = cp_type_quals (t);
16327 t = DECL_ORIGINAL_TYPE (decl);
16328 t = cp_build_qualified_type (t, quals,
16329 complain | tf_ignore_bad_quals);
16333 bool fndecl_type = (complain & tf_fndecl_type);
16334 complain &= ~tf_fndecl_type;
16336 if (type
16337 && code != TYPENAME_TYPE
16338 && code != TEMPLATE_TYPE_PARM
16339 && code != TEMPLATE_PARM_INDEX
16340 && code != IDENTIFIER_NODE
16341 && code != FUNCTION_TYPE
16342 && code != METHOD_TYPE)
16343 type = tsubst (type, args, complain, in_decl);
16344 if (type == error_mark_node)
16345 return error_mark_node;
16347 switch (code)
16349 case RECORD_TYPE:
16350 if (TYPE_PTRMEMFUNC_P (t))
16351 return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
16352 /* Fall through. */
16353 case UNION_TYPE:
16354 case ENUMERAL_TYPE:
16355 if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
16357 /* Figure out what arguments are appropriate for the
16358 type we are trying to find. For example, given:
16360 template <class T> struct S;
16361 template <class T, class U> void f(T, U) { S<U> su; }
16363 and supposing that we are instantiating f<int, double>,
16364 then our ARGS will be {int, double}, but, when looking up
16365 S we only want {double}. */
16366 tree argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
16367 complain, in_decl);
16368 if (argvec == error_mark_node)
16369 return error_mark_node;
16371 tree r = lookup_template_class (t, argvec, in_decl, NULL_TREE,
16372 complain);
16373 return cp_build_qualified_type (r, cp_type_quals (t), complain);
16375 else
16376 /* This is not a template type, so there's nothing to do. */
16377 return t;
16379 case ERROR_MARK:
16380 case IDENTIFIER_NODE:
16381 case VOID_TYPE:
16382 case OPAQUE_TYPE:
16383 case REAL_TYPE:
16384 case COMPLEX_TYPE:
16385 case VECTOR_TYPE:
16386 case BOOLEAN_TYPE:
16387 case NULLPTR_TYPE:
16388 case LANG_TYPE:
16389 return t;
16391 case INTEGER_TYPE:
16392 if (t == integer_type_node)
16393 return t;
16395 if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
16396 && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
16397 return t;
16400 tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
16402 max = tsubst_expr (omax, args, complain, in_decl);
16404 /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
16405 needed. */
16406 if (TREE_CODE (max) == NOP_EXPR
16407 && TREE_SIDE_EFFECTS (omax)
16408 && !TREE_TYPE (max))
16409 TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
16411 /* If we're in a partial instantiation, preserve the magic NOP_EXPR
16412 with TREE_SIDE_EFFECTS that indicates this is not an integral
16413 constant expression. */
16414 if (processing_template_decl
16415 && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
16417 gcc_assert (TREE_CODE (max) == NOP_EXPR);
16418 TREE_SIDE_EFFECTS (max) = 1;
16421 return compute_array_index_type (NULL_TREE, max, complain);
16424 case TEMPLATE_TYPE_PARM:
16425 if (TEMPLATE_TYPE_LEVEL (t) == 0)
16427 /* This is either an ordinary level-less auto or a CTAD placeholder
16428 auto. These get replaced only via do_auto_deduction which, in the
16429 ordinary case, temporarily overrides its level to 1 before calling
16430 tsubst. CTAD placeholders are replaced via do_class_deduction. */
16431 gcc_checking_assert (is_auto (t));
16432 tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (t);
16433 if (!tmpl)
16434 /* Ordinary level-less auto has nothing to substitute. */
16435 return t;
16437 /* Substitute the template of this CTAD placeholder. */
16438 tmpl = tsubst_expr (tmpl, args, complain, in_decl);
16439 if (TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
16440 tmpl = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (tmpl);
16442 if (tmpl != CLASS_PLACEHOLDER_TEMPLATE (t))
16443 return make_template_placeholder (tmpl);
16444 else
16445 return t;
16447 /* Fall through. */
16448 case TEMPLATE_TEMPLATE_PARM:
16449 case BOUND_TEMPLATE_TEMPLATE_PARM:
16450 case TEMPLATE_PARM_INDEX:
16452 int idx;
16453 int level;
16454 int levels;
16455 tree arg = NULL_TREE;
16457 r = NULL_TREE;
16459 gcc_assert (TREE_VEC_LENGTH (args) > 0);
16460 template_parm_level_and_index (t, &level, &idx);
16462 levels = TMPL_ARGS_DEPTH (args);
16463 if (level <= levels
16464 && TREE_VEC_LENGTH (TMPL_ARGS_LEVEL (args, level)) > 0)
16466 arg = TMPL_ARG (args, level, idx);
16468 /* See through ARGUMENT_PACK_SELECT arguments. */
16469 if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
16470 arg = argument_pack_select_arg (arg);
16473 if (arg == error_mark_node)
16474 return error_mark_node;
16475 else if (arg != NULL_TREE)
16477 if (ARGUMENT_PACK_P (arg))
16478 /* If ARG is an argument pack, we don't actually want to
16479 perform a substitution here, because substitutions
16480 for argument packs are only done
16481 element-by-element. We can get to this point when
16482 substituting the type of a non-type template
16483 parameter pack, when that type actually contains
16484 template parameter packs from an outer template, e.g.,
16486 template<typename... Types> struct A {
16487 template<Types... Values> struct B { };
16488 }; */
16489 return t;
16491 if (code == TEMPLATE_TYPE_PARM)
16493 int quals;
16495 /* When building concept checks for the purpose of
16496 deducing placeholders, we can end up with wildcards
16497 where types are expected. Adjust this to the deduced
16498 value. */
16499 if (TREE_CODE (arg) == WILDCARD_DECL)
16500 arg = TREE_TYPE (TREE_TYPE (arg));
16502 gcc_assert (TYPE_P (arg));
16504 quals = cp_type_quals (arg) | cp_type_quals (t);
16506 return cp_build_qualified_type
16507 (arg, quals, complain | tf_ignore_bad_quals);
16509 else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
16511 /* We are processing a type constructed from a
16512 template template parameter. */
16513 tree argvec = tsubst (TYPE_TI_ARGS (t),
16514 args, complain, in_decl);
16515 if (argvec == error_mark_node)
16516 return error_mark_node;
16518 gcc_assert (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
16519 || TREE_CODE (arg) == TEMPLATE_DECL
16520 || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
16522 if (TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
16523 /* Consider this code:
16525 template <template <class> class Template>
16526 struct Internal {
16527 template <class Arg> using Bind = Template<Arg>;
16530 template <template <class> class Template, class Arg>
16531 using Instantiate = Template<Arg>; //#0
16533 template <template <class> class Template,
16534 class Argument>
16535 using Bind =
16536 Instantiate<Internal<Template>::template Bind,
16537 Argument>; //#1
16539 When #1 is parsed, the
16540 BOUND_TEMPLATE_TEMPLATE_PARM representing the
16541 parameter `Template' in #0 matches the
16542 UNBOUND_CLASS_TEMPLATE representing the argument
16543 `Internal<Template>::template Bind'; We then want
16544 to assemble the type `Bind<Argument>' that can't
16545 be fully created right now, because
16546 `Internal<Template>' not being complete, the Bind
16547 template cannot be looked up in that context. So
16548 we need to "store" `Bind<Argument>' for later
16549 when the context of Bind becomes complete. Let's
16550 store that in a TYPENAME_TYPE. */
16551 return make_typename_type (TYPE_CONTEXT (arg),
16552 build_nt (TEMPLATE_ID_EXPR,
16553 TYPE_IDENTIFIER (arg),
16554 argvec),
16555 typename_type,
16556 complain);
16558 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
16559 are resolving nested-types in the signature of a
16560 member function templates. Otherwise ARG is a
16561 TEMPLATE_DECL and is the real template to be
16562 instantiated. */
16563 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
16564 arg = TYPE_NAME (arg);
16566 r = lookup_template_class (arg,
16567 argvec, in_decl,
16568 DECL_CONTEXT (arg),
16569 complain);
16570 return cp_build_qualified_type
16571 (r, cp_type_quals (t) | cp_type_quals (r), complain);
16573 else if (code == TEMPLATE_TEMPLATE_PARM)
16574 return arg;
16575 else
16576 /* TEMPLATE_PARM_INDEX. */
16577 return convert_from_reference (unshare_expr (arg));
16580 if (level == 1)
16581 /* This can happen during the attempted tsubst'ing in
16582 unify. This means that we don't yet have any information
16583 about the template parameter in question. */
16584 return t;
16586 /* Early in template argument deduction substitution, we don't
16587 want to reduce the level of 'auto', or it will be confused
16588 with a normal template parm in subsequent deduction.
16589 Similarly, don't reduce the level of template parameters to
16590 avoid mismatches when deducing their types. */
16591 if (complain & tf_partial)
16592 return t;
16594 /* If we get here, we must have been looking at a parm for a
16595 more deeply nested template. Make a new version of this
16596 template parameter, but with a lower level. */
16597 int quals;
16598 switch (code)
16600 case TEMPLATE_TYPE_PARM:
16601 case TEMPLATE_TEMPLATE_PARM:
16602 quals = cp_type_quals (t);
16603 if (quals)
16605 gcc_checking_assert (code == TEMPLATE_TYPE_PARM);
16606 t = TYPE_MAIN_VARIANT (t);
16609 if (tree d = TEMPLATE_TYPE_DESCENDANTS (t))
16610 if (TEMPLATE_PARM_LEVEL (d) == TEMPLATE_TYPE_LEVEL (t) - levels
16611 && (code == TEMPLATE_TYPE_PARM
16612 || TEMPLATE_TEMPLATE_PARM_SIMPLE_P (t)))
16613 /* Cache lowering a type parameter or a simple template
16614 template parameter. */
16615 r = TREE_TYPE (d);
16617 if (!r)
16619 r = copy_type (t);
16620 TEMPLATE_TYPE_PARM_INDEX (r)
16621 = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
16622 r, levels, args, complain);
16623 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
16624 TYPE_MAIN_VARIANT (r) = r;
16625 TYPE_POINTER_TO (r) = NULL_TREE;
16626 TYPE_REFERENCE_TO (r) = NULL_TREE;
16628 if (code == TEMPLATE_TYPE_PARM)
16629 if (tree ci = PLACEHOLDER_TYPE_CONSTRAINTS_INFO (t))
16630 /* Propagate constraints on placeholders since they are
16631 only instantiated during satisfaction. */
16632 PLACEHOLDER_TYPE_CONSTRAINTS_INFO (r) = ci;
16634 if (TYPE_STRUCTURAL_EQUALITY_P (t))
16635 SET_TYPE_STRUCTURAL_EQUALITY (r);
16636 else
16637 TYPE_CANONICAL (r) = canonical_type_parameter (r);
16640 if (quals)
16641 r = cp_build_qualified_type (r, quals,
16642 complain | tf_ignore_bad_quals);
16643 break;
16645 case BOUND_TEMPLATE_TEMPLATE_PARM:
16647 tree tinfo = TYPE_TEMPLATE_INFO (t);
16648 /* We might need to substitute into the types of non-type
16649 template parameters. This also lowers the level of
16650 the ttp appropriately. */
16651 tree tmpl = tsubst (TI_TEMPLATE (tinfo), args,
16652 complain, in_decl);
16653 if (tmpl == error_mark_node)
16654 return error_mark_node;
16655 tree argvec = tsubst (TI_ARGS (tinfo), args,
16656 complain, in_decl);
16657 if (argvec == error_mark_node)
16658 return error_mark_node;
16659 r = lookup_template_class (tmpl, argvec, in_decl, NULL_TREE,
16660 complain);
16661 r = cp_build_qualified_type (r, cp_type_quals (t), complain);
16662 break;
16665 case TEMPLATE_PARM_INDEX:
16666 /* OK, now substitute the type of the non-type parameter. We
16667 couldn't do it earlier because it might be an auto parameter,
16668 and we wouldn't need to if we had an argument. */
16669 type = tsubst (type, args, complain, in_decl);
16670 if (type == error_mark_node)
16671 return error_mark_node;
16672 r = reduce_template_parm_level (t, type, levels, args, complain);
16673 break;
16675 default:
16676 gcc_unreachable ();
16679 return r;
16682 case TREE_LIST:
16683 return tsubst_tree_list (t, args, complain, in_decl);
16685 case TREE_BINFO:
16686 /* We should never be tsubsting a binfo. */
16687 gcc_unreachable ();
16689 case TREE_VEC:
16690 /* A vector of template arguments. */
16691 gcc_assert (!type);
16692 return tsubst_template_args (t, args, complain, in_decl);
16694 case POINTER_TYPE:
16695 case REFERENCE_TYPE:
16697 if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
16698 return t;
16700 /* [temp.deduct]
16702 Type deduction may fail for any of the following
16703 reasons:
16705 -- Attempting to create a pointer to reference type.
16706 -- Attempting to create a reference to a reference type or
16707 a reference to void.
16709 Core issue 106 says that creating a reference to a reference
16710 during instantiation is no longer a cause for failure. We
16711 only enforce this check in strict C++98 mode. */
16712 if ((TYPE_REF_P (type)
16713 && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
16714 || (code == REFERENCE_TYPE && VOID_TYPE_P (type)))
16716 static location_t last_loc;
16718 /* We keep track of the last time we issued this error
16719 message to avoid spewing a ton of messages during a
16720 single bad template instantiation. */
16721 if (complain & tf_error
16722 && last_loc != input_location)
16724 if (VOID_TYPE_P (type))
16725 error ("forming reference to void");
16726 else if (code == POINTER_TYPE)
16727 error ("forming pointer to reference type %qT", type);
16728 else
16729 error ("forming reference to reference type %qT", type);
16730 last_loc = input_location;
16733 return error_mark_node;
16735 else if (TREE_CODE (type) == FUNCTION_TYPE
16736 && (type_memfn_quals (type) != TYPE_UNQUALIFIED
16737 || type_memfn_rqual (type) != REF_QUAL_NONE))
16739 if (complain & tf_error)
16741 if (code == POINTER_TYPE)
16742 error ("forming pointer to qualified function type %qT",
16743 type);
16744 else
16745 error ("forming reference to qualified function type %qT",
16746 type);
16748 return error_mark_node;
16750 else if (code == POINTER_TYPE)
16752 r = build_pointer_type (type);
16753 if (TREE_CODE (type) == METHOD_TYPE)
16754 r = build_ptrmemfunc_type (r);
16756 else if (TYPE_REF_P (type))
16757 /* In C++0x, during template argument substitution, when there is an
16758 attempt to create a reference to a reference type, reference
16759 collapsing is applied as described in [14.3.1/4 temp.arg.type]:
16761 "If a template-argument for a template-parameter T names a type
16762 that is a reference to a type A, an attempt to create the type
16763 'lvalue reference to cv T' creates the type 'lvalue reference to
16764 A,' while an attempt to create the type type rvalue reference to
16765 cv T' creates the type T"
16767 r = cp_build_reference_type
16768 (TREE_TYPE (type),
16769 TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
16770 else
16771 r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
16772 r = cp_build_qualified_type (r, cp_type_quals (t), complain);
16774 if (r != error_mark_node)
16775 /* Will this ever be needed for TYPE_..._TO values? */
16776 layout_type (r);
16778 return r;
16780 case OFFSET_TYPE:
16782 r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
16783 if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
16785 /* [temp.deduct]
16787 Type deduction may fail for any of the following
16788 reasons:
16790 -- Attempting to create "pointer to member of T" when T
16791 is not a class type. */
16792 if (complain & tf_error)
16793 error ("creating pointer to member of non-class type %qT", r);
16794 return error_mark_node;
16796 if (TYPE_REF_P (type))
16798 if (complain & tf_error)
16799 error ("creating pointer to member reference type %qT", type);
16800 return error_mark_node;
16802 if (VOID_TYPE_P (type))
16804 if (complain & tf_error)
16805 error ("creating pointer to member of type void");
16806 return error_mark_node;
16808 gcc_assert (TREE_CODE (type) != METHOD_TYPE);
16809 if (TREE_CODE (type) == FUNCTION_TYPE)
16811 /* The type of the implicit object parameter gets its
16812 cv-qualifiers from the FUNCTION_TYPE. */
16813 tree memptr;
16814 tree method_type
16815 = build_memfn_type (type, r, type_memfn_quals (type),
16816 type_memfn_rqual (type));
16817 memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
16818 return cp_build_qualified_type (memptr, cp_type_quals (t),
16819 complain);
16821 else
16822 return cp_build_qualified_type (build_ptrmem_type (r, type),
16823 cp_type_quals (t),
16824 complain);
16826 case FUNCTION_TYPE:
16827 case METHOD_TYPE:
16829 tree fntype;
16830 tree specs;
16831 fntype = tsubst_function_type (t, args, complain, in_decl);
16832 if (fntype == error_mark_node)
16833 return error_mark_node;
16835 /* Substitute the exception specification. */
16836 specs = tsubst_exception_specification (t, args, complain, in_decl,
16837 /*defer_ok*/fndecl_type);
16838 if (specs == error_mark_node)
16839 return error_mark_node;
16840 if (specs)
16841 fntype = build_exception_variant (fntype, specs);
16842 return fntype;
16844 case ARRAY_TYPE:
16846 tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
16847 if (domain == error_mark_node)
16848 return error_mark_node;
16850 /* As an optimization, we avoid regenerating the array type if
16851 it will obviously be the same as T. */
16852 if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
16853 return t;
16855 /* These checks should match the ones in create_array_type_for_decl.
16857 [temp.deduct]
16859 The deduction may fail for any of the following reasons:
16861 -- Attempting to create an array with an element type that
16862 is void, a function type, or a reference type, or [DR337]
16863 an abstract class type. */
16864 if (VOID_TYPE_P (type)
16865 || TREE_CODE (type) == FUNCTION_TYPE
16866 || (TREE_CODE (type) == ARRAY_TYPE
16867 && TYPE_DOMAIN (type) == NULL_TREE)
16868 || TYPE_REF_P (type))
16870 if (complain & tf_error)
16871 error ("creating array of %qT", type);
16872 return error_mark_node;
16875 if (!verify_type_context (input_location, TCTX_ARRAY_ELEMENT, type,
16876 !(complain & tf_error)))
16877 return error_mark_node;
16879 r = build_cplus_array_type (type, domain);
16881 if (!valid_array_size_p (input_location, r, in_decl,
16882 (complain & tf_error)))
16883 return error_mark_node;
16885 if (TYPE_USER_ALIGN (t))
16887 SET_TYPE_ALIGN (r, TYPE_ALIGN (t));
16888 TYPE_USER_ALIGN (r) = 1;
16891 return r;
16894 case TYPENAME_TYPE:
16896 tree ctx = TYPE_CONTEXT (t);
16897 if (TREE_CODE (ctx) == TYPE_PACK_EXPANSION)
16899 ctx = tsubst_pack_expansion (ctx, args,
16900 complain | tf_qualifying_scope,
16901 in_decl);
16902 if (ctx == error_mark_node
16903 || TREE_VEC_LENGTH (ctx) > 1)
16904 return error_mark_node;
16905 if (TREE_VEC_LENGTH (ctx) == 0)
16907 if (complain & tf_error)
16908 error ("%qD is instantiated for an empty pack",
16909 TYPENAME_TYPE_FULLNAME (t));
16910 return error_mark_node;
16912 ctx = TREE_VEC_ELT (ctx, 0);
16914 else
16915 ctx = tsubst_entering_scope (ctx, args,
16916 complain | tf_qualifying_scope,
16917 in_decl);
16918 if (ctx == error_mark_node)
16919 return error_mark_node;
16921 tree f = tsubst_name (TYPENAME_TYPE_FULLNAME (t), args,
16922 complain, in_decl);
16923 if (f == error_mark_node)
16924 return error_mark_node;
16926 if (!MAYBE_CLASS_TYPE_P (ctx))
16928 if (complain & tf_error)
16929 error ("%qT is not a class, struct, or union type", ctx);
16930 return error_mark_node;
16932 else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
16934 /* Normally, make_typename_type does not require that the CTX
16935 have complete type in order to allow things like:
16937 template <class T> struct S { typename S<T>::X Y; };
16939 But, such constructs have already been resolved by this
16940 point, so here CTX really should have complete type, unless
16941 it's a partial instantiation. */
16942 if (!complete_type_or_maybe_complain (ctx, NULL_TREE, complain))
16943 return error_mark_node;
16946 /* FIXME: TYPENAME_IS_CLASS_P conflates 'class' vs 'struct' vs 'union'
16947 tags. TYPENAME_TYPE should probably remember the exact tag that
16948 was written. */
16949 enum tag_types tag_type
16950 = TYPENAME_IS_CLASS_P (t) ? class_type
16951 : TYPENAME_IS_ENUM_P (t) ? enum_type
16952 : typename_type;
16953 tsubst_flags_t tcomplain = complain | tf_keep_type_decl;
16954 tcomplain |= tst_ok_flag | qualifying_scope_flag;
16955 f = make_typename_type (ctx, f, tag_type, tcomplain);
16956 if (f == error_mark_node)
16957 return f;
16958 if (TREE_CODE (f) == TYPE_DECL)
16960 complain |= tf_ignore_bad_quals;
16961 f = TREE_TYPE (f);
16964 if (TREE_CODE (f) != TYPENAME_TYPE)
16966 if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
16968 if (complain & tf_error)
16969 error ("%qT resolves to %qT, which is not an enumeration type",
16970 t, f);
16971 else
16972 return error_mark_node;
16974 else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
16976 if (complain & tf_error)
16977 error ("%qT resolves to %qT, which is not a class type",
16978 t, f);
16979 else
16980 return error_mark_node;
16984 return cp_build_qualified_type
16985 (f, cp_type_quals (f) | cp_type_quals (t), complain);
16988 case UNBOUND_CLASS_TEMPLATE:
16990 ++processing_template_decl;
16991 tree ctx = tsubst_entering_scope (TYPE_CONTEXT (t), args,
16992 complain, in_decl);
16993 --processing_template_decl;
16994 tree name = TYPE_IDENTIFIER (t);
16995 tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
16997 if (ctx == error_mark_node || name == error_mark_node)
16998 return error_mark_node;
17000 if (parm_list)
17001 parm_list = tsubst_template_parms (parm_list, args, complain);
17002 return make_unbound_class_template (ctx, name, parm_list, complain);
17005 case TYPEOF_TYPE:
17007 tree type;
17009 ++cp_unevaluated_operand;
17010 ++c_inhibit_evaluation_warnings;
17012 type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args, complain, in_decl);
17014 --cp_unevaluated_operand;
17015 --c_inhibit_evaluation_warnings;
17017 type = finish_typeof (type);
17018 return cp_build_qualified_type (type,
17019 cp_type_quals (t)
17020 | cp_type_quals (type),
17021 complain);
17024 case DECLTYPE_TYPE:
17026 tree type;
17028 ++cp_unevaluated_operand;
17029 ++c_inhibit_evaluation_warnings;
17031 type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
17032 complain|tf_decltype, in_decl);
17034 --cp_unevaluated_operand;
17035 --c_inhibit_evaluation_warnings;
17037 if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
17038 type = lambda_capture_field_type (type,
17039 false /*explicit_init*/,
17040 DECLTYPE_FOR_REF_CAPTURE (t));
17041 else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
17042 type = lambda_proxy_type (type);
17043 else
17045 bool id = DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t);
17046 if (id && TREE_CODE (DECLTYPE_TYPE_EXPR (t)) == BIT_NOT_EXPR
17047 && EXPR_P (type))
17048 /* In a template ~id could be either a complement expression
17049 or an unqualified-id naming a destructor; if instantiating
17050 it produces an expression, it's not an id-expression or
17051 member access. */
17052 id = false;
17053 type = finish_decltype_type (type, id, complain);
17055 return cp_build_qualified_type (type,
17056 cp_type_quals (t)
17057 | cp_type_quals (type),
17058 complain | tf_ignore_bad_quals);
17061 case TRAIT_TYPE:
17063 tree type1 = TRAIT_TYPE_TYPE1 (t);
17064 if (TYPE_P (type1))
17065 type1 = tsubst (type1, args, complain, in_decl);
17066 else
17067 type1 = tsubst_expr (type1, args, complain, in_decl);
17068 tree type2 = tsubst (TRAIT_TYPE_TYPE2 (t), args, complain, in_decl);
17069 type = finish_trait_type (TRAIT_TYPE_KIND (t), type1, type2, complain);
17070 return cp_build_qualified_type (type,
17071 cp_type_quals (t) | cp_type_quals (type),
17072 complain | tf_ignore_bad_quals);
17075 case TYPE_ARGUMENT_PACK:
17076 case NONTYPE_ARGUMENT_PACK:
17077 return tsubst_argument_pack (t, args, complain, in_decl);
17079 case VOID_CST:
17080 case INTEGER_CST:
17081 case REAL_CST:
17082 case STRING_CST:
17083 case PLUS_EXPR:
17084 case MINUS_EXPR:
17085 case NEGATE_EXPR:
17086 case NOP_EXPR:
17087 case INDIRECT_REF:
17088 case ADDR_EXPR:
17089 case CALL_EXPR:
17090 case ARRAY_REF:
17091 case SCOPE_REF:
17092 case OMP_ARRAY_SECTION:
17093 /* We should use one of the expression tsubsts for these codes. */
17094 gcc_unreachable ();
17096 default:
17097 sorry ("use of %qs in template", get_tree_code_name (code));
17098 return error_mark_node;
17102 /* Convenience wrapper over tsubst for substituting into the LHS
17103 of the :: scope resolution operator. */
17105 static tree
17106 tsubst_scope (tree t, tree args, tsubst_flags_t complain, tree in_decl)
17108 gcc_checking_assert (TYPE_P (t));
17109 return tsubst (t, args, complain | tf_qualifying_scope, in_decl);
17112 /* Convenience wrapper over tsubst for substituting into an id-expression
17113 without resolving its terminal name. */
17115 static tree
17116 tsubst_name (tree t, tree args, tsubst_flags_t complain, tree in_decl)
17118 return tsubst_expr (t, args, complain | tf_no_name_lookup, in_decl);
17121 /* OLDFNS is a lookup set of member functions from some class template, and
17122 NEWFNS is a lookup set of member functions from NEWTYPE, a specialization
17123 of that class template. Return the subset of NEWFNS which are
17124 specializations of a function from OLDFNS. */
17126 static tree
17127 filter_memfn_lookup (tree oldfns, tree newfns, tree newtype)
17129 /* Record all member functions from the old lookup set OLDFNS into
17130 VISIBLE_SET. */
17131 hash_set<tree> visible_set;
17132 bool seen_dep_using = false;
17133 for (tree fn : lkp_range (oldfns))
17135 if (TREE_CODE (fn) == USING_DECL)
17137 /* Imprecisely handle dependent using-decl by keeping all members
17138 in the new lookup set that are defined in a base class, i.e.
17139 members that could plausibly have been introduced by this
17140 dependent using-decl.
17141 FIXME: Track which members are introduced by a dependent
17142 using-decl precisely, perhaps by performing another lookup
17143 from the substituted USING_DECL_SCOPE. */
17144 gcc_checking_assert (DECL_DEPENDENT_P (fn));
17145 seen_dep_using = true;
17147 else
17148 visible_set.add (fn);
17151 /* Returns true iff (a less specialized version of) FN appeared in
17152 the old lookup set OLDFNS. */
17153 auto visible_p = [newtype, seen_dep_using, &visible_set] (tree fn) {
17154 if (DECL_CONTEXT (fn) != newtype)
17155 /* FN is a member function from a base class, introduced via a
17156 using-decl; if it might have been introduced by a dependent
17157 using-decl then just conservatively keep it, otherwise look
17158 in the old lookup set for FN exactly. */
17159 return seen_dep_using || visible_set.contains (fn);
17160 else if (TREE_CODE (fn) == TEMPLATE_DECL)
17161 /* FN is a member function template from the current class;
17162 look in the old lookup set for the TEMPLATE_DECL from which
17163 it was specialized. */
17164 return visible_set.contains (DECL_TI_TEMPLATE (fn));
17165 else
17166 /* FN is a non-template member function from the current class;
17167 look in the old lookup set for the FUNCTION_DECL from which
17168 it was specialized. */
17169 return visible_set.contains (DECL_TEMPLATE_RESULT
17170 (DECL_TI_TEMPLATE (fn)));
17173 bool lookup_changed_p = false;
17174 for (tree fn : lkp_range (newfns))
17175 if (!visible_p (fn))
17177 lookup_changed_p = true;
17178 break;
17180 if (!lookup_changed_p)
17181 return newfns;
17183 /* Filter out from NEWFNS the member functions that weren't
17184 previously visible according to OLDFNS. */
17185 tree filtered_fns = NULL_TREE;
17186 unsigned filtered_size = 0;
17187 for (tree fn : lkp_range (newfns))
17188 if (visible_p (fn))
17190 filtered_fns = lookup_add (fn, filtered_fns);
17191 filtered_size++;
17193 gcc_checking_assert (seen_dep_using
17194 ? filtered_size >= visible_set.elements ()
17195 : filtered_size == visible_set.elements ());
17197 return filtered_fns;
17200 /* tsubst a BASELINK. OBJECT_TYPE, if non-NULL, is the type of the
17201 expression on the left-hand side of the "." or "->" operator. We
17202 only do the lookup if we had a dependent BASELINK. Otherwise we
17203 adjust it onto the instantiated heirarchy. */
17205 static tree
17206 tsubst_baselink (tree baselink, tree object_type,
17207 tree args, tsubst_flags_t complain, tree in_decl)
17209 bool qualified_p = BASELINK_QUALIFIED_P (baselink);
17210 tree qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
17211 qualifying_scope = tsubst (qualifying_scope, args, complain, in_decl);
17213 tree optype = BASELINK_OPTYPE (baselink);
17214 optype = tsubst (optype, args, complain, in_decl);
17216 tree template_args = NULL_TREE;
17217 bool template_id_p = false;
17218 tree fns = BASELINK_FUNCTIONS (baselink);
17219 if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
17221 template_id_p = true;
17222 template_args = TREE_OPERAND (fns, 1);
17223 fns = TREE_OPERAND (fns, 0);
17224 if (template_args)
17225 template_args = tsubst_template_args (template_args, args,
17226 complain, in_decl);
17229 tree binfo_type = BINFO_TYPE (BASELINK_BINFO (baselink));
17230 binfo_type = tsubst (binfo_type, args, complain, in_decl);
17231 bool dependent_p = (binfo_type != BINFO_TYPE (BASELINK_BINFO (baselink))
17232 || optype != BASELINK_OPTYPE (baselink));
17234 if (dependent_p)
17236 tree name = OVL_NAME (fns);
17237 if (IDENTIFIER_CONV_OP_P (name))
17238 name = make_conv_op_name (optype);
17240 /* See maybe_dependent_member_ref. */
17241 if ((complain & tf_dguide) && dependent_scope_p (qualifying_scope))
17243 if (template_id_p)
17244 name = build2 (TEMPLATE_ID_EXPR, unknown_type_node, name,
17245 template_args);
17246 return build_qualified_name (NULL_TREE, qualifying_scope, name,
17247 /* ::template */false);
17250 if (name == complete_dtor_identifier)
17251 /* Treat as-if non-dependent below. */
17252 dependent_p = false;
17254 bool maybe_incomplete = BASELINK_FUNCTIONS_MAYBE_INCOMPLETE_P (baselink);
17255 baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1,
17256 complain);
17257 if (maybe_incomplete)
17259 /* Filter out from the new lookup set those functions which didn't
17260 appear in the original lookup set (in a less specialized form).
17261 This is needed to preserve the consistency of member lookup
17262 performed in an incomplete-class context, within which
17263 later-declared members ought to remain invisible. */
17264 BASELINK_FUNCTIONS (baselink)
17265 = filter_memfn_lookup (fns, BASELINK_FUNCTIONS (baselink),
17266 binfo_type);
17267 BASELINK_FUNCTIONS_MAYBE_INCOMPLETE_P (baselink) = true;
17270 if (!baselink)
17272 if ((complain & tf_error)
17273 && constructor_name_p (name, qualifying_scope))
17274 error ("cannot call constructor %<%T::%D%> directly",
17275 qualifying_scope, name);
17276 return error_mark_node;
17279 fns = BASELINK_FUNCTIONS (baselink);
17281 else
17283 /* We're going to overwrite pieces below, make a duplicate. */
17284 baselink = copy_node (baselink);
17286 if (qualifying_scope != BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink)))
17288 /* The decl we found was from non-dependent scope, but we still need
17289 to update the binfos for the instantiated qualifying_scope. */
17290 BASELINK_ACCESS_BINFO (baselink) = TYPE_BINFO (qualifying_scope);
17291 BASELINK_BINFO (baselink) = lookup_base (qualifying_scope, binfo_type,
17292 ba_unique, nullptr, complain);
17296 /* If lookup found a single function, mark it as used at this point.
17297 (If lookup found multiple functions the one selected later by
17298 overload resolution will be marked as used at that point.) */
17299 if (!template_id_p && !really_overloaded_fn (fns))
17301 tree fn = OVL_FIRST (fns);
17302 bool ok = mark_used (fn, complain);
17303 if (!ok && !(complain & tf_error))
17304 return error_mark_node;
17305 if (ok && BASELINK_P (baselink))
17306 /* We might have instantiated an auto function. */
17307 TREE_TYPE (baselink) = TREE_TYPE (fn);
17310 if (BASELINK_P (baselink))
17312 /* Add back the template arguments, if present. */
17313 if (template_id_p)
17314 BASELINK_FUNCTIONS (baselink)
17315 = build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, template_args);
17317 /* Update the conversion operator type. */
17318 BASELINK_OPTYPE (baselink) = optype;
17321 if (!object_type)
17322 object_type = current_class_type;
17324 if (qualified_p || !dependent_p)
17326 baselink = adjust_result_of_qualified_name_lookup (baselink,
17327 qualifying_scope,
17328 object_type);
17329 if (!qualified_p)
17330 /* We need to call adjust_result_of_qualified_name_lookup in case the
17331 destructor names a base class, but we unset BASELINK_QUALIFIED_P
17332 so that we still get virtual function binding. */
17333 BASELINK_QUALIFIED_P (baselink) = false;
17336 return baselink;
17339 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID. DONE is
17340 true if the qualified-id will be a postfix-expression in-and-of
17341 itself; false if more of the postfix-expression follows the
17342 QUALIFIED_ID. ADDRESS_P is true if the qualified-id is the operand
17343 of "&". */
17345 static tree
17346 tsubst_qualified_id (tree qualified_id, tree args,
17347 tsubst_flags_t complain, tree in_decl,
17348 bool done, bool address_p)
17350 tree expr;
17351 tree scope;
17352 tree name;
17353 bool is_template;
17354 tree template_args;
17355 location_t loc = EXPR_LOCATION (qualified_id);
17357 gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
17359 /* Figure out what name to look up. */
17360 name = TREE_OPERAND (qualified_id, 1);
17361 if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
17363 is_template = true;
17364 template_args = TREE_OPERAND (name, 1);
17365 if (template_args)
17366 template_args = tsubst_template_args (template_args, args,
17367 complain, in_decl);
17368 if (template_args == error_mark_node)
17369 return error_mark_node;
17370 name = TREE_OPERAND (name, 0);
17372 else
17374 is_template = false;
17375 template_args = NULL_TREE;
17378 /* Substitute into the qualifying scope. When there are no ARGS, we
17379 are just trying to simplify a non-dependent expression. In that
17380 case the qualifying scope may be dependent, and, in any case,
17381 substituting will not help. */
17382 scope = TREE_OPERAND (qualified_id, 0);
17383 if (args)
17385 scope = tsubst_scope (scope, args, complain, in_decl);
17386 expr = tsubst_name (name, args, complain, in_decl);
17388 else
17389 expr = name;
17391 if (dependent_scope_p (scope))
17393 if (TREE_CODE (expr) == SCOPE_REF)
17394 /* We built one in tsubst_baselink. */
17395 gcc_checking_assert (same_type_p (scope, TREE_OPERAND (expr, 0)));
17396 else
17398 if (is_template)
17399 expr = build_min_nt_loc (loc, TEMPLATE_ID_EXPR, expr,
17400 template_args);
17401 expr = build_qualified_name (NULL_TREE, scope, expr,
17402 QUALIFIED_NAME_IS_TEMPLATE
17403 (qualified_id));
17405 REF_PARENTHESIZED_P (expr) = REF_PARENTHESIZED_P (qualified_id);
17406 return expr;
17409 if (!BASELINK_P (name) && !DECL_P (expr))
17411 if (TREE_CODE (expr) == BIT_NOT_EXPR)
17413 /* A BIT_NOT_EXPR is used to represent a destructor. */
17414 if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
17416 error ("qualifying type %qT does not match destructor name ~%qT",
17417 scope, TREE_OPERAND (expr, 0));
17418 expr = error_mark_node;
17420 else
17421 expr = lookup_qualified_name (scope, complete_dtor_identifier,
17422 LOOK_want::NORMAL, false);
17424 else
17425 expr = lookup_qualified_name (scope, expr, LOOK_want::NORMAL, false);
17426 if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
17427 ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
17429 if (complain & tf_error)
17431 auto_diagnostic_group d;
17432 error ("dependent-name %qE is parsed as a non-type, but "
17433 "instantiation yields a type", qualified_id);
17434 inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
17436 return error_mark_node;
17440 if (DECL_P (expr))
17442 if (!check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
17443 scope, complain))
17444 return error_mark_node;
17445 /* Remember that there was a reference to this entity. */
17446 if (!mark_used (expr, complain) && !(complain & tf_error))
17447 return error_mark_node;
17450 if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
17452 if (complain & tf_error)
17453 qualified_name_lookup_error (scope,
17454 TREE_OPERAND (qualified_id, 1),
17455 expr, input_location);
17456 return error_mark_node;
17459 if (is_template)
17461 if (variable_template_p (expr))
17462 expr = lookup_and_finish_template_variable (expr, template_args,
17463 complain);
17464 else
17465 expr = lookup_template_function (expr, template_args);
17468 if (expr == error_mark_node && complain & tf_error)
17469 qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
17470 expr, input_location);
17471 else if (TYPE_P (scope))
17473 expr = (adjust_result_of_qualified_name_lookup
17474 (expr, scope, current_nonlambda_class_type ()));
17475 expr = (finish_qualified_id_expr
17476 (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
17477 QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
17478 /*template_arg_p=*/false, complain));
17481 /* Expressions do not generally have reference type. */
17482 if (TREE_CODE (expr) != SCOPE_REF
17483 /* However, if we're about to form a pointer-to-member, we just
17484 want the referenced member referenced. */
17485 && TREE_CODE (expr) != OFFSET_REF)
17486 expr = convert_from_reference (expr);
17488 if (REF_PARENTHESIZED_P (qualified_id))
17489 expr = force_paren_expr (expr);
17491 expr = maybe_wrap_with_location (expr, loc);
17493 return expr;
17496 /* tsubst the initializer for a VAR_DECL. INIT is the unsubstituted
17497 initializer, DECL is the substituted VAR_DECL. Other arguments are as
17498 for tsubst. */
17500 static tree
17501 tsubst_init (tree init, tree decl, tree args,
17502 tsubst_flags_t complain, tree in_decl)
17504 if (!init)
17505 return NULL_TREE;
17507 init = tsubst_expr (init, args, complain, in_decl);
17509 tree type = TREE_TYPE (decl);
17511 if (!init && type != error_mark_node)
17513 if (tree auto_node = type_uses_auto (type))
17515 if (!CLASS_PLACEHOLDER_TEMPLATE (auto_node))
17517 if (complain & tf_error)
17518 error ("initializer for %q#D expands to an empty list "
17519 "of expressions", decl);
17520 return error_mark_node;
17523 else if (!dependent_type_p (type))
17525 /* If we had an initializer but it
17526 instantiated to nothing,
17527 value-initialize the object. This will
17528 only occur when the initializer was a
17529 pack expansion where the parameter packs
17530 used in that expansion were of length
17531 zero. */
17532 init = build_value_init (type, complain);
17533 if (TREE_CODE (init) == AGGR_INIT_EXPR)
17534 init = get_target_expr (init, complain);
17535 if (TREE_CODE (init) == TARGET_EXPR)
17536 TARGET_EXPR_DIRECT_INIT_P (init) = true;
17540 return init;
17543 /* If T is a reference to a dependent member of the current instantiation C and
17544 we are trying to refer to that member in a partial instantiation of C,
17545 return a SCOPE_REF; otherwise, return NULL_TREE.
17547 This can happen when forming a C++17 deduction guide, as in PR96199. */
17549 static tree
17550 maybe_dependent_member_ref (tree t, tree args, tsubst_flags_t complain,
17551 tree in_decl)
17553 if (!(complain & tf_dguide))
17554 return NULL_TREE;
17556 tree decl = (t && TYPE_P (t)) ? TYPE_NAME (t) : t;
17557 if (!decl || !DECL_P (decl))
17558 return NULL_TREE;
17560 tree ctx = context_for_name_lookup (decl);
17561 if (!CLASS_TYPE_P (ctx))
17562 return NULL_TREE;
17564 ctx = tsubst (ctx, args, complain, in_decl);
17565 if (!dependent_scope_p (ctx))
17566 return NULL_TREE;
17568 if (TYPE_P (t))
17570 if (typedef_variant_p (t))
17571 t = strip_typedefs (t);
17572 tree decl = TYPE_NAME (t);
17573 if (decl)
17574 decl = maybe_dependent_member_ref (decl, args, complain, in_decl);
17575 if (!decl)
17576 return NULL_TREE;
17577 return cp_build_qualified_type (TREE_TYPE (decl), cp_type_quals (t),
17578 complain);
17581 tree name = DECL_NAME (t);
17582 tree fullname = name;
17583 if (instantiates_primary_template_p (t))
17585 tree tinfo = get_template_info (t);
17586 name = DECL_NAME (TI_TEMPLATE (tinfo));
17587 tree targs = INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo));
17588 targs = tsubst_template_args (targs, args, complain, in_decl);
17589 fullname = build_nt (TEMPLATE_ID_EXPR, name, targs);
17592 if (TREE_CODE (t) == TYPE_DECL)
17594 if (TREE_CODE (TREE_TYPE (t)) == TYPENAME_TYPE
17595 && TYPE_NAME (TREE_TYPE (t)) == t)
17596 /* The TYPE_DECL for a typename has DECL_CONTEXT of the typename
17597 scope, but it doesn't need to be rewritten again. */
17598 return NULL_TREE;
17599 tree type = build_typename_type (ctx, name, fullname, typename_type);
17600 return TYPE_NAME (type);
17602 else if (DECL_TYPE_TEMPLATE_P (t))
17603 return make_unbound_class_template (ctx, name,
17604 NULL_TREE, complain);
17605 else
17606 return build_qualified_name (NULL_TREE, ctx, fullname,
17607 TREE_CODE (t) == TEMPLATE_DECL);
17610 /* Helper function for tsubst_omp_clauses, used for instantiation of
17611 OMP_CLAUSE_DECL of clauses. */
17613 static tree
17614 tsubst_omp_clause_decl (tree decl, tree args, tsubst_flags_t complain,
17615 tree in_decl, tree *iterator_cache)
17617 if (decl == NULL_TREE || decl == ridpointers[RID_OMP_ALL_MEMORY])
17618 return decl;
17620 /* Handle OpenMP iterators. */
17621 if (TREE_CODE (decl) == TREE_LIST
17622 && TREE_PURPOSE (decl)
17623 && TREE_CODE (TREE_PURPOSE (decl)) == TREE_VEC)
17625 tree ret;
17626 if (iterator_cache[0] == TREE_PURPOSE (decl))
17627 ret = iterator_cache[1];
17628 else
17630 tree *tp = &ret;
17631 begin_scope (sk_omp, NULL);
17632 for (tree it = TREE_PURPOSE (decl); it; it = TREE_CHAIN (it))
17634 *tp = copy_node (it);
17635 TREE_VEC_ELT (*tp, 0)
17636 = tsubst_decl (TREE_VEC_ELT (it, 0), args, complain);
17637 DECL_CONTEXT (TREE_VEC_ELT (*tp, 0)) = current_function_decl;
17638 pushdecl (TREE_VEC_ELT (*tp, 0));
17639 TREE_VEC_ELT (*tp, 1)
17640 = tsubst_stmt (TREE_VEC_ELT (it, 1), args, complain, in_decl);
17641 TREE_VEC_ELT (*tp, 2)
17642 = tsubst_stmt (TREE_VEC_ELT (it, 2), args, complain, in_decl);
17643 TREE_VEC_ELT (*tp, 3)
17644 = tsubst_stmt (TREE_VEC_ELT (it, 3), args, complain, in_decl);
17645 TREE_CHAIN (*tp) = NULL_TREE;
17646 tp = &TREE_CHAIN (*tp);
17648 TREE_VEC_ELT (ret, 5) = poplevel (1, 1, 0);
17649 iterator_cache[0] = TREE_PURPOSE (decl);
17650 iterator_cache[1] = ret;
17652 return build_tree_list (ret, tsubst_omp_clause_decl (TREE_VALUE (decl),
17653 args, complain,
17654 in_decl, NULL));
17657 /* Handle an OpenMP array section represented as a TREE_LIST (or
17658 OMP_CLAUSE_DOACROSS_KIND). An OMP_CLAUSE_DOACROSS (with a depend
17659 kind of OMP_CLAUSE_DOACROSS_SINK) can also be represented as a
17660 TREE_LIST. We can handle it exactly the same as an array section
17661 (purpose, value, and a chain), even though the nomenclature
17662 (low_bound, length, etc) is different. */
17663 if (TREE_CODE (decl) == TREE_LIST)
17665 tree low_bound
17666 = tsubst_stmt (TREE_PURPOSE (decl), args, complain, in_decl);
17667 tree length = tsubst_stmt (TREE_VALUE (decl), args, complain, in_decl);
17668 tree chain = tsubst_omp_clause_decl (TREE_CHAIN (decl), args, complain,
17669 in_decl, NULL);
17670 if (TREE_PURPOSE (decl) == low_bound
17671 && TREE_VALUE (decl) == length
17672 && TREE_CHAIN (decl) == chain)
17673 return decl;
17674 tree ret = tree_cons (low_bound, length, chain);
17675 OMP_CLAUSE_DOACROSS_SINK_NEGATIVE (ret)
17676 = OMP_CLAUSE_DOACROSS_SINK_NEGATIVE (decl);
17677 return ret;
17679 else if (TREE_CODE (decl) == OMP_ARRAY_SECTION)
17681 tree low_bound
17682 = tsubst_stmt (TREE_OPERAND (decl, 1), args, complain, in_decl);
17683 tree length = tsubst_stmt (TREE_OPERAND (decl, 2), args, complain,
17684 in_decl);
17685 tree base = tsubst_omp_clause_decl (TREE_OPERAND (decl, 0), args,
17686 complain, in_decl, NULL);
17687 if (TREE_OPERAND (decl, 0) == base
17688 && TREE_OPERAND (decl, 1) == low_bound
17689 && TREE_OPERAND (decl, 2) == length)
17690 return decl;
17691 return build3 (OMP_ARRAY_SECTION, TREE_TYPE (base), base, low_bound,
17692 length);
17694 tree ret = tsubst_stmt (decl, args, complain, in_decl);
17695 /* Undo convert_from_reference tsubst_expr could have called. */
17696 if (decl
17697 && REFERENCE_REF_P (ret)
17698 && !REFERENCE_REF_P (decl))
17699 ret = TREE_OPERAND (ret, 0);
17700 return ret;
17703 /* Like tsubst_copy, but specifically for OpenMP clauses. */
17705 static tree
17706 tsubst_omp_clauses (tree clauses, enum c_omp_region_type ort,
17707 tree args, tsubst_flags_t complain, tree in_decl)
17709 tree new_clauses = NULL_TREE, nc, oc;
17710 tree linear_no_step = NULL_TREE;
17711 tree iterator_cache[2] = { NULL_TREE, NULL_TREE };
17713 for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
17715 nc = copy_node (oc);
17716 OMP_CLAUSE_CHAIN (nc) = new_clauses;
17717 new_clauses = nc;
17719 switch (OMP_CLAUSE_CODE (nc))
17721 case OMP_CLAUSE_LASTPRIVATE:
17722 if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
17724 OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
17725 tsubst_stmt (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args,
17726 complain, in_decl);
17727 OMP_CLAUSE_LASTPRIVATE_STMT (nc)
17728 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
17730 /* FALLTHRU */
17731 case OMP_CLAUSE_PRIVATE:
17732 case OMP_CLAUSE_SHARED:
17733 case OMP_CLAUSE_FIRSTPRIVATE:
17734 case OMP_CLAUSE_COPYIN:
17735 case OMP_CLAUSE_COPYPRIVATE:
17736 case OMP_CLAUSE_UNIFORM:
17737 case OMP_CLAUSE_DEPEND:
17738 case OMP_CLAUSE_DOACROSS:
17739 case OMP_CLAUSE_AFFINITY:
17740 case OMP_CLAUSE_FROM:
17741 case OMP_CLAUSE_TO:
17742 case OMP_CLAUSE_MAP:
17743 case OMP_CLAUSE__CACHE_:
17744 case OMP_CLAUSE_NONTEMPORAL:
17745 case OMP_CLAUSE_USE_DEVICE_PTR:
17746 case OMP_CLAUSE_USE_DEVICE_ADDR:
17747 case OMP_CLAUSE_IS_DEVICE_PTR:
17748 case OMP_CLAUSE_HAS_DEVICE_ADDR:
17749 case OMP_CLAUSE_INCLUSIVE:
17750 case OMP_CLAUSE_EXCLUSIVE:
17751 OMP_CLAUSE_DECL (nc)
17752 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17753 in_decl, iterator_cache);
17754 break;
17755 case OMP_CLAUSE_NUM_TEAMS:
17756 if (OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (oc))
17757 OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (nc)
17758 = tsubst_stmt (OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (oc), args,
17759 complain, in_decl);
17760 /* FALLTHRU */
17761 case OMP_CLAUSE_TILE:
17762 case OMP_CLAUSE_IF:
17763 case OMP_CLAUSE_SELF:
17764 case OMP_CLAUSE_NUM_THREADS:
17765 case OMP_CLAUSE_SCHEDULE:
17766 case OMP_CLAUSE_COLLAPSE:
17767 case OMP_CLAUSE_FINAL:
17768 case OMP_CLAUSE_DEVICE:
17769 case OMP_CLAUSE_DIST_SCHEDULE:
17770 case OMP_CLAUSE_THREAD_LIMIT:
17771 case OMP_CLAUSE_SAFELEN:
17772 case OMP_CLAUSE_SIMDLEN:
17773 case OMP_CLAUSE_NUM_TASKS:
17774 case OMP_CLAUSE_GRAINSIZE:
17775 case OMP_CLAUSE_PRIORITY:
17776 case OMP_CLAUSE_ORDERED:
17777 case OMP_CLAUSE_HINT:
17778 case OMP_CLAUSE_FILTER:
17779 case OMP_CLAUSE_NUM_GANGS:
17780 case OMP_CLAUSE_NUM_WORKERS:
17781 case OMP_CLAUSE_VECTOR_LENGTH:
17782 case OMP_CLAUSE_WORKER:
17783 case OMP_CLAUSE_VECTOR:
17784 case OMP_CLAUSE_ASYNC:
17785 case OMP_CLAUSE_WAIT:
17786 case OMP_CLAUSE_DETACH:
17787 OMP_CLAUSE_OPERAND (nc, 0)
17788 = tsubst_stmt (OMP_CLAUSE_OPERAND (oc, 0), args, complain, in_decl);
17789 break;
17790 case OMP_CLAUSE_PARTIAL:
17791 OMP_CLAUSE_PARTIAL_EXPR (nc)
17792 = tsubst_expr (OMP_CLAUSE_PARTIAL_EXPR (oc), args, complain,
17793 in_decl);
17794 break;
17795 case OMP_CLAUSE_SIZES:
17796 OMP_CLAUSE_SIZES_LIST (nc)
17797 = tsubst_expr (OMP_CLAUSE_SIZES_LIST (oc), args, complain,
17798 in_decl);
17799 break;
17800 case OMP_CLAUSE_REDUCTION:
17801 case OMP_CLAUSE_IN_REDUCTION:
17802 case OMP_CLAUSE_TASK_REDUCTION:
17803 if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc))
17805 tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc);
17806 if (TREE_CODE (placeholder) == SCOPE_REF)
17808 tree scope = tsubst (TREE_OPERAND (placeholder, 0), args,
17809 complain, in_decl);
17810 OMP_CLAUSE_REDUCTION_PLACEHOLDER (nc)
17811 = build_qualified_name (NULL_TREE, scope,
17812 TREE_OPERAND (placeholder, 1),
17813 false);
17815 else
17816 gcc_assert (identifier_p (placeholder));
17818 OMP_CLAUSE_DECL (nc)
17819 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17820 in_decl, NULL);
17821 break;
17822 case OMP_CLAUSE_GANG:
17823 case OMP_CLAUSE_ALIGNED:
17824 OMP_CLAUSE_DECL (nc)
17825 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17826 in_decl, NULL);
17827 OMP_CLAUSE_OPERAND (nc, 1)
17828 = tsubst_stmt (OMP_CLAUSE_OPERAND (oc, 1), args, complain, in_decl);
17829 break;
17830 case OMP_CLAUSE_ALLOCATE:
17831 OMP_CLAUSE_DECL (nc)
17832 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17833 in_decl, NULL);
17834 OMP_CLAUSE_OPERAND (nc, 1)
17835 = tsubst_stmt (OMP_CLAUSE_OPERAND (oc, 1), args, complain, in_decl);
17836 OMP_CLAUSE_OPERAND (nc, 2)
17837 = tsubst_stmt (OMP_CLAUSE_OPERAND (oc, 2), args, complain, in_decl);
17838 break;
17839 case OMP_CLAUSE_LINEAR:
17840 OMP_CLAUSE_DECL (nc)
17841 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17842 in_decl, NULL);
17843 if (OMP_CLAUSE_LINEAR_STEP (oc) == NULL_TREE)
17845 gcc_assert (!linear_no_step);
17846 linear_no_step = nc;
17848 else if (OMP_CLAUSE_LINEAR_VARIABLE_STRIDE (oc))
17849 OMP_CLAUSE_LINEAR_STEP (nc)
17850 = tsubst_omp_clause_decl (OMP_CLAUSE_LINEAR_STEP (oc), args,
17851 complain, in_decl, NULL);
17852 else
17853 OMP_CLAUSE_LINEAR_STEP (nc)
17854 = tsubst_stmt (OMP_CLAUSE_LINEAR_STEP (oc), args,
17855 complain, in_decl);
17856 break;
17857 case OMP_CLAUSE_NOWAIT:
17858 case OMP_CLAUSE_DEFAULT:
17859 case OMP_CLAUSE_UNTIED:
17860 case OMP_CLAUSE_MERGEABLE:
17861 case OMP_CLAUSE_INBRANCH:
17862 case OMP_CLAUSE_NOTINBRANCH:
17863 case OMP_CLAUSE_PROC_BIND:
17864 case OMP_CLAUSE_FOR:
17865 case OMP_CLAUSE_PARALLEL:
17866 case OMP_CLAUSE_SECTIONS:
17867 case OMP_CLAUSE_TASKGROUP:
17868 case OMP_CLAUSE_NOGROUP:
17869 case OMP_CLAUSE_THREADS:
17870 case OMP_CLAUSE_SIMD:
17871 case OMP_CLAUSE_DEFAULTMAP:
17872 case OMP_CLAUSE_ORDER:
17873 case OMP_CLAUSE_BIND:
17874 case OMP_CLAUSE_INDEPENDENT:
17875 case OMP_CLAUSE_AUTO:
17876 case OMP_CLAUSE_SEQ:
17877 case OMP_CLAUSE_IF_PRESENT:
17878 case OMP_CLAUSE_FINALIZE:
17879 case OMP_CLAUSE_NOHOST:
17880 case OMP_CLAUSE_FULL:
17881 break;
17882 default:
17883 gcc_unreachable ();
17885 if ((ort & C_ORT_OMP_DECLARE_SIMD) == C_ORT_OMP)
17886 switch (OMP_CLAUSE_CODE (nc))
17888 case OMP_CLAUSE_SHARED:
17889 case OMP_CLAUSE_PRIVATE:
17890 case OMP_CLAUSE_FIRSTPRIVATE:
17891 case OMP_CLAUSE_LASTPRIVATE:
17892 case OMP_CLAUSE_COPYPRIVATE:
17893 case OMP_CLAUSE_LINEAR:
17894 case OMP_CLAUSE_REDUCTION:
17895 case OMP_CLAUSE_IN_REDUCTION:
17896 case OMP_CLAUSE_TASK_REDUCTION:
17897 case OMP_CLAUSE_USE_DEVICE_PTR:
17898 case OMP_CLAUSE_USE_DEVICE_ADDR:
17899 case OMP_CLAUSE_IS_DEVICE_PTR:
17900 case OMP_CLAUSE_HAS_DEVICE_ADDR:
17901 case OMP_CLAUSE_INCLUSIVE:
17902 case OMP_CLAUSE_EXCLUSIVE:
17903 case OMP_CLAUSE_ALLOCATE:
17904 /* tsubst_expr on SCOPE_REF results in returning
17905 finish_non_static_data_member result. Undo that here. */
17906 if (TREE_CODE (OMP_CLAUSE_DECL (oc)) == SCOPE_REF
17907 && (TREE_CODE (TREE_OPERAND (OMP_CLAUSE_DECL (oc), 1))
17908 == IDENTIFIER_NODE))
17910 tree t = OMP_CLAUSE_DECL (nc);
17911 tree v = t;
17912 while (v)
17913 switch (TREE_CODE (v))
17915 case COMPONENT_REF:
17916 case MEM_REF:
17917 case INDIRECT_REF:
17918 CASE_CONVERT:
17919 case POINTER_PLUS_EXPR:
17920 v = TREE_OPERAND (v, 0);
17921 continue;
17922 case PARM_DECL:
17923 if (DECL_CONTEXT (v) == current_function_decl
17924 && DECL_ARTIFICIAL (v)
17925 && DECL_NAME (v) == this_identifier)
17926 OMP_CLAUSE_DECL (nc) = TREE_OPERAND (t, 1);
17927 /* FALLTHRU */
17928 default:
17929 v = NULL_TREE;
17930 break;
17933 else if (VAR_P (OMP_CLAUSE_DECL (oc))
17934 && DECL_HAS_VALUE_EXPR_P (OMP_CLAUSE_DECL (oc))
17935 && DECL_ARTIFICIAL (OMP_CLAUSE_DECL (oc))
17936 && DECL_LANG_SPECIFIC (OMP_CLAUSE_DECL (oc))
17937 && DECL_OMP_PRIVATIZED_MEMBER (OMP_CLAUSE_DECL (oc)))
17939 tree decl = OMP_CLAUSE_DECL (nc);
17940 if (VAR_P (decl))
17942 retrofit_lang_decl (decl);
17943 DECL_OMP_PRIVATIZED_MEMBER (decl) = 1;
17946 break;
17947 default:
17948 break;
17952 new_clauses = nreverse (new_clauses);
17953 if (ort != C_ORT_OMP_DECLARE_SIMD)
17955 new_clauses = finish_omp_clauses (new_clauses, ort);
17956 if (linear_no_step)
17957 for (nc = new_clauses; nc; nc = OMP_CLAUSE_CHAIN (nc))
17958 if (nc == linear_no_step)
17960 OMP_CLAUSE_LINEAR_STEP (nc) = NULL_TREE;
17961 break;
17964 return new_clauses;
17967 /* Like tsubst_expr, but unshare TREE_LIST nodes. */
17969 static tree
17970 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
17971 tree in_decl)
17973 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
17975 tree purpose, value, chain;
17977 if (t == NULL)
17978 return t;
17980 if (TREE_CODE (t) != TREE_LIST)
17981 return tsubst_expr (t, args, complain, in_decl);
17983 if (t == void_list_node)
17984 return t;
17986 purpose = TREE_PURPOSE (t);
17987 if (purpose)
17988 purpose = RECUR (purpose);
17989 value = TREE_VALUE (t);
17990 if (value)
17992 if (TREE_CODE (value) != LABEL_DECL)
17993 value = RECUR (value);
17994 else
17996 value = lookup_label (DECL_NAME (value));
17997 gcc_assert (TREE_CODE (value) == LABEL_DECL);
17998 TREE_USED (value) = 1;
18001 chain = TREE_CHAIN (t);
18002 if (chain && chain != void_type_node)
18003 chain = RECUR (chain);
18004 return tree_cons (purpose, value, chain);
18005 #undef RECUR
18008 /* Used to temporarily communicate the list of #pragma omp parallel
18009 clauses to #pragma omp for instantiation if they are combined
18010 together. */
18012 static tree *omp_parallel_combined_clauses;
18014 static tree tsubst_decomp_names (tree, tree, tree, tsubst_flags_t, tree,
18015 cp_decomp *);
18017 /* Substitute one OMP_FOR iterator. */
18019 static bool
18020 tsubst_omp_for_iterator (tree t, int i, tree declv, tree &orig_declv,
18021 tree initv, tree condv, tree incrv, tree *clauses,
18022 tree args, tsubst_flags_t complain, tree in_decl)
18024 #define RECUR(NODE) \
18025 tsubst_stmt ((NODE), args, complain, in_decl)
18026 tree decl, init, cond = NULL_TREE, incr = NULL_TREE;
18027 bool ret = false;
18029 init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
18030 gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
18032 decl = TREE_OPERAND (init, 0);
18033 init = TREE_OPERAND (init, 1);
18034 tree decl_expr = NULL_TREE;
18035 bool range_for = TREE_VEC_ELT (OMP_FOR_COND (t), i) == global_namespace;
18036 if (range_for)
18038 bool decomp = false;
18039 if (decl != error_mark_node && DECL_HAS_VALUE_EXPR_P (decl))
18041 tree v = DECL_VALUE_EXPR (decl);
18042 if (TREE_CODE (v) == ARRAY_REF
18043 && DECL_DECOMPOSITION_P (TREE_OPERAND (v, 0)))
18045 cp_decomp decomp_d = { NULL_TREE, 0 };
18046 tree d = tsubst_decl (TREE_OPERAND (v, 0), args, complain);
18047 maybe_push_decl (d);
18048 d = tsubst_decomp_names (d, TREE_OPERAND (v, 0), args, complain,
18049 in_decl, &decomp_d);
18050 decomp = true;
18051 if (d == error_mark_node)
18052 decl = error_mark_node;
18053 else
18054 for (unsigned int i = 0; i < decomp_d.count; i++)
18056 if (!DECL_HAS_VALUE_EXPR_P (decomp_d.decl))
18058 tree v = build_nt (ARRAY_REF, d,
18059 size_int (decomp_d.count - i - 1),
18060 NULL_TREE, NULL_TREE);
18061 SET_DECL_VALUE_EXPR (decomp_d.decl, v);
18062 DECL_HAS_VALUE_EXPR_P (decomp_d.decl) = 1;
18064 fit_decomposition_lang_decl (decomp_d.decl, d);
18065 decomp_d.decl = DECL_CHAIN (decomp_d.decl);
18069 decl = tsubst_decl (decl, args, complain);
18070 if (!decomp)
18071 maybe_push_decl (decl);
18073 else if (init && TREE_CODE (init) == DECL_EXPR)
18075 /* We need to jump through some hoops to handle declarations in the
18076 init-statement, since we might need to handle auto deduction,
18077 but we need to keep control of initialization. */
18078 decl_expr = init;
18079 init = DECL_INITIAL (DECL_EXPR_DECL (init));
18080 decl = tsubst_decl (decl, args, complain);
18082 else
18084 if (TREE_CODE (decl) == SCOPE_REF)
18086 decl = RECUR (decl);
18087 if (TREE_CODE (decl) == COMPONENT_REF)
18089 tree v = decl;
18090 while (v)
18091 switch (TREE_CODE (v))
18093 case COMPONENT_REF:
18094 case MEM_REF:
18095 case INDIRECT_REF:
18096 CASE_CONVERT:
18097 case POINTER_PLUS_EXPR:
18098 v = TREE_OPERAND (v, 0);
18099 continue;
18100 case PARM_DECL:
18101 if (DECL_CONTEXT (v) == current_function_decl
18102 && DECL_ARTIFICIAL (v)
18103 && DECL_NAME (v) == this_identifier)
18105 decl = TREE_OPERAND (decl, 1);
18106 decl = omp_privatize_field (decl, false);
18108 /* FALLTHRU */
18109 default:
18110 v = NULL_TREE;
18111 break;
18115 else
18116 decl = RECUR (decl);
18118 if (init && TREE_CODE (init) == TREE_VEC)
18120 init = copy_node (init);
18121 TREE_VEC_ELT (init, 0)
18122 = tsubst_decl (TREE_VEC_ELT (init, 0), args, complain);
18123 TREE_VEC_ELT (init, 1) = RECUR (TREE_VEC_ELT (init, 1));
18124 TREE_VEC_ELT (init, 2) = RECUR (TREE_VEC_ELT (init, 2));
18126 else
18127 init = RECUR (init);
18129 if (orig_declv && OMP_FOR_ORIG_DECLS (t))
18131 tree o = TREE_VEC_ELT (OMP_FOR_ORIG_DECLS (t), i);
18132 if (TREE_CODE (o) == TREE_LIST)
18133 TREE_VEC_ELT (orig_declv, i)
18134 = tree_cons (RECUR (TREE_PURPOSE (o)),
18135 RECUR (TREE_VALUE (o)),
18136 NULL_TREE);
18137 else
18138 TREE_VEC_ELT (orig_declv, i) = RECUR (o);
18141 if (range_for)
18143 tree this_pre_body = NULL_TREE;
18144 tree orig_init = NULL_TREE;
18145 tree orig_decl = NULL_TREE;
18146 tree init_sl = NULL_TREE;
18147 cp_convert_omp_range_for (this_pre_body, init_sl, decl, orig_decl, init,
18148 orig_init, cond, incr, true);
18149 if (orig_decl)
18151 if (orig_declv == NULL_TREE)
18152 orig_declv = copy_node (declv);
18153 TREE_VEC_ELT (orig_declv, i) = orig_decl;
18154 ret = true;
18156 else if (orig_declv)
18157 TREE_VEC_ELT (orig_declv, i) = decl;
18160 tree auto_node = type_uses_auto (TREE_TYPE (decl));
18161 if (!range_for && auto_node && init)
18162 TREE_TYPE (decl)
18163 = do_auto_deduction (TREE_TYPE (decl), init, auto_node, complain);
18165 gcc_assert (!type_dependent_expression_p (decl));
18167 if (!CLASS_TYPE_P (TREE_TYPE (decl)) || range_for)
18169 if (decl_expr)
18171 /* Declare the variable, but don't let that initialize it. */
18172 tree init_sav = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
18173 DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL_TREE;
18174 RECUR (decl_expr);
18175 DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init_sav;
18178 if (!range_for)
18180 cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
18181 if (COMPARISON_CLASS_P (cond)
18182 && TREE_CODE (TREE_OPERAND (cond, 1)) == TREE_VEC)
18184 tree lhs = RECUR (TREE_OPERAND (cond, 0));
18185 tree rhs = copy_node (TREE_OPERAND (cond, 1));
18186 TREE_VEC_ELT (rhs, 0)
18187 = tsubst_decl (TREE_VEC_ELT (rhs, 0), args, complain);
18188 TREE_VEC_ELT (rhs, 1) = RECUR (TREE_VEC_ELT (rhs, 1));
18189 TREE_VEC_ELT (rhs, 2) = RECUR (TREE_VEC_ELT (rhs, 2));
18190 cond = build2 (TREE_CODE (cond), TREE_TYPE (cond),
18191 lhs, rhs);
18193 else
18194 cond = RECUR (cond);
18195 incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
18196 if (TREE_CODE (incr) == MODIFY_EXPR)
18198 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18199 tree rhs = RECUR (TREE_OPERAND (incr, 1));
18200 incr = build_x_modify_expr (EXPR_LOCATION (incr), lhs,
18201 NOP_EXPR, rhs, NULL_TREE, complain);
18203 else
18204 incr = RECUR (incr);
18205 if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
18206 TREE_VEC_ELT (orig_declv, i) = decl;
18208 TREE_VEC_ELT (declv, i) = decl;
18209 TREE_VEC_ELT (initv, i) = init;
18210 TREE_VEC_ELT (condv, i) = cond;
18211 TREE_VEC_ELT (incrv, i) = incr;
18212 return ret;
18215 if (decl_expr)
18217 /* Declare and initialize the variable. */
18218 RECUR (decl_expr);
18219 init = NULL_TREE;
18221 else if (init)
18223 tree *pc;
18224 int j;
18225 for (j = ((omp_parallel_combined_clauses == NULL
18226 || TREE_CODE (t) == OMP_LOOP) ? 1 : 0); j < 2; j++)
18228 for (pc = j ? clauses : omp_parallel_combined_clauses; *pc; )
18230 if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_PRIVATE
18231 && OMP_CLAUSE_DECL (*pc) == decl)
18232 break;
18233 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_LASTPRIVATE
18234 && OMP_CLAUSE_DECL (*pc) == decl)
18236 if (j)
18237 break;
18238 /* Move lastprivate (decl) clause to OMP_FOR_CLAUSES. */
18239 tree c = *pc;
18240 *pc = OMP_CLAUSE_CHAIN (c);
18241 OMP_CLAUSE_CHAIN (c) = *clauses;
18242 *clauses = c;
18244 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_FIRSTPRIVATE
18245 && OMP_CLAUSE_DECL (*pc) == decl)
18247 error ("iteration variable %qD should not be firstprivate",
18248 decl);
18249 *pc = OMP_CLAUSE_CHAIN (*pc);
18251 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_REDUCTION
18252 && OMP_CLAUSE_DECL (*pc) == decl)
18254 error ("iteration variable %qD should not be reduction",
18255 decl);
18256 *pc = OMP_CLAUSE_CHAIN (*pc);
18258 else
18259 pc = &OMP_CLAUSE_CHAIN (*pc);
18261 if (*pc)
18262 break;
18264 if (*pc == NULL_TREE)
18266 tree c = build_omp_clause (input_location,
18267 TREE_CODE (t) == OMP_LOOP
18268 ? OMP_CLAUSE_LASTPRIVATE
18269 : OMP_CLAUSE_PRIVATE);
18270 OMP_CLAUSE_DECL (c) = decl;
18271 c = finish_omp_clauses (c, C_ORT_OMP);
18272 if (c)
18274 OMP_CLAUSE_CHAIN (c) = *clauses;
18275 *clauses = c;
18279 cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
18280 if (COMPARISON_CLASS_P (cond))
18282 tree op0 = RECUR (TREE_OPERAND (cond, 0));
18283 tree op1 = RECUR (TREE_OPERAND (cond, 1));
18284 cond = build2 (TREE_CODE (cond), boolean_type_node, op0, op1);
18286 else
18287 cond = RECUR (cond);
18288 incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
18289 switch (TREE_CODE (incr))
18291 case PREINCREMENT_EXPR:
18292 case PREDECREMENT_EXPR:
18293 case POSTINCREMENT_EXPR:
18294 case POSTDECREMENT_EXPR:
18295 incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
18296 RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
18297 break;
18298 case MODIFY_EXPR:
18299 if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
18300 || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
18302 tree rhs = TREE_OPERAND (incr, 1);
18303 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18304 tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
18305 tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
18306 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18307 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
18308 rhs0, rhs1));
18310 else
18311 incr = RECUR (incr);
18312 break;
18313 case MODOP_EXPR:
18314 if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
18315 || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
18317 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18318 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18319 build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
18320 TREE_TYPE (decl), lhs,
18321 RECUR (TREE_OPERAND (incr, 2))));
18323 else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
18324 && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
18325 || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
18327 tree rhs = TREE_OPERAND (incr, 2);
18328 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18329 tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
18330 tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
18331 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18332 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
18333 rhs0, rhs1));
18335 else
18336 incr = RECUR (incr);
18337 break;
18338 default:
18339 incr = RECUR (incr);
18340 break;
18343 if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
18344 TREE_VEC_ELT (orig_declv, i) = decl;
18345 TREE_VEC_ELT (declv, i) = decl;
18346 TREE_VEC_ELT (initv, i) = init;
18347 TREE_VEC_ELT (condv, i) = cond;
18348 TREE_VEC_ELT (incrv, i) = incr;
18349 return false;
18350 #undef RECUR
18353 /* Helper function of tsubst_expr, find OMP_TEAMS inside
18354 of OMP_TARGET's body. */
18356 static tree
18357 tsubst_find_omp_teams (tree *tp, int *walk_subtrees, void *)
18359 *walk_subtrees = 0;
18360 switch (TREE_CODE (*tp))
18362 case OMP_TEAMS:
18363 return *tp;
18364 case BIND_EXPR:
18365 case STATEMENT_LIST:
18366 *walk_subtrees = 1;
18367 break;
18368 default:
18369 break;
18371 return NULL_TREE;
18374 /* Helper function for tsubst_expr. For decomposition declaration
18375 artificial base DECL, which is tsubsted PATTERN_DECL, tsubst
18376 also the corresponding decls representing the identifiers
18377 of the decomposition declaration. Return DECL if successful
18378 or error_mark_node otherwise, set *FIRST to the first decl
18379 in the list chained through DECL_CHAIN and *CNT to the number
18380 of such decls. */
18382 static tree
18383 tsubst_decomp_names (tree decl, tree pattern_decl, tree args,
18384 tsubst_flags_t complain, tree in_decl, cp_decomp *decomp)
18386 tree decl2, decl3, prev = decl;
18387 decomp->count = 0;
18388 gcc_assert (DECL_NAME (decl) == NULL_TREE);
18389 for (decl2 = DECL_CHAIN (pattern_decl);
18390 decl2
18391 && DECL_DECOMPOSITION_P (decl2)
18392 && DECL_NAME (decl2);
18393 decl2 = DECL_CHAIN (decl2))
18395 if (TREE_TYPE (decl2) == error_mark_node && decomp->count == 0)
18397 gcc_assert (errorcount);
18398 return error_mark_node;
18400 decomp->count++;
18401 gcc_assert (DECL_DECOMP_BASE (decl2) == pattern_decl);
18402 gcc_assert (DECL_HAS_VALUE_EXPR_P (decl2));
18403 tree v = DECL_VALUE_EXPR (decl2);
18404 DECL_HAS_VALUE_EXPR_P (decl2) = 0;
18405 SET_DECL_VALUE_EXPR (decl2, NULL_TREE);
18406 decl3 = tsubst (decl2, args, complain, in_decl);
18407 SET_DECL_VALUE_EXPR (decl2, v);
18408 DECL_HAS_VALUE_EXPR_P (decl2) = 1;
18409 if (VAR_P (decl3))
18410 DECL_TEMPLATE_INSTANTIATED (decl3) = 1;
18411 else
18413 gcc_assert (errorcount);
18414 decl = error_mark_node;
18415 continue;
18417 maybe_push_decl (decl3);
18418 if (error_operand_p (decl3))
18419 decl = error_mark_node;
18420 else if (decl != error_mark_node
18421 && DECL_CHAIN (decl3) != prev
18422 && decl != prev)
18424 gcc_assert (errorcount);
18425 decl = error_mark_node;
18427 else
18428 prev = decl3;
18430 decomp->decl = prev;
18431 return decl;
18434 /* Return the proper local_specialization for init-capture pack DECL. */
18436 static tree
18437 lookup_init_capture_pack (tree decl)
18439 /* We handle normal pack captures by forwarding to the specialization of the
18440 captured parameter. We can't do that for pack init-captures; we need them
18441 to have their own local_specialization. We created the individual
18442 VAR_DECLs (if any) under build_capture_proxy, and we need to collect them
18443 when we process the DECL_EXPR for the pack init-capture in the template.
18444 So, how do we find them? We don't know the capture proxy pack when
18445 building the individual resulting proxies, and we don't know the
18446 individual proxies when instantiating the pack. What we have in common is
18447 the FIELD_DECL.
18449 So...when we instantiate the FIELD_DECL, we stick the result in
18450 local_specializations. Then at the DECL_EXPR we look up that result, see
18451 how many elements it has, synthesize the names, and look them up. */
18453 tree cname = DECL_NAME (decl);
18454 tree val = DECL_VALUE_EXPR (decl);
18455 tree field = TREE_OPERAND (val, 1);
18456 gcc_assert (TREE_CODE (field) == FIELD_DECL);
18457 tree fpack = retrieve_local_specialization (field);
18458 if (fpack == error_mark_node)
18459 return error_mark_node;
18461 int len = 1;
18462 tree vec = NULL_TREE;
18463 tree r = NULL_TREE;
18464 if (TREE_CODE (fpack) == TREE_VEC)
18466 len = TREE_VEC_LENGTH (fpack);
18467 vec = make_tree_vec (len);
18468 r = make_node (NONTYPE_ARGUMENT_PACK);
18469 ARGUMENT_PACK_ARGS (r) = vec;
18471 for (int i = 0; i < len; ++i)
18473 tree ename = vec ? make_ith_pack_parameter_name (cname, i) : cname;
18474 tree elt = lookup_name (ename);
18475 if (vec)
18476 TREE_VEC_ELT (vec, i) = elt;
18477 else
18478 r = elt;
18480 return r;
18483 /* T is an operand of a template tree being substituted. Return whether
18484 T is dependent such that we should suppress some warnings that would
18485 make sense if the substituted expression were written directly, like
18486 template <int I> bool f() { return I == 2; }
18487 We don't want to warn when instantiating f that comparing two constants
18488 always has the same value.
18490 This is a more limited concept of dependence than instantiation-dependent;
18491 here we don't care whether substitution could fail. */
18493 static bool
18494 dependent_operand_p (tree t)
18496 while (TREE_CODE (t) == IMPLICIT_CONV_EXPR)
18497 t = TREE_OPERAND (t, 0);
18498 ++processing_template_decl;
18499 bool r = (potential_constant_expression (t)
18500 ? value_dependent_expression_p (t)
18501 : type_dependent_expression_p (t));
18502 --processing_template_decl;
18503 return r;
18506 /* A superset of tsubst_expr that also handles statement trees. */
18508 static tree
18509 tsubst_stmt (tree t, tree args, tsubst_flags_t complain, tree in_decl)
18511 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
18512 #define RECUR(NODE) \
18513 tsubst_stmt ((NODE), args, complain, in_decl)
18515 tree stmt, tmp;
18516 tree r;
18517 location_t loc;
18519 if (t == NULL_TREE || t == error_mark_node)
18520 return t;
18522 loc = input_location;
18523 if (location_t eloc = cp_expr_location (t))
18524 input_location = eloc;
18525 if (STATEMENT_CODE_P (TREE_CODE (t)))
18526 current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
18528 switch (TREE_CODE (t))
18530 case STATEMENT_LIST:
18532 for (tree stmt : tsi_range (t))
18533 RECUR (stmt);
18534 break;
18537 case CTOR_INITIALIZER:
18538 finish_mem_initializers (tsubst_initializer_list
18539 (TREE_OPERAND (t, 0), args));
18540 break;
18542 case RETURN_EXPR:
18543 finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
18544 break;
18546 case CO_RETURN_EXPR:
18547 finish_co_return_stmt (input_location, RECUR (TREE_OPERAND (t, 0)));
18548 break;
18550 case EXPR_STMT:
18551 tmp = RECUR (EXPR_STMT_EXPR (t));
18552 if (EXPR_STMT_STMT_EXPR_RESULT (t))
18553 finish_stmt_expr_expr (tmp, cur_stmt_expr);
18554 else
18555 finish_expr_stmt (tmp);
18556 break;
18558 case USING_STMT:
18559 finish_using_directive (USING_STMT_NAMESPACE (t), /*attribs=*/NULL_TREE);
18560 break;
18562 case PRECONDITION_STMT:
18563 case POSTCONDITION_STMT:
18564 gcc_unreachable ();
18566 case ASSERTION_STMT:
18568 r = tsubst_contract (NULL_TREE, t, args, complain, in_decl);
18569 if (r != error_mark_node)
18570 add_stmt (r);
18571 RETURN (r);
18573 break;
18575 case DECL_EXPR:
18577 tree decl, pattern_decl;
18578 tree init;
18580 pattern_decl = decl = DECL_EXPR_DECL (t);
18581 if (TREE_CODE (decl) == LABEL_DECL)
18582 finish_label_decl (DECL_NAME (decl));
18583 else if (TREE_CODE (decl) == USING_DECL)
18585 tree scope = USING_DECL_SCOPE (decl);
18586 if (DECL_DEPENDENT_P (decl))
18588 scope = tsubst (scope, args, complain, in_decl);
18589 if (!MAYBE_CLASS_TYPE_P (scope)
18590 && TREE_CODE (scope) != ENUMERAL_TYPE)
18592 if (complain & tf_error)
18593 error_at (DECL_SOURCE_LOCATION (decl), "%qT is not a "
18594 "class, namespace, or enumeration", scope);
18595 return error_mark_node;
18597 finish_nonmember_using_decl (scope, DECL_NAME (decl));
18599 else
18601 /* This is a non-dependent using-decl, and we'll have
18602 used the names it found during template parsing. We do
18603 not want to do the lookup again, because we might not
18604 find the things we found then. */
18605 gcc_checking_assert (scope == tsubst (scope, args,
18606 complain, in_decl));
18607 /* We still need to push the bindings so that we can look up
18608 this name later. */
18609 push_using_decl_bindings (DECL_NAME (decl),
18610 USING_DECL_DECLS (decl));
18613 else if (is_capture_proxy (decl)
18614 && !DECL_TEMPLATE_INSTANTIATION (current_function_decl))
18616 /* We're in tsubst_lambda_expr, we've already inserted a new
18617 capture proxy, so look it up and register it. */
18618 tree inst;
18619 if (!DECL_PACK_P (decl))
18621 inst = lookup_name (DECL_NAME (decl), LOOK_where::BLOCK,
18622 LOOK_want::HIDDEN_LAMBDA);
18623 gcc_assert (inst != decl && is_capture_proxy (inst));
18625 else if (is_normal_capture_proxy (decl))
18627 inst = (retrieve_local_specialization
18628 (DECL_CAPTURED_VARIABLE (decl)));
18629 gcc_assert (TREE_CODE (inst) == NONTYPE_ARGUMENT_PACK
18630 || DECL_PACK_P (inst));
18632 else
18633 inst = lookup_init_capture_pack (decl);
18635 register_local_specialization (inst, decl);
18636 break;
18638 else if (DECL_PRETTY_FUNCTION_P (decl))
18639 decl = make_fname_decl (DECL_SOURCE_LOCATION (decl),
18640 DECL_NAME (decl),
18641 true/*DECL_PRETTY_FUNCTION_P (decl)*/);
18642 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
18643 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
18644 /* Don't copy the old closure; we'll create a new one in
18645 tsubst_lambda_expr. */
18646 break;
18647 else
18649 init = DECL_INITIAL (decl);
18650 decl = tsubst (decl, args, complain, in_decl);
18651 if (decl != error_mark_node)
18653 /* By marking the declaration as instantiated, we avoid
18654 trying to instantiate it. Since instantiate_decl can't
18655 handle local variables, and since we've already done
18656 all that needs to be done, that's the right thing to
18657 do. */
18658 if (VAR_P (decl))
18659 DECL_TEMPLATE_INSTANTIATED (decl) = 1;
18660 if (VAR_P (decl) && !DECL_NAME (decl)
18661 && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
18662 /* Anonymous aggregates are a special case. */
18663 finish_anon_union (decl);
18664 else if (is_capture_proxy (DECL_EXPR_DECL (t)))
18666 DECL_CONTEXT (decl) = current_function_decl;
18667 if (DECL_NAME (decl) == this_identifier)
18669 tree lam = DECL_CONTEXT (current_function_decl);
18670 lam = CLASSTYPE_LAMBDA_EXPR (lam);
18671 LAMBDA_EXPR_THIS_CAPTURE (lam) = decl;
18673 insert_capture_proxy (decl);
18675 else if (DECL_IMPLICIT_TYPEDEF_P (t))
18676 /* We already did a pushtag. */;
18677 else if (VAR_OR_FUNCTION_DECL_P (decl)
18678 && DECL_LOCAL_DECL_P (decl))
18680 if (TREE_CODE (DECL_CONTEXT (decl)) == FUNCTION_DECL)
18681 DECL_CONTEXT (decl) = NULL_TREE;
18682 decl = pushdecl (decl);
18683 if (TREE_CODE (decl) == FUNCTION_DECL
18684 && DECL_OMP_DECLARE_REDUCTION_P (decl)
18685 && cp_check_omp_declare_reduction (decl))
18686 instantiate_body (pattern_decl, args, decl, true);
18688 else
18690 bool const_init = false;
18691 cp_decomp decomp_d, *decomp = NULL;
18692 tree asmspec_tree = NULL_TREE;
18693 maybe_push_decl (decl);
18695 if (VAR_P (decl)
18696 && DECL_LANG_SPECIFIC (decl)
18697 && DECL_OMP_PRIVATIZED_MEMBER (decl))
18698 break;
18700 if (DECL_DECOMPOSITION_P (decl)
18701 && TREE_TYPE (pattern_decl) != error_mark_node)
18703 decomp = &decomp_d;
18704 if (tsubst_decomp_names (decl, pattern_decl, args,
18705 complain, in_decl, decomp)
18706 == error_mark_node)
18707 decomp = NULL;
18710 init = tsubst_init (init, decl, args, complain, in_decl);
18712 if (VAR_P (decl))
18713 const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
18714 (pattern_decl));
18716 /* In a non-template function, VLA type declarations are
18717 handled in grokdeclarator; for templates, handle them
18718 now. */
18719 predeclare_vla (decl);
18721 if (VAR_P (decl) && DECL_HARD_REGISTER (pattern_decl))
18723 tree id = DECL_ASSEMBLER_NAME (pattern_decl);
18724 const char *asmspec = IDENTIFIER_POINTER (id);
18725 gcc_assert (asmspec[0] == '*');
18726 asmspec_tree
18727 = build_string (IDENTIFIER_LENGTH (id) - 1,
18728 asmspec + 1);
18729 TREE_TYPE (asmspec_tree) = char_array_type_node;
18732 cp_finish_decl (decl, init, const_init, asmspec_tree, 0,
18733 decomp);
18738 break;
18741 case FOR_STMT:
18742 stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
18743 RECUR (FOR_INIT_STMT (t));
18744 finish_init_stmt (stmt);
18745 tmp = RECUR (FOR_COND (t));
18746 finish_for_cond (tmp, stmt, false, 0, false);
18747 tmp = RECUR (FOR_EXPR (t));
18748 finish_for_expr (tmp, stmt);
18750 bool prev = note_iteration_stmt_body_start ();
18751 RECUR (FOR_BODY (t));
18752 note_iteration_stmt_body_end (prev);
18754 finish_for_stmt (stmt);
18755 break;
18757 case RANGE_FOR_STMT:
18759 /* Construct another range_for, if this is not a final
18760 substitution (for inside a generic lambda of a
18761 template). Otherwise convert to a regular for. */
18762 tree decl, expr;
18763 stmt = (processing_template_decl
18764 ? begin_range_for_stmt (NULL_TREE, NULL_TREE)
18765 : begin_for_stmt (NULL_TREE, NULL_TREE));
18766 RECUR (RANGE_FOR_INIT_STMT (t));
18767 decl = RANGE_FOR_DECL (t);
18768 decl = tsubst (decl, args, complain, in_decl);
18769 maybe_push_decl (decl);
18770 expr = RECUR (RANGE_FOR_EXPR (t));
18772 cp_decomp decomp_d, *decomp = NULL;
18773 if (DECL_DECOMPOSITION_P (decl))
18775 decomp = &decomp_d;
18776 decl = tsubst_decomp_names (decl, RANGE_FOR_DECL (t), args,
18777 complain, in_decl, decomp);
18780 tree unroll = RECUR (RANGE_FOR_UNROLL (t));
18781 if (unroll)
18782 unroll
18783 = cp_check_pragma_unroll (EXPR_LOCATION (RANGE_FOR_UNROLL (t)),
18784 unroll);
18785 if (processing_template_decl)
18787 RANGE_FOR_IVDEP (stmt) = RANGE_FOR_IVDEP (t);
18788 RANGE_FOR_UNROLL (stmt) = unroll;
18789 RANGE_FOR_NOVECTOR (stmt) = RANGE_FOR_NOVECTOR (t);
18790 finish_range_for_decl (stmt, decl, expr);
18791 if (decomp && decl != error_mark_node)
18792 cp_finish_decomp (decl, decomp);
18794 else
18795 stmt = cp_convert_range_for (stmt, decl, expr, decomp,
18796 RANGE_FOR_IVDEP (t), unroll,
18797 RANGE_FOR_NOVECTOR (t));
18799 bool prev = note_iteration_stmt_body_start ();
18800 RECUR (RANGE_FOR_BODY (t));
18801 note_iteration_stmt_body_end (prev);
18802 finish_for_stmt (stmt);
18804 break;
18806 case WHILE_STMT:
18807 stmt = begin_while_stmt ();
18808 tmp = RECUR (WHILE_COND (t));
18809 finish_while_stmt_cond (tmp, stmt, false, 0, false);
18811 bool prev = note_iteration_stmt_body_start ();
18812 RECUR (WHILE_BODY (t));
18813 note_iteration_stmt_body_end (prev);
18815 finish_while_stmt (stmt);
18816 break;
18818 case DO_STMT:
18819 stmt = begin_do_stmt ();
18821 bool prev = note_iteration_stmt_body_start ();
18822 RECUR (DO_BODY (t));
18823 note_iteration_stmt_body_end (prev);
18825 finish_do_body (stmt);
18826 tmp = RECUR (DO_COND (t));
18827 finish_do_stmt (tmp, stmt, false, 0, false);
18828 break;
18830 case IF_STMT:
18831 stmt = begin_if_stmt ();
18832 IF_STMT_CONSTEXPR_P (stmt) = IF_STMT_CONSTEXPR_P (t);
18833 IF_STMT_CONSTEVAL_P (stmt) = IF_STMT_CONSTEVAL_P (t);
18834 if (IF_STMT_CONSTEXPR_P (t))
18835 args = add_extra_args (IF_STMT_EXTRA_ARGS (t), args, complain, in_decl);
18837 tree cond = IF_COND (t);
18838 bool was_dep = dependent_operand_p (cond);
18839 cond = RECUR (cond);
18840 warning_sentinel s1(warn_address, was_dep);
18841 tmp = finish_if_stmt_cond (cond, stmt);
18843 if (IF_STMT_CONSTEXPR_P (t)
18844 && instantiation_dependent_expression_p (tmp))
18846 /* We're partially instantiating a generic lambda, but the condition
18847 of the constexpr if is still dependent. Don't substitute into the
18848 branches now, just remember the template arguments. */
18849 do_poplevel (IF_SCOPE (stmt));
18850 IF_SCOPE (stmt) = NULL_TREE;
18851 IF_COND (stmt) = IF_COND (t);
18852 THEN_CLAUSE (stmt) = THEN_CLAUSE (t);
18853 ELSE_CLAUSE (stmt) = ELSE_CLAUSE (t);
18854 IF_STMT_EXTRA_ARGS (stmt) = build_extra_args (stmt, args, complain);
18855 add_stmt (stmt);
18856 break;
18858 if (IF_STMT_CONSTEXPR_P (t) && integer_zerop (tmp))
18859 /* Don't instantiate the THEN_CLAUSE. */;
18860 else if (IF_STMT_CONSTEVAL_P (t))
18862 bool save_in_consteval_if_p = in_consteval_if_p;
18863 in_consteval_if_p = true;
18864 RECUR (THEN_CLAUSE (t));
18865 in_consteval_if_p = save_in_consteval_if_p;
18867 else
18869 tree folded = fold_non_dependent_expr (tmp, complain);
18870 bool inhibit = integer_zerop (folded);
18871 if (inhibit)
18872 ++c_inhibit_evaluation_warnings;
18873 RECUR (THEN_CLAUSE (t));
18874 if (inhibit)
18875 --c_inhibit_evaluation_warnings;
18877 finish_then_clause (stmt);
18879 if (IF_STMT_CONSTEXPR_P (t) && integer_nonzerop (tmp))
18880 /* Don't instantiate the ELSE_CLAUSE. */;
18881 else if (ELSE_CLAUSE (t))
18883 tree folded = fold_non_dependent_expr (tmp, complain);
18884 bool inhibit = integer_nonzerop (folded);
18885 begin_else_clause (stmt);
18886 if (inhibit)
18887 ++c_inhibit_evaluation_warnings;
18888 RECUR (ELSE_CLAUSE (t));
18889 if (inhibit)
18890 --c_inhibit_evaluation_warnings;
18891 finish_else_clause (stmt);
18894 finish_if_stmt (stmt);
18895 break;
18897 case BIND_EXPR:
18898 if (BIND_EXPR_BODY_BLOCK (t))
18899 stmt = begin_function_body ();
18900 else
18901 stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
18902 ? BCS_TRY_BLOCK : 0);
18904 RECUR (BIND_EXPR_BODY (t));
18906 if (BIND_EXPR_BODY_BLOCK (t))
18907 finish_function_body (stmt);
18908 else
18909 finish_compound_stmt (stmt);
18910 break;
18912 case BREAK_STMT:
18913 finish_break_stmt ();
18914 break;
18916 case CONTINUE_STMT:
18917 finish_continue_stmt ();
18918 break;
18920 case SWITCH_STMT:
18921 stmt = begin_switch_stmt ();
18922 tmp = RECUR (SWITCH_STMT_COND (t));
18923 finish_switch_cond (tmp, stmt);
18924 RECUR (SWITCH_STMT_BODY (t));
18925 finish_switch_stmt (stmt);
18926 break;
18928 case CASE_LABEL_EXPR:
18930 tree decl = CASE_LABEL (t);
18931 tree low = RECUR (CASE_LOW (t));
18932 tree high = RECUR (CASE_HIGH (t));
18933 tree l = finish_case_label (EXPR_LOCATION (t), low, high);
18934 if (l && TREE_CODE (l) == CASE_LABEL_EXPR)
18936 tree label = CASE_LABEL (l);
18937 FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
18938 if (DECL_ATTRIBUTES (decl) != NULL_TREE)
18939 cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
18942 break;
18944 case LABEL_EXPR:
18946 tree decl = LABEL_EXPR_LABEL (t);
18947 tree label = finish_label_stmt (DECL_NAME (decl));
18948 if (TREE_CODE (label) == LABEL_DECL)
18950 FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
18951 copy_warning (label, decl);
18953 if (DECL_ATTRIBUTES (decl) != NULL_TREE)
18954 cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
18956 break;
18958 case GOTO_EXPR:
18959 tmp = GOTO_DESTINATION (t);
18960 if (TREE_CODE (tmp) != LABEL_DECL)
18961 /* Computed goto's must be tsubst'd into. On the other hand,
18962 non-computed gotos must not be; the identifier in question
18963 will have no binding. */
18964 tmp = RECUR (tmp);
18965 else
18966 tmp = DECL_NAME (tmp);
18967 finish_goto_stmt (tmp);
18968 break;
18970 case ASM_EXPR:
18972 tree string = RECUR (ASM_STRING (t));
18973 tree outputs = tsubst_copy_asm_operands (ASM_OUTPUTS (t), args,
18974 complain, in_decl);
18975 tree inputs = tsubst_copy_asm_operands (ASM_INPUTS (t), args,
18976 complain, in_decl);
18977 tree clobbers = tsubst_copy_asm_operands (ASM_CLOBBERS (t), args,
18978 complain, in_decl);
18979 tree labels = tsubst_copy_asm_operands (ASM_LABELS (t), args,
18980 complain, in_decl);
18981 tmp = finish_asm_stmt (EXPR_LOCATION (t), ASM_VOLATILE_P (t), string,
18982 outputs, inputs, clobbers, labels,
18983 ASM_INLINE_P (t));
18984 tree asm_expr = tmp;
18985 if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
18986 asm_expr = TREE_OPERAND (asm_expr, 0);
18987 ASM_BASIC_P (asm_expr) = ASM_BASIC_P (t);
18989 break;
18991 case TRY_BLOCK:
18992 if (CLEANUP_P (t))
18994 stmt = begin_try_block ();
18995 RECUR (TRY_STMTS (t));
18996 finish_cleanup_try_block (stmt);
18997 finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
18999 else
19001 tree compound_stmt = NULL_TREE;
19003 if (FN_TRY_BLOCK_P (t))
19004 stmt = begin_function_try_block (&compound_stmt);
19005 else
19006 stmt = begin_try_block ();
19008 RECUR (TRY_STMTS (t));
19010 if (FN_TRY_BLOCK_P (t))
19011 finish_function_try_block (stmt);
19012 else
19013 finish_try_block (stmt);
19015 RECUR (TRY_HANDLERS (t));
19016 if (FN_TRY_BLOCK_P (t))
19017 finish_function_handler_sequence (stmt, compound_stmt);
19018 else
19019 finish_handler_sequence (stmt);
19021 break;
19023 case HANDLER:
19025 tree decl = HANDLER_PARMS (t);
19027 if (decl)
19029 decl = tsubst (decl, args, complain, in_decl);
19030 /* Prevent instantiate_decl from trying to instantiate
19031 this variable. We've already done all that needs to be
19032 done. */
19033 if (decl != error_mark_node)
19034 DECL_TEMPLATE_INSTANTIATED (decl) = 1;
19036 stmt = begin_handler ();
19037 finish_handler_parms (decl, stmt);
19038 RECUR (HANDLER_BODY (t));
19039 finish_handler (stmt);
19041 break;
19043 case TAG_DEFN:
19044 tmp = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
19045 if (dependent_type_p (tmp))
19046 /* This is a partial instantiation, try again when full. */
19047 add_stmt (build_min (TAG_DEFN, tmp));
19048 else if (CLASS_TYPE_P (tmp))
19050 /* Local classes are not independent templates; they are
19051 instantiated along with their containing function. And this
19052 way we don't have to deal with pushing out of one local class
19053 to instantiate a member of another local class. */
19054 /* Closures are handled by the LAMBDA_EXPR. */
19055 gcc_assert (!LAMBDA_TYPE_P (TREE_TYPE (t)));
19056 complete_type (tmp);
19057 tree save_ccp = current_class_ptr;
19058 tree save_ccr = current_class_ref;
19059 for (tree fld = TYPE_FIELDS (tmp); fld; fld = DECL_CHAIN (fld))
19060 if ((VAR_P (fld)
19061 || (TREE_CODE (fld) == FUNCTION_DECL
19062 && !DECL_ARTIFICIAL (fld)))
19063 && DECL_TEMPLATE_INSTANTIATION (fld))
19064 instantiate_decl (fld, /*defer_ok=*/false,
19065 /*expl_inst_class=*/false);
19066 else if (TREE_CODE (fld) == FIELD_DECL)
19067 maybe_instantiate_nsdmi_init (fld, tf_warning_or_error);
19068 current_class_ptr = save_ccp;
19069 current_class_ref = save_ccr;
19071 break;
19073 case STATIC_ASSERT:
19075 tree condition, message;
19077 ++c_inhibit_evaluation_warnings;
19078 condition = tsubst_expr (STATIC_ASSERT_CONDITION (t), args,
19079 complain, in_decl);
19080 message = tsubst_expr (STATIC_ASSERT_MESSAGE (t), args,
19081 complain, in_decl);
19082 if (TREE_CODE (STATIC_ASSERT_MESSAGE (t)) != STRING_CST
19083 && TREE_CODE (message) == STRING_CST)
19084 message = build1_loc (STATIC_ASSERT_SOURCE_LOCATION (t),
19085 PAREN_EXPR, TREE_TYPE (message), message);
19086 --c_inhibit_evaluation_warnings;
19088 finish_static_assert (condition, message,
19089 STATIC_ASSERT_SOURCE_LOCATION (t),
19090 /*member_p=*/false, /*show_expr_p=*/true);
19092 break;
19094 case OACC_KERNELS:
19095 case OACC_PARALLEL:
19096 case OACC_SERIAL:
19097 tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_ACC_TARGET, args,
19098 complain, in_decl);
19099 stmt = begin_omp_parallel ();
19100 RECUR (OMP_BODY (t));
19101 finish_omp_construct (TREE_CODE (t), stmt, tmp);
19102 break;
19104 case OMP_PARALLEL:
19105 r = push_omp_privatization_clauses (OMP_PARALLEL_COMBINED (t));
19106 tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t), C_ORT_OMP, args,
19107 complain, in_decl);
19108 if (OMP_PARALLEL_COMBINED (t))
19109 omp_parallel_combined_clauses = &tmp;
19110 stmt = begin_omp_parallel ();
19111 RECUR (OMP_PARALLEL_BODY (t));
19112 gcc_assert (omp_parallel_combined_clauses == NULL);
19113 OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
19114 = OMP_PARALLEL_COMBINED (t);
19115 pop_omp_privatization_clauses (r);
19116 break;
19118 case OMP_TASK:
19119 if (OMP_TASK_BODY (t) == NULL_TREE)
19121 tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
19122 complain, in_decl);
19123 t = copy_node (t);
19124 OMP_TASK_CLAUSES (t) = tmp;
19125 add_stmt (t);
19126 break;
19128 r = push_omp_privatization_clauses (false);
19129 tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
19130 complain, in_decl);
19131 stmt = begin_omp_task ();
19132 RECUR (OMP_TASK_BODY (t));
19133 finish_omp_task (tmp, stmt);
19134 pop_omp_privatization_clauses (r);
19135 break;
19137 case OMP_FOR:
19138 case OMP_LOOP:
19139 case OMP_SIMD:
19140 case OMP_DISTRIBUTE:
19141 case OMP_TASKLOOP:
19142 case OMP_TILE:
19143 case OMP_UNROLL:
19144 case OACC_LOOP:
19146 tree clauses, body, pre_body;
19147 tree declv = NULL_TREE, initv = NULL_TREE, condv = NULL_TREE;
19148 tree orig_declv = NULL_TREE;
19149 tree incrv = NULL_TREE;
19150 enum c_omp_region_type ort = C_ORT_OMP;
19151 bool any_range_for = false;
19152 int i;
19154 if (TREE_CODE (t) == OACC_LOOP)
19155 ort = C_ORT_ACC;
19157 r = push_omp_privatization_clauses (OMP_FOR_INIT (t) == NULL_TREE);
19158 clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t), ort, args, complain,
19159 in_decl);
19160 if (OMP_FOR_INIT (t) != NULL_TREE)
19162 declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19163 if (OMP_FOR_ORIG_DECLS (t))
19164 orig_declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19165 initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19166 condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19167 incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19170 keep_next_level (true);
19171 stmt = begin_omp_structured_block ();
19173 pre_body = push_stmt_list ();
19174 RECUR (OMP_FOR_PRE_BODY (t));
19175 pre_body = pop_stmt_list (pre_body);
19177 tree sl = NULL_TREE;
19178 if (flag_range_for_ext_temps
19179 && OMP_FOR_INIT (t) != NULL_TREE
19180 && !processing_template_decl)
19181 for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
19182 if (TREE_VEC_ELT (OMP_FOR_INIT (t), i)
19183 && TREE_VEC_ELT (OMP_FOR_COND (t), i) == global_namespace)
19185 sl = push_stmt_list ();
19186 break;
19189 if (OMP_FOR_INIT (t) != NULL_TREE)
19190 for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
19192 if (TREE_VEC_ELT (OMP_FOR_INIT (t), i))
19193 any_range_for
19194 |= tsubst_omp_for_iterator (t, i, declv, orig_declv, initv,
19195 condv, incrv, &clauses, args,
19196 complain, in_decl);
19197 else
19199 TREE_VEC_ELT (declv, i) = global_namespace;
19200 TREE_VEC_ELT (initv, i) = NULL_TREE;
19201 TREE_VEC_ELT (condv, i) = NULL_TREE;
19202 TREE_VEC_ELT (incrv, i) = NULL_TREE;
19203 if (orig_declv)
19204 TREE_VEC_ELT (orig_declv, i) = NULL_TREE;
19207 omp_parallel_combined_clauses = NULL;
19209 if (any_range_for)
19211 gcc_assert (orig_declv);
19212 body = begin_omp_structured_block ();
19213 for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
19214 if (TREE_VEC_ELT (declv, i) != global_namespace
19215 && TREE_VEC_ELT (orig_declv, i) != TREE_VEC_ELT (declv, i)
19216 && TREE_CODE (TREE_VEC_ELT (orig_declv, i)) == TREE_LIST
19217 && TREE_CHAIN (TREE_VEC_ELT (orig_declv, i)))
19218 cp_finish_omp_range_for (TREE_VEC_ELT (orig_declv, i),
19219 TREE_VEC_ELT (declv, i));
19221 else
19222 body = push_stmt_list ();
19223 RECUR (OMP_FOR_BODY (t));
19224 if (any_range_for)
19225 body = finish_omp_structured_block (body);
19226 else
19227 body = pop_stmt_list (body);
19229 if (OMP_FOR_INIT (t) != NULL_TREE)
19230 t = finish_omp_for (EXPR_LOCATION (t), TREE_CODE (t), declv,
19231 orig_declv, initv, condv, incrv, body, pre_body,
19232 NULL, clauses);
19233 else
19235 t = make_node (TREE_CODE (t));
19236 TREE_TYPE (t) = void_type_node;
19237 OMP_FOR_BODY (t) = body;
19238 OMP_FOR_PRE_BODY (t) = pre_body;
19239 OMP_FOR_CLAUSES (t) = clauses;
19240 SET_EXPR_LOCATION (t, EXPR_LOCATION (t));
19241 add_stmt (t);
19244 if (sl)
19246 /* P2718R0 - Add CLEANUP_POINT_EXPR so that temporaries in
19247 for-range-initializer whose lifetime is extended are destructed
19248 here. */
19249 sl = pop_stmt_list (sl);
19250 sl = maybe_cleanup_point_expr_void (sl);
19251 add_stmt (sl);
19254 add_stmt (finish_omp_for_block (finish_omp_structured_block (stmt),
19255 t));
19256 pop_omp_privatization_clauses (r);
19258 if (any_range_for && !processing_template_decl && t)
19259 for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
19260 if (TREE_VEC_ELT (OMP_FOR_ORIG_DECLS (t), i)
19261 && TREE_CODE (TREE_VEC_ELT (OMP_FOR_ORIG_DECLS (t),
19262 i)) == TREE_LIST)
19264 tree v = TREE_VEC_ELT (OMP_FOR_ORIG_DECLS (t), i);
19265 if (TREE_CHAIN (v) == NULL_TREE
19266 || TREE_CODE (TREE_CHAIN (v)) != TREE_VEC)
19267 continue;
19268 v = TREE_VEC_ELT (TREE_CHAIN (v), 0);
19269 gcc_assert (VAR_P (v) && DECL_NAME (v) == NULL_TREE);
19270 DECL_NAME (v) = for_range_identifier;
19273 break;
19275 case OMP_SECTIONS:
19276 case OMP_MASKED:
19277 omp_parallel_combined_clauses = NULL;
19278 /* FALLTHRU */
19279 case OMP_SINGLE:
19280 case OMP_SCOPE:
19281 case OMP_TEAMS:
19282 case OMP_CRITICAL:
19283 case OMP_TASKGROUP:
19284 case OMP_SCAN:
19285 r = push_omp_privatization_clauses (TREE_CODE (t) == OMP_TEAMS
19286 && OMP_TEAMS_COMBINED (t));
19287 tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_OMP, args, complain,
19288 in_decl);
19289 if (TREE_CODE (t) == OMP_TEAMS)
19291 keep_next_level (true);
19292 stmt = begin_omp_structured_block ();
19293 RECUR (OMP_BODY (t));
19294 stmt = finish_omp_structured_block (stmt);
19296 else
19298 stmt = push_stmt_list ();
19299 RECUR (OMP_BODY (t));
19300 stmt = pop_stmt_list (stmt);
19303 if (TREE_CODE (t) == OMP_CRITICAL
19304 && tmp != NULL_TREE
19305 && integer_nonzerop (OMP_CLAUSE_HINT_EXPR (tmp)))
19307 error_at (OMP_CLAUSE_LOCATION (tmp),
19308 "%<#pragma omp critical%> with %<hint%> clause requires "
19309 "a name, except when %<omp_sync_hint_none%> is used");
19310 RETURN (error_mark_node);
19312 t = copy_node (t);
19313 OMP_BODY (t) = stmt;
19314 OMP_CLAUSES (t) = tmp;
19315 add_stmt (t);
19316 pop_omp_privatization_clauses (r);
19317 break;
19319 case OMP_DEPOBJ:
19320 r = RECUR (OMP_DEPOBJ_DEPOBJ (t));
19321 if (OMP_DEPOBJ_CLAUSES (t) && OMP_DEPOBJ_CLAUSES (t) != error_mark_node)
19323 enum omp_clause_depend_kind kind = OMP_CLAUSE_DEPEND_INVALID;
19324 if (TREE_CODE (OMP_DEPOBJ_CLAUSES (t)) == OMP_CLAUSE)
19326 tmp = tsubst_omp_clauses (OMP_DEPOBJ_CLAUSES (t), C_ORT_OMP,
19327 args, complain, in_decl);
19328 if (tmp == NULL_TREE)
19329 tmp = error_mark_node;
19331 else
19333 kind = (enum omp_clause_depend_kind)
19334 tree_to_uhwi (OMP_DEPOBJ_CLAUSES (t));
19335 tmp = NULL_TREE;
19337 finish_omp_depobj (EXPR_LOCATION (t), r, kind, tmp);
19339 else
19340 finish_omp_depobj (EXPR_LOCATION (t), r,
19341 OMP_CLAUSE_DEPEND_INVALID,
19342 OMP_DEPOBJ_CLAUSES (t));
19343 break;
19345 case OACC_DATA:
19346 case OMP_TARGET_DATA:
19347 case OMP_TARGET:
19348 tmp = tsubst_omp_clauses (OMP_CLAUSES (t),
19349 TREE_CODE (t) == OACC_DATA
19350 ? C_ORT_ACC
19351 : TREE_CODE (t) == OMP_TARGET
19352 ? C_ORT_OMP_TARGET : C_ORT_OMP,
19353 args, complain, in_decl);
19354 keep_next_level (true);
19355 stmt = begin_omp_structured_block ();
19357 RECUR (OMP_BODY (t));
19358 stmt = finish_omp_structured_block (stmt);
19360 t = copy_node (t);
19361 OMP_BODY (t) = stmt;
19362 OMP_CLAUSES (t) = tmp;
19364 if (TREE_CODE (t) == OMP_TARGET)
19365 finish_omp_target_clauses (EXPR_LOCATION (t), OMP_BODY (t),
19366 &OMP_CLAUSES (t));
19368 if (TREE_CODE (t) == OMP_TARGET && OMP_TARGET_COMBINED (t))
19370 tree teams = cp_walk_tree (&stmt, tsubst_find_omp_teams, NULL, NULL);
19371 if (teams)
19372 /* For combined target teams, ensure the num_teams and
19373 thread_limit clause expressions are evaluated on the host,
19374 before entering the target construct. */
19375 for (tree c = OMP_TEAMS_CLAUSES (teams);
19376 c; c = OMP_CLAUSE_CHAIN (c))
19377 if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS
19378 || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_THREAD_LIMIT)
19379 for (int i = 0;
19380 i <= (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS); ++i)
19381 if (OMP_CLAUSE_OPERAND (c, i)
19382 && TREE_CODE (OMP_CLAUSE_OPERAND (c, i)) != INTEGER_CST)
19384 tree expr = OMP_CLAUSE_OPERAND (c, i);
19385 expr = force_target_expr (TREE_TYPE (expr), expr,
19386 tf_none);
19387 if (expr == error_mark_node)
19388 continue;
19389 tmp = TARGET_EXPR_SLOT (expr);
19390 add_stmt (expr);
19391 OMP_CLAUSE_OPERAND (c, i) = expr;
19392 tree tc = build_omp_clause (OMP_CLAUSE_LOCATION (c),
19393 OMP_CLAUSE_FIRSTPRIVATE);
19394 OMP_CLAUSE_DECL (tc) = tmp;
19395 OMP_CLAUSE_CHAIN (tc) = OMP_TARGET_CLAUSES (t);
19396 OMP_TARGET_CLAUSES (t) = tc;
19399 add_stmt (t);
19400 break;
19402 case OACC_DECLARE:
19403 t = copy_node (t);
19404 tmp = tsubst_omp_clauses (OACC_DECLARE_CLAUSES (t), C_ORT_ACC, args,
19405 complain, in_decl);
19406 OACC_DECLARE_CLAUSES (t) = tmp;
19407 add_stmt (t);
19408 break;
19410 case OMP_TARGET_UPDATE:
19411 case OMP_TARGET_ENTER_DATA:
19412 case OMP_TARGET_EXIT_DATA:
19413 tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_OMP, args,
19414 complain, in_decl);
19415 t = copy_node (t);
19416 OMP_STANDALONE_CLAUSES (t) = tmp;
19417 add_stmt (t);
19418 break;
19420 case OACC_CACHE:
19421 case OACC_ENTER_DATA:
19422 case OACC_EXIT_DATA:
19423 case OACC_UPDATE:
19424 tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_ACC, args,
19425 complain, in_decl);
19426 t = copy_node (t);
19427 OMP_STANDALONE_CLAUSES (t) = tmp;
19428 add_stmt (t);
19429 break;
19431 case OMP_ORDERED:
19432 tmp = tsubst_omp_clauses (OMP_ORDERED_CLAUSES (t), C_ORT_OMP, args,
19433 complain, in_decl);
19434 if (OMP_BODY (t))
19436 stmt = push_stmt_list ();
19437 RECUR (OMP_BODY (t));
19438 stmt = pop_stmt_list (stmt);
19440 else
19441 stmt = NULL_TREE;
19443 t = copy_node (t);
19444 OMP_BODY (t) = stmt;
19445 OMP_ORDERED_CLAUSES (t) = tmp;
19446 add_stmt (t);
19447 break;
19449 case OMP_MASTER:
19450 case OMP_STRUCTURED_BLOCK:
19451 omp_parallel_combined_clauses = NULL;
19452 /* FALLTHRU */
19453 case OMP_SECTION:
19454 stmt = push_stmt_list ();
19455 RECUR (OMP_BODY (t));
19456 stmt = pop_stmt_list (stmt);
19458 t = copy_node (t);
19459 OMP_BODY (t) = stmt;
19460 add_stmt (t);
19461 break;
19463 case OMP_ATOMIC:
19464 gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
19465 tmp = NULL_TREE;
19466 if (TREE_CODE (TREE_OPERAND (t, 0)) == OMP_CLAUSE)
19467 tmp = tsubst_omp_clauses (TREE_OPERAND (t, 0), C_ORT_OMP, args,
19468 complain, in_decl);
19469 if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
19471 tree op1 = TREE_OPERAND (t, 1);
19472 tree rhs1 = NULL_TREE;
19473 tree r = NULL_TREE;
19474 tree lhs, rhs;
19475 if (TREE_CODE (op1) == COMPOUND_EXPR)
19477 rhs1 = RECUR (TREE_OPERAND (op1, 0));
19478 op1 = TREE_OPERAND (op1, 1);
19480 if (TREE_CODE (op1) == COND_EXPR)
19482 gcc_assert (rhs1 == NULL_TREE);
19483 tree c = TREE_OPERAND (op1, 0);
19484 if (TREE_CODE (c) == MODIFY_EXPR)
19486 r = RECUR (TREE_OPERAND (c, 0));
19487 c = TREE_OPERAND (c, 1);
19489 gcc_assert (TREE_CODE (c) == EQ_EXPR);
19490 rhs = RECUR (TREE_OPERAND (c, 1));
19491 lhs = RECUR (TREE_OPERAND (op1, 2));
19492 rhs1 = RECUR (TREE_OPERAND (op1, 1));
19494 else
19496 lhs = RECUR (TREE_OPERAND (op1, 0));
19497 rhs = RECUR (TREE_OPERAND (op1, 1));
19499 finish_omp_atomic (EXPR_LOCATION (t), OMP_ATOMIC, TREE_CODE (op1),
19500 lhs, rhs, NULL_TREE, NULL_TREE, rhs1, r,
19501 tmp, OMP_ATOMIC_MEMORY_ORDER (t),
19502 OMP_ATOMIC_WEAK (t));
19504 else
19506 tree op1 = TREE_OPERAND (t, 1);
19507 tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
19508 tree rhs1 = NULL_TREE, r = NULL_TREE;
19509 enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
19510 enum tree_code opcode = NOP_EXPR;
19511 if (code == OMP_ATOMIC_READ)
19513 v = RECUR (TREE_OPERAND (op1, 0));
19514 lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
19516 else if (code == OMP_ATOMIC_CAPTURE_OLD
19517 || code == OMP_ATOMIC_CAPTURE_NEW)
19519 tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
19520 v = RECUR (TREE_OPERAND (op1, 0));
19521 lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
19522 if (TREE_CODE (op11) == COMPOUND_EXPR)
19524 rhs1 = RECUR (TREE_OPERAND (op11, 0));
19525 op11 = TREE_OPERAND (op11, 1);
19527 if (TREE_CODE (op11) == COND_EXPR)
19529 gcc_assert (rhs1 == NULL_TREE);
19530 tree c = TREE_OPERAND (op11, 0);
19531 if (TREE_CODE (c) == MODIFY_EXPR)
19533 r = RECUR (TREE_OPERAND (c, 0));
19534 c = TREE_OPERAND (c, 1);
19536 gcc_assert (TREE_CODE (c) == EQ_EXPR);
19537 rhs = RECUR (TREE_OPERAND (c, 1));
19538 lhs = RECUR (TREE_OPERAND (op11, 2));
19539 rhs1 = RECUR (TREE_OPERAND (op11, 1));
19541 else
19543 lhs = RECUR (TREE_OPERAND (op11, 0));
19544 rhs = RECUR (TREE_OPERAND (op11, 1));
19546 opcode = TREE_CODE (op11);
19547 if (opcode == MODIFY_EXPR)
19548 opcode = NOP_EXPR;
19550 else
19552 code = OMP_ATOMIC;
19553 lhs = RECUR (TREE_OPERAND (op1, 0));
19554 rhs = RECUR (TREE_OPERAND (op1, 1));
19556 finish_omp_atomic (EXPR_LOCATION (t), code, opcode, lhs, rhs, v,
19557 lhs1, rhs1, r, tmp,
19558 OMP_ATOMIC_MEMORY_ORDER (t), OMP_ATOMIC_WEAK (t));
19560 break;
19562 case TRANSACTION_EXPR:
19564 int flags = 0;
19565 flags |= (TRANSACTION_EXPR_OUTER (t) ? TM_STMT_ATTR_OUTER : 0);
19566 flags |= (TRANSACTION_EXPR_RELAXED (t) ? TM_STMT_ATTR_RELAXED : 0);
19568 if (TRANSACTION_EXPR_IS_STMT (t))
19570 tree body = TRANSACTION_EXPR_BODY (t);
19571 tree noex = NULL_TREE;
19572 if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
19574 noex = MUST_NOT_THROW_COND (body);
19575 if (noex == NULL_TREE)
19576 noex = boolean_true_node;
19577 body = TREE_OPERAND (body, 0);
19579 stmt = begin_transaction_stmt (input_location, NULL, flags);
19580 RECUR (body);
19581 finish_transaction_stmt (stmt, NULL, flags, RECUR (noex));
19583 else
19585 stmt = build_transaction_expr (EXPR_LOCATION (t),
19586 RECUR (TRANSACTION_EXPR_BODY (t)),
19587 flags, NULL_TREE);
19588 RETURN (stmt);
19591 break;
19593 case MUST_NOT_THROW_EXPR:
19595 tree op0 = RECUR (TREE_OPERAND (t, 0));
19596 tree cond = RECUR (MUST_NOT_THROW_COND (t));
19597 RETURN (build_must_not_throw_expr (op0, cond));
19600 case EXPR_PACK_EXPANSION:
19601 error ("invalid use of pack expansion expression");
19602 RETURN (error_mark_node);
19604 case NONTYPE_ARGUMENT_PACK:
19605 error ("use %<...%> to expand argument pack");
19606 RETURN (error_mark_node);
19608 case COMPOUND_EXPR:
19609 tmp = RECUR (TREE_OPERAND (t, 0));
19610 if (tmp == NULL_TREE)
19611 /* If the first operand was a statement, we're done with it. */
19612 RETURN (RECUR (TREE_OPERAND (t, 1)));
19613 RETURN (build_x_compound_expr (EXPR_LOCATION (t), tmp,
19614 RECUR (TREE_OPERAND (t, 1)),
19615 templated_operator_saved_lookups (t),
19616 complain));
19618 case PREDICT_EXPR:
19619 RETURN (add_stmt (copy_node (t)));
19621 case ANNOTATE_EXPR:
19623 /* Although ANNOTATE_EXPR is an expression, it can only appear in
19624 WHILE_COND, DO_COND or FOR_COND expressions, which are tsubsted
19625 using tsubst_stmt rather than tsubst_expr and can contain
19626 DECL_EXPRs. */
19627 tree op1 = RECUR (TREE_OPERAND (t, 0));
19628 tree op2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl);
19629 tree op3 = tsubst_expr (TREE_OPERAND (t, 2), args, complain, in_decl);
19630 if (TREE_CODE (op2) == INTEGER_CST
19631 && wi::to_widest (op2) == (int) annot_expr_unroll_kind)
19632 op3 = cp_check_pragma_unroll (EXPR_LOCATION (TREE_OPERAND (t, 2)),
19633 op3);
19634 RETURN (build3_loc (EXPR_LOCATION (t), ANNOTATE_EXPR,
19635 TREE_TYPE (op1), op1, op2, op3));
19638 default:
19639 gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
19641 RETURN (tsubst_expr (t, args, complain, in_decl));
19644 RETURN (NULL_TREE);
19645 out:
19646 input_location = loc;
19647 return r;
19648 #undef RECUR
19649 #undef RETURN
19652 /* Instantiate the special body of the artificial DECL_OMP_DECLARE_REDUCTION
19653 function. For description of the body see comment above
19654 cp_parser_omp_declare_reduction_exprs. */
19656 static void
19657 tsubst_omp_udr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
19659 if (t == NULL_TREE || t == error_mark_node)
19660 return;
19662 gcc_assert (TREE_CODE (t) == STATEMENT_LIST && current_function_decl);
19664 tree_stmt_iterator tsi;
19665 int i;
19666 tree stmts[7];
19667 memset (stmts, 0, sizeof stmts);
19668 for (i = 0, tsi = tsi_start (t);
19669 i < 7 && !tsi_end_p (tsi);
19670 i++, tsi_next (&tsi))
19671 stmts[i] = tsi_stmt (tsi);
19672 gcc_assert (tsi_end_p (tsi));
19674 if (i >= 3)
19676 gcc_assert (TREE_CODE (stmts[0]) == DECL_EXPR
19677 && TREE_CODE (stmts[1]) == DECL_EXPR);
19678 tree omp_out = tsubst (DECL_EXPR_DECL (stmts[0]),
19679 args, complain, in_decl);
19680 tree omp_in = tsubst (DECL_EXPR_DECL (stmts[1]),
19681 args, complain, in_decl);
19682 /* tsubsting a local var_decl leaves DECL_CONTEXT null, as we
19683 expect to be pushing it. */
19684 DECL_CONTEXT (omp_out) = current_function_decl;
19685 DECL_CONTEXT (omp_in) = current_function_decl;
19686 keep_next_level (true);
19687 tree block = begin_omp_structured_block ();
19688 tsubst_stmt (stmts[2], args, complain, in_decl);
19689 block = finish_omp_structured_block (block);
19690 block = maybe_cleanup_point_expr_void (block);
19691 add_decl_expr (omp_out);
19692 copy_warning (omp_out, DECL_EXPR_DECL (stmts[0]));
19693 add_decl_expr (omp_in);
19694 finish_expr_stmt (block);
19696 if (i >= 6)
19698 gcc_assert (TREE_CODE (stmts[3]) == DECL_EXPR
19699 && TREE_CODE (stmts[4]) == DECL_EXPR);
19700 tree omp_priv = tsubst (DECL_EXPR_DECL (stmts[3]),
19701 args, complain, in_decl);
19702 tree omp_orig = tsubst (DECL_EXPR_DECL (stmts[4]),
19703 args, complain, in_decl);
19704 DECL_CONTEXT (omp_priv) = current_function_decl;
19705 DECL_CONTEXT (omp_orig) = current_function_decl;
19706 keep_next_level (true);
19707 tree block = begin_omp_structured_block ();
19708 tsubst_stmt (stmts[5], args, complain, in_decl);
19709 block = finish_omp_structured_block (block);
19710 block = maybe_cleanup_point_expr_void (block);
19711 cp_walk_tree (&block, cp_remove_omp_priv_cleanup_stmt, omp_priv, NULL);
19712 add_decl_expr (omp_priv);
19713 add_decl_expr (omp_orig);
19714 finish_expr_stmt (block);
19715 if (i == 7)
19716 add_decl_expr (omp_orig);
19720 /* T is a postfix-expression that is not being used in a function
19721 call. Return the substituted version of T. */
19723 static tree
19724 tsubst_non_call_postfix_expression (tree t, tree args,
19725 tsubst_flags_t complain,
19726 tree in_decl)
19728 if (TREE_CODE (t) == SCOPE_REF)
19729 t = tsubst_qualified_id (t, args, complain, in_decl,
19730 /*done=*/false, /*address_p=*/false);
19731 else
19732 t = tsubst_expr (t, args, complain, in_decl);
19734 return t;
19737 /* Subroutine of tsubst_lambda_expr: add the FIELD/INIT capture pair to the
19738 LAMBDA_EXPR_CAPTURE_LIST passed in LIST. Do deduction for a previously
19739 dependent init-capture. EXPLICIT_P is true if the original list had
19740 explicit captures. */
19742 static void
19743 prepend_one_capture (tree field, tree init, tree &list, bool explicit_p,
19744 tsubst_flags_t complain)
19746 if (tree auto_node = type_uses_auto (TREE_TYPE (field)))
19748 tree type = NULL_TREE;
19749 if (!init)
19751 if (complain & tf_error)
19752 error ("empty initializer in lambda init-capture");
19753 init = error_mark_node;
19755 else if (TREE_CODE (init) == TREE_LIST)
19756 init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
19757 if (!type)
19758 type = do_auto_deduction (TREE_TYPE (field), init, auto_node, complain);
19759 TREE_TYPE (field) = type;
19760 cp_apply_type_quals_to_decl (cp_type_quals (type), field);
19762 list = tree_cons (field, init, list);
19763 LAMBDA_CAPTURE_EXPLICIT_P (list) = explicit_p;
19766 /* T is a LAMBDA_EXPR. Generate a new LAMBDA_EXPR for the current
19767 instantiation context. Instantiating a pack expansion containing a lambda
19768 might result in multiple lambdas all based on the same lambda in the
19769 template. */
19771 tree
19772 tsubst_lambda_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
19774 tree oldfn = lambda_function (t);
19775 in_decl = oldfn;
19777 args = add_extra_args (LAMBDA_EXPR_EXTRA_ARGS (t), args, complain, in_decl);
19778 if (processing_template_decl
19779 && (!in_template_context || (complain & tf_partial)))
19781 /* Defer templated substitution into a lambda-expr if we lost the
19782 necessary template context. This may happen for a lambda-expr
19783 used as a default template argument.
19785 Defer dependent substitution as well so that we don't prematurely
19786 lower the level of a deduced return type or any other auto or
19787 template parameter belonging to the lambda. */
19788 t = copy_node (t);
19789 LAMBDA_EXPR_EXTRA_ARGS (t) = NULL_TREE;
19790 LAMBDA_EXPR_EXTRA_ARGS (t) = build_extra_args (t, args, complain);
19791 return t;
19794 tree r = build_lambda_expr ();
19796 LAMBDA_EXPR_LOCATION (r)
19797 = LAMBDA_EXPR_LOCATION (t);
19798 LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
19799 = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
19800 if (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
19801 LAMBDA_EXPR_REGEN_INFO (r)
19802 = build_template_info (t, add_to_template_args (TI_ARGS (ti),
19803 preserve_args (args)));
19804 else
19805 LAMBDA_EXPR_REGEN_INFO (r)
19806 = build_template_info (t, preserve_args (args));
19808 gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
19809 && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
19811 vec<tree,va_gc>* field_packs = NULL;
19812 unsigned name_independent_cnt = 0;
19813 for (tree cap = LAMBDA_EXPR_CAPTURE_LIST (t); cap;
19814 cap = TREE_CHAIN (cap))
19816 tree ofield = TREE_PURPOSE (cap);
19817 tree init = TREE_VALUE (cap);
19818 if (PACK_EXPANSION_P (init))
19819 init = tsubst_pack_expansion (init, args, complain, in_decl);
19820 else
19821 init = tsubst_expr (init, args, complain, in_decl);
19823 if (init == error_mark_node)
19824 return error_mark_node;
19826 if (init && TREE_CODE (init) == TREE_LIST)
19827 init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
19829 if (!processing_template_decl
19830 && init && TREE_CODE (init) != TREE_VEC
19831 && variably_modified_type_p (TREE_TYPE (init), NULL_TREE))
19833 /* For a VLA, simply tsubsting the field type won't work, we need to
19834 go through add_capture again. XXX do we want to do this for all
19835 captures? */
19836 tree name = (get_identifier
19837 (IDENTIFIER_POINTER (DECL_NAME (ofield)) + 2));
19838 tree ftype = TREE_TYPE (ofield);
19839 bool by_ref = (TYPE_REF_P (ftype)
19840 || (TREE_CODE (ftype) == DECLTYPE_TYPE
19841 && DECLTYPE_FOR_REF_CAPTURE (ftype)));
19842 add_capture (r, name, init, by_ref, !DECL_NORMAL_CAPTURE_P (ofield),
19843 &name_independent_cnt);
19844 continue;
19847 if (PACK_EXPANSION_P (ofield))
19848 ofield = PACK_EXPANSION_PATTERN (ofield);
19849 tree field = tsubst_decl (ofield, args, complain);
19851 if (DECL_PACK_P (ofield) && !DECL_NORMAL_CAPTURE_P (ofield))
19853 /* Remember these for when we've pushed local_specializations. */
19854 vec_safe_push (field_packs, ofield);
19855 vec_safe_push (field_packs, field);
19858 if (field == error_mark_node)
19859 return error_mark_node;
19861 if (TREE_CODE (field) == TREE_VEC)
19863 int len = TREE_VEC_LENGTH (field);
19864 gcc_assert (TREE_CODE (init) == TREE_VEC
19865 && TREE_VEC_LENGTH (init) == len);
19866 for (int i = 0; i < len; ++i)
19867 prepend_one_capture (TREE_VEC_ELT (field, i),
19868 TREE_VEC_ELT (init, i),
19869 LAMBDA_EXPR_CAPTURE_LIST (r),
19870 LAMBDA_CAPTURE_EXPLICIT_P (cap),
19871 complain);
19873 else
19875 prepend_one_capture (field, init, LAMBDA_EXPR_CAPTURE_LIST (r),
19876 LAMBDA_CAPTURE_EXPLICIT_P (cap), complain);
19878 if (id_equal (DECL_NAME (field), "__this"))
19879 LAMBDA_EXPR_THIS_CAPTURE (r) = field;
19883 tree type = begin_lambda_type (r);
19884 if (type == error_mark_node)
19886 gcc_checking_assert (!(complain & tf_error) || seen_error ());
19887 return error_mark_node;
19890 if (LAMBDA_EXPR_EXTRA_SCOPE (t))
19891 record_lambda_scope (r);
19892 else if (TYPE_NAMESPACE_SCOPE_P (TREE_TYPE (t)))
19893 /* If we're pushed into another scope (PR105652), fix it. */
19894 TYPE_CONTEXT (type) = DECL_CONTEXT (TYPE_NAME (type))
19895 = TYPE_CONTEXT (TREE_TYPE (t));
19896 record_lambda_scope_discriminator (r);
19898 /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set. */
19899 determine_visibility (TYPE_NAME (type));
19901 register_capture_members (LAMBDA_EXPR_CAPTURE_LIST (r));
19903 tree oldtmpl = (generic_lambda_fn_p (oldfn)
19904 ? DECL_TI_TEMPLATE (oldfn)
19905 : NULL_TREE);
19907 tree tparms = NULL_TREE;
19908 if (oldtmpl)
19909 tparms = tsubst_template_parms (DECL_TEMPLATE_PARMS (oldtmpl), args, complain);
19911 tree fntype = static_fn_type (oldfn);
19913 tree saved_ctp = current_template_parms;
19914 if (oldtmpl)
19916 ++processing_template_decl;
19917 current_template_parms = tparms;
19919 fntype = tsubst (fntype, args, complain, in_decl);
19920 if (oldtmpl)
19922 current_template_parms = saved_ctp;
19923 --processing_template_decl;
19926 if (fntype == error_mark_node)
19927 r = error_mark_node;
19928 else
19930 /* The body of a lambda-expression is not a subexpression of the
19931 enclosing expression. Parms are to have DECL_CHAIN tsubsted,
19932 which would be skipped if cp_unevaluated_operand. */
19933 cp_evaluated ev;
19935 /* Fix the type of 'this'.
19936 For static and xobj member functions we use this to transport the
19937 lambda's closure type. It appears that in the regular case the
19938 object parameter is still pulled off, and then re-added again anyway.
19939 So perhaps we could do something better here? */
19940 fntype = build_memfn_type (fntype, type,
19941 type_memfn_quals (fntype),
19942 type_memfn_rqual (fntype));
19943 tree inst = (oldtmpl
19944 ? tsubst_template_decl (oldtmpl, args, complain,
19945 fntype, tparms)
19946 : tsubst_function_decl (oldfn, args, complain, fntype));
19947 if (inst == error_mark_node)
19949 r = error_mark_node;
19950 goto out;
19952 finish_member_declaration (inst);
19953 record_lambda_scope_sig_discriminator (r, inst);
19955 tree fn = oldtmpl ? DECL_TEMPLATE_RESULT (inst) : inst;
19957 /* Let finish_function set this. */
19958 DECL_DECLARED_CONSTEXPR_P (fn) = false;
19960 bool nested = cfun;
19961 if (nested)
19962 push_function_context ();
19963 else
19964 /* Still increment function_depth so that we don't GC in the
19965 middle of an expression. */
19966 ++function_depth;
19968 local_specialization_stack s (lss_copy);
19970 bool save_in_consteval_if_p = in_consteval_if_p;
19971 in_consteval_if_p = false;
19973 tree body = start_lambda_function (fn, r);
19975 /* Now record them for lookup_init_capture_pack. */
19976 int fplen = vec_safe_length (field_packs);
19977 for (int i = 0; i < fplen; )
19979 tree pack = (*field_packs)[i++];
19980 tree inst = (*field_packs)[i++];
19981 register_local_specialization (inst, pack);
19983 release_tree_vector (field_packs);
19985 register_parameter_specializations (oldfn, fn);
19987 if (oldtmpl)
19989 /* We might not partially instantiate some parts of the function, so
19990 copy these flags from the original template. */
19991 language_function *ol = DECL_STRUCT_FUNCTION (oldfn)->language;
19992 current_function_returns_value = ol->returns_value;
19993 current_function_returns_null = ol->returns_null;
19994 current_function_returns_abnormally = ol->returns_abnormally;
19995 current_function_infinite_loop = ol->infinite_loop;
19998 /* [temp.deduct] A lambda-expression appearing in a function type or a
19999 template parameter is not considered part of the immediate context for
20000 the purposes of template argument deduction. */
20001 complain = tf_warning_or_error;
20003 tree saved = DECL_SAVED_TREE (oldfn);
20004 if (TREE_CODE (saved) == BIND_EXPR && BIND_EXPR_BODY_BLOCK (saved))
20005 /* We already have a body block from start_lambda_function, we don't
20006 need another to confuse NRV (91217). */
20007 saved = BIND_EXPR_BODY (saved);
20009 tsubst_stmt (saved, args, complain, r);
20011 finish_lambda_function (body);
20013 in_consteval_if_p = save_in_consteval_if_p;
20015 if (nested)
20016 pop_function_context ();
20017 else
20018 --function_depth;
20020 /* The capture list was built up in reverse order; fix that now. */
20021 LAMBDA_EXPR_CAPTURE_LIST (r)
20022 = nreverse (LAMBDA_EXPR_CAPTURE_LIST (r));
20024 LAMBDA_EXPR_THIS_CAPTURE (r) = NULL_TREE;
20026 maybe_add_lambda_conv_op (type);
20029 out:
20030 finish_struct (type, /*attr*/NULL_TREE);
20032 insert_pending_capture_proxies ();
20034 return r;
20037 /* Subroutine of maybe_fold_fn_template_args. */
20039 static bool
20040 fold_targs_r (tree targs, tsubst_flags_t complain)
20042 int len = TREE_VEC_LENGTH (targs);
20043 for (int i = 0; i < len; ++i)
20045 tree &elt = TREE_VEC_ELT (targs, i);
20046 if (!elt || TYPE_P (elt)
20047 || TREE_CODE (elt) == TEMPLATE_DECL)
20048 continue;
20049 if (TREE_CODE (elt) == NONTYPE_ARGUMENT_PACK)
20051 if (!fold_targs_r (ARGUMENT_PACK_ARGS (elt), complain))
20052 return false;
20054 else if (/* We can only safely preevaluate scalar prvalues. */
20055 SCALAR_TYPE_P (TREE_TYPE (elt))
20056 && !glvalue_p (elt)
20057 && !TREE_CONSTANT (elt))
20059 elt = cxx_constant_value (elt, complain);
20060 if (elt == error_mark_node)
20061 return false;
20065 return true;
20068 /* Try to do constant evaluation of any explicit template arguments in FN
20069 before overload resolution, to get any errors only once. Return true iff
20070 we didn't have any problems folding. */
20072 static bool
20073 maybe_fold_fn_template_args (tree fn, tsubst_flags_t complain)
20075 if (processing_template_decl || fn == NULL_TREE)
20076 return true;
20077 if (fn == error_mark_node)
20078 return false;
20079 if (TREE_CODE (fn) == OFFSET_REF
20080 || TREE_CODE (fn) == COMPONENT_REF)
20081 fn = TREE_OPERAND (fn, 1);
20082 if (BASELINK_P (fn))
20083 fn = BASELINK_FUNCTIONS (fn);
20084 if (TREE_CODE (fn) != TEMPLATE_ID_EXPR)
20085 return true;
20086 tree targs = TREE_OPERAND (fn, 1);
20087 if (targs == NULL_TREE)
20088 return true;
20089 if (targs == error_mark_node)
20090 return false;
20091 return fold_targs_r (targs, complain);
20094 /* Helper function for tsubst_expr CALL_EXPR and ARRAY_REF handling. */
20096 static void
20097 tsubst_call_args (tree t, tree args, tsubst_flags_t complain,
20098 tree in_decl, releasing_vec &call_args)
20100 unsigned int nargs = call_expr_nargs (t);
20101 for (unsigned int i = 0; i < nargs; ++i)
20103 tree arg = CALL_EXPR_ARG (t, i);
20105 if (!PACK_EXPANSION_P (arg))
20106 vec_safe_push (call_args, tsubst_expr (arg, args, complain, in_decl));
20107 else
20109 /* Expand the pack expansion and push each entry onto CALL_ARGS. */
20110 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
20111 if (TREE_CODE (arg) == TREE_VEC)
20113 unsigned int len, j;
20115 len = TREE_VEC_LENGTH (arg);
20116 for (j = 0; j < len; ++j)
20118 tree value = TREE_VEC_ELT (arg, j);
20119 if (value != NULL_TREE)
20120 value = convert_from_reference (value);
20121 vec_safe_push (call_args, value);
20124 else
20125 /* A partial substitution. Add one entry. */
20126 vec_safe_push (call_args, arg);
20131 /* Like tsubst but deals with expressions and performs semantic
20132 analysis. */
20134 tree
20135 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
20137 #define RETURN(EXP) do { retval = (EXP); goto out; } while(0)
20138 #define RECUR(NODE) \
20139 tsubst_expr (NODE, args, complain, in_decl)
20141 tree retval, op1;
20142 location_t save_loc;
20144 if (t == NULL_TREE || t == error_mark_node)
20145 return t;
20147 save_loc = input_location;
20148 if (location_t eloc = cp_expr_location (t))
20149 input_location = eloc;
20151 /* N3276 decltype magic only applies to calls at the top level or on the
20152 right side of a comma. */
20153 tsubst_flags_t decltype_flag = (complain & tf_decltype);
20154 complain &= ~tf_decltype;
20156 /* This flag only applies to id-expressions at the top level, and
20157 controls resolution thereof. */
20158 tsubst_flags_t no_name_lookup_flag = (complain & tf_no_name_lookup);
20159 complain &= ~tf_no_name_lookup;
20161 if (!no_name_lookup_flag)
20162 if (tree d = maybe_dependent_member_ref (t, args, complain, in_decl))
20163 return d;
20165 switch (TREE_CODE (t))
20167 case USING_DECL:
20168 t = DECL_NAME (t);
20169 /* Fall through. */
20170 case IDENTIFIER_NODE:
20172 tree decl;
20173 cp_id_kind idk;
20174 const char *error_msg;
20176 if (IDENTIFIER_CONV_OP_P (t))
20178 tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20179 t = make_conv_op_name (new_type);
20182 if (no_name_lookup_flag)
20183 RETURN (t);
20185 /* Look up the name. */
20186 decl = lookup_name (t);
20188 /* By convention, expressions use ERROR_MARK_NODE to indicate
20189 failure, not NULL_TREE. */
20190 if (decl == NULL_TREE)
20191 decl = error_mark_node;
20193 decl = finish_id_expression (t, decl, NULL_TREE,
20194 &idk,
20195 /*i_c_e_p=*/false,
20196 /*allow_i_c_e_p=*/true,
20197 /*non_i_c_e_p=*/nullptr,
20198 /*template_p=*/false,
20199 /*done=*/true,
20200 /*address_p=*/false,
20201 /*template_arg_p=*/false,
20202 &error_msg,
20203 input_location);
20204 if (error_msg)
20205 error (error_msg);
20206 if (identifier_p (decl))
20208 if (complain & tf_error)
20209 unqualified_name_lookup_error (decl);
20210 decl = error_mark_node;
20212 RETURN (decl);
20215 case TEMPLATE_ID_EXPR:
20217 tree object;
20218 tree templ = TREE_OPERAND (t, 0);
20219 tree targs = TREE_OPERAND (t, 1);
20221 if (no_name_lookup_flag)
20222 templ = tsubst_name (templ, args, complain, in_decl);
20223 else
20224 templ = tsubst_expr (templ, args, complain, in_decl);
20226 if (targs)
20227 targs = tsubst_template_args (targs, args, complain, in_decl);
20228 if (targs == error_mark_node)
20229 RETURN (error_mark_node);
20231 if (TREE_CODE (templ) == SCOPE_REF)
20233 tree name = TREE_OPERAND (templ, 1);
20234 tree tid = lookup_template_function (name, targs);
20235 TREE_OPERAND (templ, 1) = tid;
20236 RETURN (templ);
20239 if (concept_definition_p (templ))
20241 tree check = build_concept_check (templ, targs, complain);
20242 if (check == error_mark_node)
20243 RETURN (error_mark_node);
20244 RETURN (check);
20247 if (variable_template_p (templ))
20249 if (no_name_lookup_flag)
20250 RETURN (lookup_template_variable (templ, targs, complain));
20252 tree r = lookup_and_finish_template_variable (templ, targs,
20253 complain);
20254 r = convert_from_reference (r);
20255 r = maybe_wrap_with_location (r, EXPR_LOCATION (t));
20256 RETURN (r);
20259 if (TREE_CODE (templ) == COMPONENT_REF)
20261 object = TREE_OPERAND (templ, 0);
20262 templ = TREE_OPERAND (templ, 1);
20264 else
20265 object = NULL_TREE;
20267 tree tid = lookup_template_function (templ, targs);
20268 protected_set_expr_location (tid, EXPR_LOCATION (t));
20270 if (object)
20271 RETURN (build3 (COMPONENT_REF, TREE_TYPE (tid),
20272 object, tid, NULL_TREE));
20273 else if (no_name_lookup_flag)
20274 RETURN (tid);
20275 else if (identifier_p (templ))
20277 /* C++20 P0846: we can encounter an IDENTIFIER_NODE here when
20278 name lookup found nothing when parsing the template name. */
20279 gcc_assert (cxx_dialect >= cxx20 || seen_error ());
20280 RETURN (tid);
20282 else
20283 RETURN (baselink_for_fns (tid));
20286 case INDIRECT_REF:
20288 tree r = RECUR (TREE_OPERAND (t, 0));
20290 if (REFERENCE_REF_P (t))
20292 /* A type conversion to reference type will be enclosed in
20293 such an indirect ref, but the substitution of the cast
20294 will have also added such an indirect ref. */
20295 r = convert_from_reference (r);
20297 else
20298 r = build_x_indirect_ref (input_location, r, RO_UNARY_STAR,
20299 templated_operator_saved_lookups (t),
20300 complain|decltype_flag);
20302 if (REF_PARENTHESIZED_P (t))
20303 r = force_paren_expr (r);
20305 RETURN (r);
20308 case MEM_REF:
20310 tree op0 = RECUR (TREE_OPERAND (t, 0));
20311 tree op1 = RECUR (TREE_OPERAND (t, 0));
20312 tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20313 RETURN (build2_loc (EXPR_LOCATION (t), MEM_REF, new_type, op0, op1));
20316 case NOP_EXPR:
20318 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20319 tree op0 = RECUR (TREE_OPERAND (t, 0));
20320 RETURN (build_nop (type, op0));
20323 case IMPLICIT_CONV_EXPR:
20325 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20326 if (type == error_mark_node)
20327 RETURN (error_mark_node);
20328 tree expr = RECUR (TREE_OPERAND (t, 0));
20329 if (dependent_type_p (type) || type_dependent_expression_p (expr))
20331 retval = copy_node (t);
20332 TREE_TYPE (retval) = type;
20333 TREE_OPERAND (retval, 0) = expr;
20334 RETURN (retval);
20336 if (IMPLICIT_CONV_EXPR_NONTYPE_ARG (t))
20338 tree r = convert_nontype_argument (type, expr, complain);
20339 if (r == NULL_TREE)
20340 r = error_mark_node;
20341 RETURN (r);
20343 int flags = LOOKUP_IMPLICIT;
20344 if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
20345 flags = LOOKUP_NORMAL;
20346 if (IMPLICIT_CONV_EXPR_BRACED_INIT (t))
20347 flags |= LOOKUP_NO_NARROWING;
20348 RETURN (perform_implicit_conversion_flags (type, expr, complain,
20349 flags));
20352 case CONVERT_EXPR:
20354 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20355 tree op0 = RECUR (TREE_OPERAND (t, 0));
20356 if (op0 == error_mark_node)
20357 RETURN (error_mark_node);
20358 RETURN (build1 (CONVERT_EXPR, type, op0));
20361 case CAST_EXPR:
20362 case REINTERPRET_CAST_EXPR:
20363 case CONST_CAST_EXPR:
20364 case DYNAMIC_CAST_EXPR:
20365 case STATIC_CAST_EXPR:
20367 tree type;
20368 tree op, r = NULL_TREE;
20370 tsubst_flags_t tcomplain = complain;
20371 if (TREE_CODE (t) == CAST_EXPR)
20372 tcomplain |= tf_tst_ok;
20373 type = tsubst (TREE_TYPE (t), args, tcomplain, in_decl);
20375 op = RECUR (TREE_OPERAND (t, 0));
20377 warning_sentinel s(warn_useless_cast);
20378 warning_sentinel s2(warn_ignored_qualifiers);
20379 warning_sentinel s3(warn_int_in_bool_context);
20380 switch (TREE_CODE (t))
20382 case CAST_EXPR:
20383 r = build_functional_cast (input_location, type, op, complain);
20384 break;
20385 case REINTERPRET_CAST_EXPR:
20386 r = build_reinterpret_cast (input_location, type, op, complain);
20387 break;
20388 case CONST_CAST_EXPR:
20389 r = build_const_cast (input_location, type, op, complain);
20390 break;
20391 case DYNAMIC_CAST_EXPR:
20392 r = build_dynamic_cast (input_location, type, op, complain);
20393 break;
20394 case STATIC_CAST_EXPR:
20395 r = build_static_cast (input_location, type, op, complain);
20396 if (IMPLICIT_RVALUE_P (t))
20397 set_implicit_rvalue_p (r);
20398 break;
20399 default:
20400 gcc_unreachable ();
20403 RETURN (r);
20406 case BIT_CAST_EXPR:
20408 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20409 tree op0 = RECUR (TREE_OPERAND (t, 0));
20410 RETURN (cp_build_bit_cast (EXPR_LOCATION (t), type, op0, complain));
20413 case POSTDECREMENT_EXPR:
20414 case POSTINCREMENT_EXPR:
20415 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20416 args, complain, in_decl);
20417 RETURN (build_x_unary_op (input_location, TREE_CODE (t), op1,
20418 templated_operator_saved_lookups (t),
20419 complain|decltype_flag));
20421 case BIT_NOT_EXPR:
20422 if (identifier_p (TREE_OPERAND (t, 0)))
20424 gcc_checking_assert (no_name_lookup_flag);
20425 RETURN (t);
20427 else if (TYPE_P (TREE_OPERAND (t, 0)))
20429 gcc_checking_assert (no_name_lookup_flag);
20430 tree op0 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
20431 RETURN (build_min_nt_loc (EXPR_LOCATION (t), BIT_NOT_EXPR, op0));
20433 /* Fall through. */
20434 case PREDECREMENT_EXPR:
20435 case PREINCREMENT_EXPR:
20436 case NEGATE_EXPR:
20437 case ABS_EXPR:
20438 case TRUTH_NOT_EXPR:
20439 case UNARY_PLUS_EXPR: /* Unary + */
20440 case REALPART_EXPR:
20441 case IMAGPART_EXPR:
20442 RETURN (build_x_unary_op (input_location, TREE_CODE (t),
20443 RECUR (TREE_OPERAND (t, 0)),
20444 templated_operator_saved_lookups (t),
20445 complain|decltype_flag));
20447 case EXCESS_PRECISION_EXPR:
20449 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20450 tree op0 = RECUR (TREE_OPERAND (t, 0));
20451 if (TREE_CODE (op0) == EXCESS_PRECISION_EXPR)
20452 RETURN (op0);
20453 RETURN (build1_loc (EXPR_LOCATION (t), EXCESS_PRECISION_EXPR,
20454 type, op0));
20457 case FIX_TRUNC_EXPR:
20458 /* convert_like should have created an IMPLICIT_CONV_EXPR. */
20459 gcc_unreachable ();
20461 case ADDR_EXPR:
20462 op1 = TREE_OPERAND (t, 0);
20463 if (TREE_CODE (op1) == LABEL_DECL)
20464 RETURN (finish_label_address_expr (DECL_NAME (op1),
20465 EXPR_LOCATION (op1)));
20466 if (TREE_CODE (op1) == SCOPE_REF)
20467 op1 = tsubst_qualified_id (op1, args, complain, in_decl,
20468 /*done=*/true, /*address_p=*/true);
20469 else
20470 op1 = tsubst_non_call_postfix_expression (op1, args, complain,
20471 in_decl);
20472 RETURN (build_x_unary_op (input_location, ADDR_EXPR, op1,
20473 templated_operator_saved_lookups (t),
20474 complain|decltype_flag));
20476 case PLUS_EXPR:
20477 case MINUS_EXPR:
20478 case MULT_EXPR:
20479 case TRUNC_DIV_EXPR:
20480 case CEIL_DIV_EXPR:
20481 case FLOOR_DIV_EXPR:
20482 case ROUND_DIV_EXPR:
20483 case EXACT_DIV_EXPR:
20484 case BIT_AND_EXPR:
20485 case BIT_IOR_EXPR:
20486 case BIT_XOR_EXPR:
20487 case TRUNC_MOD_EXPR:
20488 case FLOOR_MOD_EXPR:
20489 case TRUTH_ANDIF_EXPR:
20490 case TRUTH_ORIF_EXPR:
20491 case TRUTH_AND_EXPR:
20492 case TRUTH_OR_EXPR:
20493 case RSHIFT_EXPR:
20494 case LSHIFT_EXPR:
20495 case EQ_EXPR:
20496 case NE_EXPR:
20497 case MAX_EXPR:
20498 case MIN_EXPR:
20499 case LE_EXPR:
20500 case GE_EXPR:
20501 case LT_EXPR:
20502 case GT_EXPR:
20503 case SPACESHIP_EXPR:
20504 case MEMBER_REF:
20505 case DOTSTAR_EXPR:
20507 /* If either OP0 or OP1 was value- or type-dependent, suppress
20508 warnings that depend on the range of the types involved. */
20509 tree op0 = TREE_OPERAND (t, 0);
20510 tree op1 = TREE_OPERAND (t, 1);
20511 const bool was_dep = (dependent_operand_p (op0)
20512 || dependent_operand_p (op1));
20513 op0 = RECUR (op0);
20514 op1 = RECUR (op1);
20516 warning_sentinel s1(warn_type_limits, was_dep);
20517 warning_sentinel s2(warn_div_by_zero, was_dep);
20518 warning_sentinel s3(warn_logical_op, was_dep);
20519 warning_sentinel s4(warn_tautological_compare, was_dep);
20520 warning_sentinel s5(warn_address, was_dep);
20522 tree r = build_x_binary_op
20523 (input_location, TREE_CODE (t),
20524 op0,
20525 (warning_suppressed_p (TREE_OPERAND (t, 0))
20526 ? ERROR_MARK
20527 : TREE_CODE (TREE_OPERAND (t, 0))),
20528 op1,
20529 (warning_suppressed_p (TREE_OPERAND (t, 1))
20530 ? ERROR_MARK
20531 : TREE_CODE (TREE_OPERAND (t, 1))),
20532 templated_operator_saved_lookups (t),
20533 /*overload=*/NULL,
20534 complain|decltype_flag);
20535 if (EXPR_P (r))
20536 copy_warning (r, t);
20538 RETURN (r);
20541 case POINTER_PLUS_EXPR:
20543 tree op0 = RECUR (TREE_OPERAND (t, 0));
20544 if (op0 == error_mark_node)
20545 RETURN (error_mark_node);
20546 tree op1 = RECUR (TREE_OPERAND (t, 1));
20547 if (op1 == error_mark_node)
20548 RETURN (error_mark_node);
20549 RETURN (fold_build_pointer_plus (op0, op1));
20552 case SCOPE_REF:
20553 if (no_name_lookup_flag)
20555 tree op0 = tsubst_scope (TREE_OPERAND (t, 0), args, complain, in_decl);
20556 tree op1 = tsubst_name (TREE_OPERAND (t, 1), args, complain, in_decl);
20557 RETURN (build_qualified_name (/*type=*/NULL_TREE, op0, op1,
20558 QUALIFIED_NAME_IS_TEMPLATE (t)));
20560 else
20561 RETURN (tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
20562 /*address_p=*/false));
20564 case BASELINK:
20565 RETURN (tsubst_baselink (t, current_nonlambda_class_type (),
20566 args, complain, in_decl));
20568 case ARRAY_REF:
20569 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20570 args, complain, in_decl);
20571 if (TREE_CODE (TREE_OPERAND (t, 1)) == CALL_EXPR
20572 && (CALL_EXPR_FN (TREE_OPERAND (t, 1))
20573 == ovl_op_identifier (ARRAY_REF)))
20575 tree c = TREE_OPERAND (t, 1);
20576 releasing_vec index_exp_list;
20577 tsubst_call_args (c, args, complain, in_decl, index_exp_list);
20579 tree r;
20580 if (vec_safe_length (index_exp_list) == 1
20581 && !PACK_EXPANSION_P (index_exp_list[0]))
20582 r = grok_array_decl (EXPR_LOCATION (t), op1,
20583 index_exp_list[0], NULL,
20584 complain | decltype_flag);
20585 else
20586 r = grok_array_decl (EXPR_LOCATION (t), op1,
20587 NULL_TREE, &index_exp_list,
20588 complain | decltype_flag);
20589 RETURN (r);
20591 RETURN (build_x_array_ref (EXPR_LOCATION (t), op1,
20592 RECUR (TREE_OPERAND (t, 1)),
20593 complain|decltype_flag));
20595 case OMP_ARRAY_SECTION:
20597 tree op0 = RECUR (TREE_OPERAND (t, 0));
20598 tree op1 = NULL_TREE, op2 = NULL_TREE;
20599 if (op0 == error_mark_node)
20600 RETURN (error_mark_node);
20601 if (TREE_OPERAND (t, 1))
20603 op1 = RECUR (TREE_OPERAND (t, 1));
20604 if (op1 == error_mark_node)
20605 RETURN (error_mark_node);
20607 if (TREE_OPERAND (t, 2))
20609 op2 = RECUR (TREE_OPERAND (t, 2));
20610 if (op2 == error_mark_node)
20611 RETURN (error_mark_node);
20613 RETURN (build_omp_array_section (EXPR_LOCATION (t), op0, op1, op2));
20616 case SIZEOF_EXPR:
20617 if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
20618 || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
20620 tree expanded, op = TREE_OPERAND (t, 0);
20621 int len = 0;
20623 if (SIZEOF_EXPR_TYPE_P (t))
20624 op = TREE_TYPE (op);
20626 ++cp_unevaluated_operand;
20627 ++c_inhibit_evaluation_warnings;
20628 /* We only want to compute the number of arguments. */
20629 if (PACK_EXPANSION_P (op))
20630 expanded = tsubst_pack_expansion (op, args, complain, in_decl);
20631 else
20632 expanded = tsubst_template_args (ARGUMENT_PACK_ARGS (op),
20633 args, complain, in_decl);
20634 --cp_unevaluated_operand;
20635 --c_inhibit_evaluation_warnings;
20637 if (TREE_CODE (expanded) == TREE_VEC)
20639 len = TREE_VEC_LENGTH (expanded);
20640 /* Set TREE_USED for the benefit of -Wunused. */
20641 for (int i = 0; i < len; i++)
20642 if (DECL_P (TREE_VEC_ELT (expanded, i)))
20643 TREE_USED (TREE_VEC_ELT (expanded, i)) = true;
20646 if (expanded == error_mark_node)
20647 RETURN (error_mark_node);
20648 else if (PACK_EXPANSION_P (expanded)
20649 || (TREE_CODE (expanded) == TREE_VEC
20650 && pack_expansion_args_count (expanded)))
20653 if (PACK_EXPANSION_P (expanded))
20654 /* OK. */;
20655 else
20656 expanded = make_argument_pack (expanded);
20658 if (TYPE_P (expanded))
20659 RETURN (cxx_sizeof_or_alignof_type (input_location,
20660 expanded, SIZEOF_EXPR,
20661 false,
20662 complain & tf_error));
20663 else
20664 RETURN (cxx_sizeof_or_alignof_expr (input_location,
20665 expanded, SIZEOF_EXPR,
20666 false,
20667 complain & tf_error));
20669 else
20670 RETURN (build_int_cst (size_type_node, len));
20672 /* Fall through */
20674 case ALIGNOF_EXPR:
20676 tree r;
20678 op1 = TREE_OPERAND (t, 0);
20679 if (TREE_CODE (t) == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (t))
20680 op1 = TREE_TYPE (op1);
20681 bool std_alignof = (TREE_CODE (t) == ALIGNOF_EXPR
20682 && ALIGNOF_EXPR_STD_P (t));
20683 if (!args)
20685 /* When there are no ARGS, we are trying to evaluate a
20686 non-dependent expression from the parser. Trying to do
20687 the substitutions may not work. */
20688 if (!TYPE_P (op1))
20689 op1 = TREE_TYPE (op1);
20691 else
20693 ++cp_unevaluated_operand;
20694 ++c_inhibit_evaluation_warnings;
20695 if (TYPE_P (op1))
20696 op1 = tsubst (op1, args, complain, in_decl);
20697 else
20698 op1 = tsubst_expr (op1, args, complain, in_decl);
20699 --cp_unevaluated_operand;
20700 --c_inhibit_evaluation_warnings;
20702 if (TYPE_P (op1))
20703 r = cxx_sizeof_or_alignof_type (input_location,
20704 op1, TREE_CODE (t), std_alignof,
20705 complain & tf_error);
20706 else
20707 r = cxx_sizeof_or_alignof_expr (input_location,
20708 op1, TREE_CODE (t), std_alignof,
20709 complain & tf_error);
20710 if (TREE_CODE (t) == SIZEOF_EXPR && r != error_mark_node)
20712 if (TREE_CODE (r) != SIZEOF_EXPR || TYPE_P (op1))
20714 if (!processing_template_decl && TYPE_P (op1))
20716 r = build_min (SIZEOF_EXPR, size_type_node,
20717 build1 (NOP_EXPR, op1, error_mark_node));
20718 SIZEOF_EXPR_TYPE_P (r) = 1;
20720 else
20721 r = build_min (SIZEOF_EXPR, size_type_node, op1);
20722 TREE_SIDE_EFFECTS (r) = 0;
20723 TREE_READONLY (r) = 1;
20725 SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
20726 copy_warning (r, t);
20728 RETURN (r);
20731 case AT_ENCODE_EXPR:
20733 op1 = TREE_OPERAND (t, 0);
20734 ++cp_unevaluated_operand;
20735 ++c_inhibit_evaluation_warnings;
20736 op1 = tsubst (op1, args, complain, in_decl);
20737 --cp_unevaluated_operand;
20738 --c_inhibit_evaluation_warnings;
20739 RETURN (objc_build_encode_expr (op1));
20742 case NOEXCEPT_EXPR:
20743 op1 = TREE_OPERAND (t, 0);
20744 ++cp_unevaluated_operand;
20745 ++c_inhibit_evaluation_warnings;
20746 ++cp_noexcept_operand;
20747 op1 = tsubst_expr (op1, args, complain, in_decl);
20748 --cp_unevaluated_operand;
20749 --c_inhibit_evaluation_warnings;
20750 --cp_noexcept_operand;
20751 RETURN (finish_noexcept_expr (op1, complain));
20753 case MODOP_EXPR:
20755 warning_sentinel s(warn_div_by_zero);
20756 tree lhs = RECUR (TREE_OPERAND (t, 0));
20757 tree rhs = RECUR (TREE_OPERAND (t, 2));
20759 tree r = build_x_modify_expr
20760 (EXPR_LOCATION (t), lhs, TREE_CODE (TREE_OPERAND (t, 1)), rhs,
20761 templated_operator_saved_lookups (t),
20762 complain|decltype_flag);
20763 /* TREE_NO_WARNING must be set if either the expression was
20764 parenthesized or it uses an operator such as >>= rather
20765 than plain assignment. In the former case, it was already
20766 set and must be copied. In the latter case,
20767 build_x_modify_expr sets it and it must not be reset
20768 here. */
20769 if (warning_suppressed_p (t, OPT_Wparentheses))
20770 suppress_warning (STRIP_REFERENCE_REF (r), OPT_Wparentheses);
20772 RETURN (r);
20775 case ARROW_EXPR:
20776 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20777 args, complain, in_decl);
20778 /* Remember that there was a reference to this entity. */
20779 if (DECL_P (op1)
20780 && !mark_used (op1, complain) && !(complain & tf_error))
20781 RETURN (error_mark_node);
20782 RETURN (build_x_arrow (input_location, op1, complain));
20784 case NEW_EXPR:
20786 tree placement = RECUR (TREE_OPERAND (t, 0));
20787 tree init = RECUR (TREE_OPERAND (t, 3));
20788 vec<tree, va_gc> *placement_vec;
20789 vec<tree, va_gc> *init_vec;
20790 tree ret;
20791 location_t loc = EXPR_LOCATION (t);
20793 if (placement == NULL_TREE)
20794 placement_vec = NULL;
20795 else if (placement == error_mark_node)
20796 RETURN (error_mark_node);
20797 else
20799 placement_vec = make_tree_vector ();
20800 for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
20801 vec_safe_push (placement_vec, TREE_VALUE (placement));
20804 /* If there was an initializer in the original tree, but it
20805 instantiated to an empty list, then we should pass a
20806 non-NULL empty vector to tell build_new that it was an
20807 empty initializer() rather than no initializer. This can
20808 only happen when the initializer is a pack expansion whose
20809 parameter packs are of length zero. */
20810 if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
20811 init_vec = NULL;
20812 else if (init == error_mark_node)
20813 RETURN (error_mark_node);
20814 else
20816 init_vec = make_tree_vector ();
20817 if (init == void_node)
20818 gcc_assert (init_vec != NULL);
20819 else
20821 for (; init != NULL_TREE; init = TREE_CHAIN (init))
20822 vec_safe_push (init_vec, TREE_VALUE (init));
20826 /* Avoid passing an enclosing decl to valid_array_size_p. */
20827 in_decl = NULL_TREE;
20829 tree op1 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
20830 tree op2 = RECUR (TREE_OPERAND (t, 2));
20831 ret = build_new (loc, &placement_vec, op1, op2,
20832 &init_vec, NEW_EXPR_USE_GLOBAL (t),
20833 complain);
20835 if (placement_vec != NULL)
20836 release_tree_vector (placement_vec);
20837 if (init_vec != NULL)
20838 release_tree_vector (init_vec);
20840 RETURN (ret);
20843 case DELETE_EXPR:
20845 tree op0 = RECUR (TREE_OPERAND (t, 0));
20846 tree op1 = RECUR (TREE_OPERAND (t, 1));
20847 RETURN (delete_sanity (input_location, op0, op1,
20848 DELETE_EXPR_USE_VEC (t),
20849 DELETE_EXPR_USE_GLOBAL (t),
20850 complain));
20853 case COMPOUND_EXPR:
20855 tree op0 = tsubst_expr (TREE_OPERAND (t, 0), args,
20856 complain & ~tf_decltype, in_decl);
20857 RETURN (build_x_compound_expr (EXPR_LOCATION (t),
20858 op0,
20859 RECUR (TREE_OPERAND (t, 1)),
20860 templated_operator_saved_lookups (t),
20861 complain|decltype_flag));
20864 case CALL_EXPR:
20866 tree function;
20867 unsigned int nargs;
20868 bool qualified_p;
20869 bool koenig_p;
20870 tree ret;
20872 function = CALL_EXPR_FN (t);
20873 /* Internal function with no arguments. */
20874 if (function == NULL_TREE && call_expr_nargs (t) == 0)
20875 RETURN (t);
20877 /* When we parsed the expression, we determined whether or
20878 not Koenig lookup should be performed. */
20879 koenig_p = KOENIG_LOOKUP_P (t);
20880 if (function == NULL_TREE)
20882 koenig_p = false;
20883 qualified_p = false;
20885 else if (TREE_CODE (function) == SCOPE_REF)
20887 qualified_p = true;
20888 function = tsubst_qualified_id (function, args, complain, in_decl,
20889 /*done=*/false,
20890 /*address_p=*/false);
20892 else if (CALL_EXPR_STATIC_CHAIN (t)
20893 && TREE_CODE (function) == FUNCTION_DECL
20894 && fndecl_built_in_p (function, BUILT_IN_CLASSIFY_TYPE))
20896 tree type = tsubst (CALL_EXPR_STATIC_CHAIN (t), args, complain,
20897 in_decl);
20898 if (dependent_type_p (type))
20900 ret = build_vl_exp (CALL_EXPR, 4);
20901 CALL_EXPR_FN (ret) = function;
20902 CALL_EXPR_STATIC_CHAIN (ret) = type;
20903 CALL_EXPR_ARG (ret, 0)
20904 = build_min (SIZEOF_EXPR, size_type_node, type);
20905 TREE_TYPE (ret) = integer_type_node;
20907 else
20908 ret = build_int_cst (integer_type_node, type_to_class (type));
20909 RETURN (ret);
20911 else if (koenig_p
20912 && (identifier_p (function)
20913 || (TREE_CODE (function) == TEMPLATE_ID_EXPR
20914 && identifier_p (TREE_OPERAND (function, 0)))))
20916 /* Do nothing; calling tsubst_expr on an identifier
20917 would incorrectly perform unqualified lookup again.
20919 Note that we can also have an IDENTIFIER_NODE if the earlier
20920 unqualified lookup found a dependent local extern declaration
20921 (as per finish_call_expr); in that case koenig_p will be false
20922 and we do want to do the lookup again to find the substituted
20923 declaration. */
20924 qualified_p = false;
20926 if (TREE_CODE (function) == TEMPLATE_ID_EXPR)
20927 function = tsubst_name (function, args, complain, in_decl);
20929 else
20931 if (TREE_CODE (function) == COMPONENT_REF)
20933 tree op = TREE_OPERAND (function, 1);
20935 qualified_p = (TREE_CODE (op) == SCOPE_REF
20936 || (BASELINK_P (op)
20937 && BASELINK_QUALIFIED_P (op)));
20939 else
20940 qualified_p = false;
20942 if (TREE_CODE (function) == ADDR_EXPR
20943 && TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL)
20944 /* Avoid error about taking the address of a constructor. */
20945 function = TREE_OPERAND (function, 0);
20947 tsubst_flags_t subcomplain = complain;
20948 if (koenig_p && TREE_CODE (function) == FUNCTION_DECL)
20949 /* When KOENIG_P, we don't want to mark_used the callee before
20950 augmenting the overload set via ADL, so during this initial
20951 substitution we disable mark_used by setting tf_conv (68942). */
20952 subcomplain |= tf_conv;
20953 function = tsubst_expr (function, args, subcomplain, in_decl);
20955 if (BASELINK_P (function))
20956 qualified_p = true;
20959 nargs = call_expr_nargs (t);
20960 releasing_vec call_args;
20961 tsubst_call_args (t, args, complain, in_decl, call_args);
20963 /* Stripped-down processing for a call in a thunk. Specifically, in
20964 the thunk template for a generic lambda. */
20965 if (call_from_lambda_thunk_p (t))
20967 /* Now that we've expanded any packs, the number of call args
20968 might be different. */
20969 unsigned int cargs = call_args->length ();
20970 tree thisarg = NULL_TREE;
20971 if (TREE_CODE (function) == COMPONENT_REF)
20973 thisarg = TREE_OPERAND (function, 0);
20974 if (TREE_CODE (thisarg) == INDIRECT_REF)
20975 thisarg = TREE_OPERAND (thisarg, 0);
20976 function = TREE_OPERAND (function, 1);
20977 if (TREE_CODE (function) == BASELINK)
20978 function = BASELINK_FUNCTIONS (function);
20980 /* We aren't going to do normal overload resolution, so force the
20981 template-id to resolve. */
20982 function = resolve_nondeduced_context (function, complain);
20983 for (unsigned i = 0; i < cargs; ++i)
20985 /* In a thunk, pass through args directly, without any
20986 conversions. */
20987 tree arg = (*call_args)[i];
20988 while (TREE_CODE (arg) != PARM_DECL)
20989 arg = TREE_OPERAND (arg, 0);
20990 (*call_args)[i] = arg;
20992 if (thisarg)
20994 /* If there are no other args, just push 'this'. */
20995 if (cargs == 0)
20996 vec_safe_push (call_args, thisarg);
20997 else
20999 /* Otherwise, shift the other args over to make room. */
21000 tree last = (*call_args)[cargs - 1];
21001 vec_safe_push (call_args, last);
21002 for (int i = cargs - 1; i > 0; --i)
21003 (*call_args)[i] = (*call_args)[i - 1];
21004 (*call_args)[0] = thisarg;
21007 ret = build_call_a (function, call_args->length (),
21008 call_args->address ());
21009 /* The thunk location is not interesting. */
21010 SET_EXPR_LOCATION (ret, UNKNOWN_LOCATION);
21011 CALL_FROM_THUNK_P (ret) = true;
21012 if (CLASS_TYPE_P (TREE_TYPE (ret)))
21013 CALL_EXPR_RETURN_SLOT_OPT (ret) = true;
21015 RETURN (ret);
21018 /* We do not perform argument-dependent lookup if normal
21019 lookup finds a non-function, in accordance with the
21020 resolution of DR 218. */
21021 if (koenig_p
21022 && ((is_overloaded_fn (function)
21023 /* If lookup found a member function, the Koenig lookup is
21024 not appropriate, even if an unqualified-name was used
21025 to denote the function. */
21026 && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
21027 || identifier_p (function)
21028 /* C++20 P0846: Lookup found nothing. */
21029 || (TREE_CODE (function) == TEMPLATE_ID_EXPR
21030 && identifier_p (TREE_OPERAND (function, 0))))
21031 /* Only do this when substitution turns a dependent call
21032 into a non-dependent call. */
21033 && type_dependent_expression_p_push (t)
21034 && !any_type_dependent_arguments_p (call_args))
21035 function = perform_koenig_lookup (function, call_args, tf_none);
21037 if (function != NULL_TREE
21038 && (identifier_p (function)
21039 || (TREE_CODE (function) == TEMPLATE_ID_EXPR
21040 && identifier_p (TREE_OPERAND (function, 0))
21041 && !any_dependent_template_arguments_p (TREE_OPERAND
21042 (function, 1))))
21043 && !any_type_dependent_arguments_p (call_args))
21045 bool template_id_p = (TREE_CODE (function) == TEMPLATE_ID_EXPR);
21046 if (template_id_p)
21047 function = TREE_OPERAND (function, 0);
21048 if (koenig_p && (complain & tf_warning_or_error))
21050 /* For backwards compatibility and good diagnostics, try
21051 the unqualified lookup again if we aren't in SFINAE
21052 context. */
21053 tree unq = tsubst_expr (function, args, complain, in_decl);
21054 if (unq == error_mark_node)
21055 RETURN (error_mark_node);
21057 if (unq != function)
21059 auto_diagnostic_group d;
21060 char const *const msg
21061 = G_("%qD was not declared in this scope, "
21062 "and no declarations were found by "
21063 "argument-dependent lookup at the point "
21064 "of instantiation");
21066 bool in_lambda = (current_class_type
21067 && LAMBDA_TYPE_P (current_class_type));
21068 /* In a lambda fn, we have to be careful to not
21069 introduce new this captures. Legacy code can't
21070 be using lambdas anyway, so it's ok to be
21071 stricter. Be strict with C++20 template-id ADL too.
21072 And be strict if we're already failing anyway. */
21073 bool strict = in_lambda || template_id_p || seen_error ();
21074 bool diag = true;
21075 if (strict)
21076 error_at (cp_expr_loc_or_input_loc (t),
21077 msg, function);
21078 else
21079 diag = permerror (cp_expr_loc_or_input_loc (t),
21080 msg, function);
21081 if (diag)
21083 tree fn = unq;
21085 if (INDIRECT_REF_P (fn))
21086 fn = TREE_OPERAND (fn, 0);
21087 if (is_overloaded_fn (fn))
21088 fn = get_first_fn (fn);
21090 if (!DECL_P (fn))
21091 /* Can't say anything more. */;
21092 else if (DECL_CLASS_SCOPE_P (fn))
21094 location_t loc = cp_expr_loc_or_input_loc (t);
21095 inform (loc,
21096 "declarations in dependent base %qT are "
21097 "not found by unqualified lookup",
21098 DECL_CLASS_CONTEXT (fn));
21099 if (current_class_ptr)
21100 inform (loc,
21101 "use %<this->%D%> instead", function);
21102 else
21103 inform (loc,
21104 "use %<%T::%D%> instead",
21105 current_class_name, function);
21107 else
21108 inform (DECL_SOURCE_LOCATION (fn),
21109 "%qD declared here, later in the "
21110 "translation unit", fn);
21111 if (strict)
21112 RETURN (error_mark_node);
21115 function = unq;
21118 if (identifier_p (function))
21120 if (complain & tf_error)
21121 unqualified_name_lookup_error (function);
21122 RETURN (error_mark_node);
21126 /* Remember that there was a reference to this entity. */
21127 if (function != NULL_TREE
21128 && DECL_P (function)
21129 && !mark_used (function, complain) && !(complain & tf_error))
21130 RETURN (error_mark_node);
21132 if (!maybe_fold_fn_template_args (function, complain))
21133 return error_mark_node;
21135 /* Put back tf_decltype for the actual call. */
21136 complain |= decltype_flag;
21138 if (function == NULL_TREE)
21139 switch (CALL_EXPR_IFN (t))
21141 case IFN_LAUNDER:
21142 gcc_assert (nargs == 1);
21143 if (vec_safe_length (call_args) != 1)
21145 error_at (cp_expr_loc_or_input_loc (t),
21146 "wrong number of arguments to "
21147 "%<__builtin_launder%>");
21148 ret = error_mark_node;
21150 else
21151 ret = finish_builtin_launder (cp_expr_loc_or_input_loc (t),
21152 (*call_args)[0], complain);
21153 break;
21155 case IFN_VEC_CONVERT:
21156 gcc_assert (nargs == 1);
21157 if (vec_safe_length (call_args) != 1)
21159 error_at (cp_expr_loc_or_input_loc (t),
21160 "wrong number of arguments to "
21161 "%<__builtin_convertvector%>");
21162 ret = error_mark_node;
21163 break;
21165 ret = cp_build_vec_convert ((*call_args)[0], input_location,
21166 tsubst (TREE_TYPE (t), args,
21167 complain, in_decl),
21168 complain);
21169 if (TREE_CODE (ret) == VIEW_CONVERT_EXPR)
21170 RETURN (ret);
21171 break;
21173 case IFN_SHUFFLEVECTOR:
21175 ret = build_x_shufflevector (input_location, call_args,
21176 complain);
21177 if (ret != error_mark_node)
21178 RETURN (ret);
21179 break;
21182 case IFN_ASSUME:
21183 gcc_assert (nargs == 1);
21184 if (vec_safe_length (call_args) != 1)
21186 error_at (cp_expr_loc_or_input_loc (t),
21187 "wrong number of arguments to "
21188 "%<assume%> attribute");
21189 ret = error_mark_node;
21191 else
21193 tree &arg = (*call_args)[0];
21194 if (!type_dependent_expression_p (arg))
21195 arg = contextual_conv_bool (arg, tf_warning_or_error);
21196 if (error_operand_p (arg))
21198 ret = error_mark_node;
21199 break;
21201 ret = build_assume_call (EXPR_LOCATION (t), arg);
21202 RETURN (ret);
21204 break;
21206 default:
21207 /* Unsupported internal function with arguments. */
21208 gcc_unreachable ();
21210 else if (TREE_CODE (function) == OFFSET_REF
21211 || TREE_CODE (function) == DOTSTAR_EXPR
21212 || TREE_CODE (function) == MEMBER_REF)
21213 ret = build_offset_ref_call_from_tree (function, &call_args,
21214 complain);
21215 else if (concept_check_p (function))
21216 /* Calls to concepts should have been previously diagnosed. */
21217 gcc_assert (false);
21218 else
21219 ret = finish_call_expr (function, &call_args,
21220 /*disallow_virtual=*/qualified_p,
21221 koenig_p,
21222 complain);
21224 if (ret != error_mark_node)
21226 bool op = CALL_EXPR_OPERATOR_SYNTAX (t);
21227 bool ord = CALL_EXPR_ORDERED_ARGS (t);
21228 bool rev = CALL_EXPR_REVERSE_ARGS (t);
21229 bool mtc = false;
21230 if (TREE_CODE (t) == CALL_EXPR)
21231 mtc = CALL_EXPR_MUST_TAIL_CALL (t);
21232 if (op || ord || rev || mtc)
21233 if (tree call = extract_call_expr (ret))
21235 CALL_EXPR_OPERATOR_SYNTAX (call) = op;
21236 CALL_EXPR_ORDERED_ARGS (call) = ord;
21237 CALL_EXPR_REVERSE_ARGS (call) = rev;
21238 if (TREE_CODE (call) == CALL_EXPR)
21239 CALL_EXPR_MUST_TAIL_CALL (call) = mtc;
21240 else if (TREE_CODE (call) == AGGR_INIT_EXPR)
21241 AGGR_INIT_EXPR_MUST_TAIL (call) = mtc;
21243 if (warning_suppressed_p (t, OPT_Wpessimizing_move))
21244 /* This also suppresses -Wredundant-move. */
21245 suppress_warning (ret, OPT_Wpessimizing_move);
21248 RETURN (ret);
21251 case COND_EXPR:
21253 tree cond = RECUR (TREE_OPERAND (t, 0));
21254 cond = mark_rvalue_use (cond);
21255 tree folded_cond = fold_non_dependent_expr (cond, complain);
21256 tree exp1, exp2;
21258 if (TREE_CODE (folded_cond) == INTEGER_CST)
21260 if (integer_zerop (folded_cond))
21262 ++c_inhibit_evaluation_warnings;
21263 exp1 = RECUR (TREE_OPERAND (t, 1));
21264 --c_inhibit_evaluation_warnings;
21265 exp2 = RECUR (TREE_OPERAND (t, 2));
21267 else
21269 exp1 = RECUR (TREE_OPERAND (t, 1));
21270 ++c_inhibit_evaluation_warnings;
21271 exp2 = RECUR (TREE_OPERAND (t, 2));
21272 --c_inhibit_evaluation_warnings;
21274 cond = folded_cond;
21276 else
21278 exp1 = RECUR (TREE_OPERAND (t, 1));
21279 exp2 = RECUR (TREE_OPERAND (t, 2));
21282 warning_sentinel s(warn_duplicated_branches);
21283 RETURN (build_x_conditional_expr (EXPR_LOCATION (t),
21284 cond, exp1, exp2, complain));
21287 case PSEUDO_DTOR_EXPR:
21289 tree op0 = RECUR (TREE_OPERAND (t, 0));
21290 tree op1 = RECUR (TREE_OPERAND (t, 1));
21291 tree op2 = tsubst (TREE_OPERAND (t, 2), args, complain, in_decl);
21292 RETURN (finish_pseudo_destructor_expr (op0, op1, op2,
21293 input_location));
21296 case TREE_LIST:
21297 RETURN (tsubst_tree_list (t, args, complain, in_decl));
21299 case COMPONENT_REF:
21301 tree object;
21302 tree object_type;
21303 tree member;
21304 tree r;
21306 object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
21307 args, complain, in_decl);
21308 /* Remember that there was a reference to this entity. */
21309 if (DECL_P (object)
21310 && !mark_used (object, complain) && !(complain & tf_error))
21311 RETURN (error_mark_node);
21312 object_type = TREE_TYPE (object);
21314 member = TREE_OPERAND (t, 1);
21315 if (BASELINK_P (member))
21316 member = tsubst_baselink (member,
21317 non_reference (TREE_TYPE (object)),
21318 args, complain, in_decl);
21319 else
21320 member = tsubst_name (member, args, complain, in_decl);
21321 if (member == error_mark_node)
21322 RETURN (error_mark_node);
21324 if (object_type && TYPE_PTRMEMFUNC_P (object_type)
21325 && TREE_CODE (member) == FIELD_DECL)
21327 r = build_ptrmemfunc_access_expr (object, DECL_NAME (member));
21328 RETURN (r);
21330 else if (TREE_CODE (member) == FIELD_DECL)
21332 r = finish_non_static_data_member (member, object, NULL_TREE,
21333 complain);
21334 if (TREE_CODE (r) == COMPONENT_REF)
21335 REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
21336 RETURN (r);
21338 else if (type_dependent_expression_p (object))
21339 /* We can't do much here. */;
21340 else if (!CLASS_TYPE_P (object_type))
21342 if (scalarish_type_p (object_type))
21344 tree s = NULL_TREE;
21345 tree dtor = member;
21347 if (TREE_CODE (dtor) == SCOPE_REF)
21349 s = TREE_OPERAND (dtor, 0);
21350 dtor = TREE_OPERAND (dtor, 1);
21352 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
21354 dtor = TREE_OPERAND (dtor, 0);
21355 if (TYPE_P (dtor))
21356 RETURN (finish_pseudo_destructor_expr
21357 (object, s, dtor, input_location));
21361 else if (TREE_CODE (member) == SCOPE_REF
21362 && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
21364 /* Lookup the template functions now that we know what the
21365 scope is. */
21366 tree scope = TREE_OPERAND (member, 0);
21367 tree tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
21368 tree args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
21369 member = lookup_qualified_name (scope, tmpl, LOOK_want::NORMAL,
21370 /*complain=*/false);
21371 if (BASELINK_P (member))
21373 BASELINK_FUNCTIONS (member)
21374 = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
21375 args);
21376 member = (adjust_result_of_qualified_name_lookup
21377 (member, BINFO_TYPE (BASELINK_BINFO (member)),
21378 object_type));
21380 else
21382 qualified_name_lookup_error (scope, tmpl, member,
21383 input_location);
21384 RETURN (error_mark_node);
21387 else if (TREE_CODE (member) == SCOPE_REF
21388 && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
21389 && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
21391 if (complain & tf_error)
21393 if (TYPE_P (TREE_OPERAND (member, 0)))
21394 error ("%qT is not a class or namespace",
21395 TREE_OPERAND (member, 0));
21396 else
21397 error ("%qD is not a class or namespace",
21398 TREE_OPERAND (member, 0));
21400 RETURN (error_mark_node);
21403 r = finish_class_member_access_expr (object, member,
21404 /*template_p=*/false,
21405 complain);
21406 if (REF_PARENTHESIZED_P (t))
21407 r = force_paren_expr (r);
21408 RETURN (r);
21411 case THROW_EXPR:
21412 RETURN (build_throw
21413 (input_location, RECUR (TREE_OPERAND (t, 0)), complain));
21415 case CONSTRUCTOR:
21417 vec<constructor_elt, va_gc> *n;
21418 constructor_elt *ce;
21419 unsigned HOST_WIDE_INT idx;
21420 bool process_index_p;
21421 int newlen;
21422 bool need_copy_p = false;
21423 tree r;
21425 tsubst_flags_t tcomplain = complain;
21426 if (COMPOUND_LITERAL_P (t))
21427 tcomplain |= tf_tst_ok;
21428 tree type = tsubst (TREE_TYPE (t), args, tcomplain, in_decl);
21429 if (type == error_mark_node)
21430 RETURN (error_mark_node);
21432 /* We do not want to process the index of aggregate
21433 initializers as they are identifier nodes which will be
21434 looked up by digest_init. */
21435 process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
21437 if (null_member_pointer_value_p (t))
21439 gcc_assert (same_type_p (type, TREE_TYPE (t)));
21440 RETURN (t);
21443 n = vec_safe_copy (CONSTRUCTOR_ELTS (t));
21444 newlen = vec_safe_length (n);
21445 FOR_EACH_VEC_SAFE_ELT (n, idx, ce)
21447 if (ce->index && process_index_p
21448 /* An identifier index is looked up in the type
21449 being initialized, not the current scope. */
21450 && TREE_CODE (ce->index) != IDENTIFIER_NODE)
21451 ce->index = RECUR (ce->index);
21453 if (PACK_EXPANSION_P (ce->value))
21455 /* Substitute into the pack expansion. */
21456 ce->value = tsubst_pack_expansion (ce->value, args, complain,
21457 in_decl);
21459 if (ce->value == error_mark_node
21460 || PACK_EXPANSION_P (ce->value))
21462 else if (TREE_VEC_LENGTH (ce->value) == 1)
21463 /* Just move the argument into place. */
21464 ce->value = TREE_VEC_ELT (ce->value, 0);
21465 else
21467 /* Update the length of the final CONSTRUCTOR
21468 arguments vector, and note that we will need to
21469 copy.*/
21470 newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
21471 need_copy_p = true;
21474 else
21475 ce->value = RECUR (ce->value);
21478 if (need_copy_p)
21480 vec<constructor_elt, va_gc> *old_n = n;
21482 vec_alloc (n, newlen);
21483 FOR_EACH_VEC_ELT (*old_n, idx, ce)
21485 if (TREE_CODE (ce->value) == TREE_VEC)
21487 int i, len = TREE_VEC_LENGTH (ce->value);
21488 for (i = 0; i < len; ++i)
21489 CONSTRUCTOR_APPEND_ELT (n, 0,
21490 TREE_VEC_ELT (ce->value, i));
21492 else
21493 CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
21497 r = build_constructor (init_list_type_node, n);
21498 CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
21499 CONSTRUCTOR_IS_DESIGNATED_INIT (r)
21500 = CONSTRUCTOR_IS_DESIGNATED_INIT (t);
21502 if (TREE_HAS_CONSTRUCTOR (t))
21504 fcl_t cl = fcl_functional;
21505 if (CONSTRUCTOR_C99_COMPOUND_LITERAL (t))
21506 cl = fcl_c99;
21507 RETURN (finish_compound_literal (type, r, complain, cl));
21510 TREE_TYPE (r) = type;
21511 RETURN (r);
21514 case TYPEID_EXPR:
21516 tree operand_0 = TREE_OPERAND (t, 0);
21517 if (TYPE_P (operand_0))
21519 operand_0 = tsubst (operand_0, args, complain, in_decl);
21520 RETURN (get_typeid (operand_0, complain));
21522 else
21524 operand_0 = RECUR (operand_0);
21525 RETURN (build_typeid (operand_0, complain));
21529 case FUNCTION_DECL:
21530 case PARM_DECL:
21531 case VAR_DECL:
21532 if (!args)
21533 RETURN (t);
21534 tree r;
21535 if (VAR_OR_FUNCTION_DECL_P (t)
21536 && DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
21537 r = tsubst_decl (t, args, complain);
21538 else if (VAR_OR_FUNCTION_DECL_P (t) && DECL_LOCAL_DECL_P (t))
21540 /* Local specialization will usually have been created when
21541 we instantiated the DECL_EXPR_DECL. */
21542 r = retrieve_local_specialization (t);
21543 if (!r)
21545 /* We're in a generic lambda referencing a local extern
21546 from an outer block-scope of a non-template. */
21547 gcc_checking_assert (LAMBDA_FUNCTION_P (current_function_decl));
21548 r = t;
21551 else if (local_variable_p (t)
21552 && ((r = retrieve_local_specialization (t))
21553 || TREE_CODE (t) == PARM_DECL
21554 || uses_template_parms (DECL_CONTEXT (t))))
21556 if (r == NULL_TREE && TREE_CODE (t) == PARM_DECL)
21558 /* We get here for a use of 'this' in an NSDMI. */
21559 if (DECL_NAME (t) == this_identifier && current_class_ptr)
21560 RETURN (current_class_ptr);
21562 /* This can happen for a parameter name used later in a function
21563 declaration (such as in a late-specified return type). Just
21564 make a dummy decl, since it's only used for its type. */
21565 gcc_assert (cp_unevaluated_operand);
21566 r = tsubst_decl (t, args, complain);
21567 /* Give it the template pattern as its context; its true context
21568 hasn't been instantiated yet and this is good enough for
21569 mangling. */
21570 DECL_CONTEXT (r) = DECL_CONTEXT (t);
21572 else if (r == NULL_TREE)
21574 /* First try name lookup to find the instantiation. */
21575 r = lookup_name (DECL_NAME (t));
21576 if (r)
21578 if (!VAR_P (r))
21580 /* During error-recovery we may find a non-variable,
21581 even an OVERLOAD: just bail out and avoid ICEs and
21582 duplicate diagnostics (c++/62207). */
21583 gcc_assert (seen_error ());
21584 RETURN (error_mark_node);
21586 if (!is_capture_proxy (r))
21588 /* Make sure the one we found is the one we want. */
21589 tree ctx = enclosing_instantiation_of (DECL_CONTEXT (t));
21590 if (ctx != DECL_CONTEXT (r))
21591 r = NULL_TREE;
21595 if (r)
21596 /* OK */;
21597 else
21599 /* This can happen for a variable used in a
21600 late-specified return type of a local lambda, or for a
21601 local static or constant. Building a new VAR_DECL
21602 should be OK in all those cases. */
21603 r = tsubst_decl (t, args, complain);
21604 if (local_specializations)
21605 /* Avoid infinite recursion (79640). */
21606 register_local_specialization (r, t);
21607 if (decl_maybe_constant_var_p (r))
21609 /* We can't call cp_finish_decl, so handle the
21610 initializer by hand. */
21611 tree init = tsubst_init (DECL_INITIAL (t), r, args,
21612 complain, in_decl);
21613 if (!processing_template_decl)
21614 init = maybe_constant_init (init);
21615 if (processing_template_decl
21616 ? potential_constant_expression (init)
21617 : reduced_constant_expression_p (init))
21618 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
21619 = TREE_CONSTANT (r) = true;
21620 DECL_INITIAL (r) = init;
21621 if (tree auto_node = type_uses_auto (TREE_TYPE (r)))
21622 TREE_TYPE (r)
21623 = do_auto_deduction (TREE_TYPE (r), init, auto_node,
21624 complain, adc_variable_type);
21626 gcc_assert (cp_unevaluated_operand
21627 || processing_contract_condition
21628 || TREE_STATIC (r)
21629 || decl_constant_var_p (r)
21630 || seen_error ());
21631 if (!processing_template_decl
21632 && !TREE_STATIC (r))
21633 r = process_outer_var_ref (r, complain);
21635 /* Remember this for subsequent uses. */
21636 if (local_specializations)
21637 register_local_specialization (r, t);
21639 if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
21640 r = argument_pack_select_arg (r);
21642 else
21643 r = t;
21644 if (!mark_used (r, complain))
21645 RETURN (error_mark_node);
21647 if (!no_name_lookup_flag
21648 && (TREE_CODE (t) == PARM_DECL || TREE_CODE (t) == VAR_DECL))
21650 /* ??? We're doing a subset of finish_id_expression here. */
21651 if (tree wrap = maybe_get_tls_wrapper_call (r))
21652 /* Replace an evaluated use of the thread_local variable with
21653 a call to its wrapper. */
21654 r = wrap;
21655 else if (outer_automatic_var_p (r))
21656 r = process_outer_var_ref (r, complain);
21658 if (!TYPE_REF_P (TREE_TYPE (t)))
21659 /* If the original type was a reference, we'll be wrapped in
21660 the appropriate INDIRECT_REF. */
21661 r = convert_from_reference (r);
21663 RETURN (r);
21665 case CONST_DECL:
21667 tree enum_type;
21668 tree v;
21670 if (DECL_TEMPLATE_PARM_P (t))
21671 RETURN (RECUR (DECL_INITIAL (t)));
21672 if (!args || !uses_template_parms (DECL_CONTEXT (t)))
21673 RETURN (t);
21675 /* Unfortunately, we cannot just call lookup_name here.
21676 Consider:
21678 template <int I> int f() {
21679 enum E { a = I };
21680 struct S { void g() { E e = a; } };
21683 When we instantiate f<7>::S::g(), say, lookup_name is not
21684 clever enough to find f<7>::a. */
21685 enum_type = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
21687 for (v = TYPE_VALUES (enum_type);
21688 v != NULL_TREE;
21689 v = TREE_CHAIN (v))
21690 if (TREE_PURPOSE (v) == DECL_NAME (t))
21691 RETURN (TREE_VALUE (v));
21693 /* We didn't find the name. That should never happen; if
21694 name-lookup found it during preliminary parsing, we
21695 should find it again here during instantiation. */
21696 gcc_unreachable ();
21697 RETURN (t);
21700 case FIELD_DECL:
21701 if (DECL_CONTEXT (t))
21703 tree ctx;
21705 ctx = tsubst_entering_scope (DECL_CONTEXT (t), args,
21706 complain, in_decl);
21707 if (ctx != DECL_CONTEXT (t))
21709 tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
21710 if (!r)
21712 if (complain & tf_error)
21713 error ("using invalid field %qD", t);
21714 RETURN (error_mark_node);
21716 RETURN (r);
21719 RETURN (t);
21721 case NAMESPACE_DECL:
21722 case OVERLOAD:
21723 RETURN (t);
21725 case TEMPLATE_DECL:
21726 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
21727 RETURN (tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
21728 args, complain, in_decl));
21729 else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
21730 RETURN (tsubst (t, args, complain, in_decl));
21731 else if (DECL_CLASS_SCOPE_P (t)
21732 && uses_template_parms (DECL_CONTEXT (t)))
21734 /* Template template argument like the following example need
21735 special treatment:
21737 template <template <class> class TT> struct C {};
21738 template <class T> struct D {
21739 template <class U> struct E {};
21740 C<E> c; // #1
21742 D<int> d; // #2
21744 We are processing the template argument `E' in #1 for
21745 the template instantiation #2. Originally, `E' is a
21746 TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT. Now we
21747 have to substitute this with one having context `D<int>'. */
21749 tree context = tsubst_entering_scope (DECL_CONTEXT (t), args,
21750 complain, in_decl);
21751 RETURN (lookup_field (context, DECL_NAME(t), 0, false));
21753 else
21754 /* Ordinary template template argument. */
21755 RETURN (t);
21757 case TEMPLATE_PARM_INDEX:
21758 case TYPE_DECL:
21759 RETURN (tsubst (t, args, complain, in_decl));
21761 case CLEANUP_POINT_EXPR:
21762 /* We shouldn't have built any of these during initial template
21763 generation. Instead, they should be built during instantiation
21764 in response to the saved STMT_IS_FULL_EXPR_P setting. */
21765 gcc_unreachable ();
21767 case OFFSET_REF:
21769 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
21770 tree op0 = RECUR (TREE_OPERAND (t, 0));
21771 tree op1 = RECUR (TREE_OPERAND (t, 1));
21772 r = build2 (OFFSET_REF, type, op0, op1);
21773 PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
21774 if (!mark_used (TREE_OPERAND (r, 1), complain)
21775 && !(complain & tf_error))
21776 RETURN (error_mark_node);
21777 RETURN (r);
21780 case EXPR_PACK_EXPANSION:
21781 error ("invalid use of pack expansion expression");
21782 RETURN (error_mark_node);
21784 case NONTYPE_ARGUMENT_PACK:
21785 error ("use %<...%> to expand argument pack");
21786 RETURN (error_mark_node);
21788 case VOID_CST:
21789 gcc_checking_assert (t == void_node && VOID_TYPE_P (TREE_TYPE (t)));
21790 RETURN (t);
21792 case INTEGER_CST:
21793 case REAL_CST:
21794 case COMPLEX_CST:
21795 case VECTOR_CST:
21797 /* Instantiate any typedefs in the type. */
21798 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
21799 r = fold_convert (type, t);
21800 gcc_assert (TREE_CODE (r) == TREE_CODE (t));
21801 RETURN (r);
21804 case STRING_CST:
21806 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
21807 r = t;
21808 if (type != TREE_TYPE (t))
21810 r = copy_node (t);
21811 TREE_TYPE (r) = type;
21813 RETURN (r);
21816 case PTRMEM_CST:
21817 /* These can sometimes show up in a partial instantiation, but never
21818 involve template parms. */
21819 gcc_assert (!uses_template_parms (t));
21820 RETURN (t);
21822 case UNARY_LEFT_FOLD_EXPR:
21823 RETURN (tsubst_unary_left_fold (t, args, complain, in_decl));
21824 case UNARY_RIGHT_FOLD_EXPR:
21825 RETURN (tsubst_unary_right_fold (t, args, complain, in_decl));
21826 case BINARY_LEFT_FOLD_EXPR:
21827 RETURN (tsubst_binary_left_fold (t, args, complain, in_decl));
21828 case BINARY_RIGHT_FOLD_EXPR:
21829 RETURN (tsubst_binary_right_fold (t, args, complain, in_decl));
21830 case PREDICT_EXPR:
21831 RETURN (t);
21833 case DEBUG_BEGIN_STMT:
21834 /* ??? There's no point in copying it for now, but maybe some
21835 day it will contain more information, such as a pointer back
21836 to the containing function, inlined copy or so. */
21837 RETURN (t);
21839 case CO_YIELD_EXPR:
21840 RETURN (finish_co_yield_expr (input_location,
21841 RECUR (TREE_OPERAND (t, 0))));
21843 case CO_AWAIT_EXPR:
21844 RETURN (finish_co_await_expr (input_location,
21845 RECUR (TREE_OPERAND (t, 0))));
21847 case VA_ARG_EXPR:
21849 tree op0 = RECUR (TREE_OPERAND (t, 0));
21850 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
21851 RETURN (build_x_va_arg (EXPR_LOCATION (t), op0, type));
21854 case OFFSETOF_EXPR:
21856 tree object_ptr
21857 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl);
21858 RETURN (finish_offsetof (object_ptr,
21859 RECUR (TREE_OPERAND (t, 0)),
21860 EXPR_LOCATION (t)));
21863 case ADDRESSOF_EXPR:
21864 RETURN (cp_build_addressof (EXPR_LOCATION (t),
21865 RECUR (TREE_OPERAND (t, 0)), complain));
21867 case TRAIT_EXPR:
21869 tree type1 = TRAIT_EXPR_TYPE1 (t);
21870 if (TYPE_P (type1))
21871 type1 = tsubst (type1, args, complain, in_decl);
21872 else
21873 type1 = tsubst_expr (type1, args, complain, in_decl);
21874 tree type2 = tsubst (TRAIT_EXPR_TYPE2 (t), args,
21875 complain, in_decl);
21876 RETURN (finish_trait_expr (TRAIT_EXPR_LOCATION (t),
21877 TRAIT_EXPR_KIND (t), type1, type2));
21880 case STMT_EXPR:
21882 tree old_stmt_expr = cur_stmt_expr;
21883 tree stmt_expr = begin_stmt_expr ();
21885 cur_stmt_expr = stmt_expr;
21886 tsubst_stmt (STMT_EXPR_STMT (t), args, complain, in_decl);
21887 stmt_expr = finish_stmt_expr (stmt_expr, false);
21888 cur_stmt_expr = old_stmt_expr;
21890 /* If the resulting list of expression statement is empty,
21891 fold it further into void_node. */
21892 if (empty_expr_stmt_p (stmt_expr))
21893 stmt_expr = void_node;
21895 RETURN (stmt_expr);
21898 case LAMBDA_EXPR:
21900 tree r = tsubst_lambda_expr (t, args, complain, in_decl);
21902 RETURN (build_lambda_object (r));
21905 case TRANSACTION_EXPR:
21906 gcc_checking_assert (!TRANSACTION_EXPR_IS_STMT (t));
21907 RETURN (tsubst_stmt (t, args, complain, in_decl));
21909 case PAREN_EXPR:
21910 if (REF_PARENTHESIZED_P (t))
21911 RETURN (finish_parenthesized_expr (RECUR (TREE_OPERAND (t, 0))));
21912 else
21913 /* Recreate the PAREN_EXPR from __builtin_assoc_barrier. */
21915 tree op0 = RECUR (TREE_OPERAND (t, 0));
21916 RETURN (build1_loc (input_location, PAREN_EXPR,
21917 TREE_TYPE (op0), op0));
21920 case VEC_PERM_EXPR:
21922 tree op0 = RECUR (TREE_OPERAND (t, 0));
21923 tree op1 = RECUR (TREE_OPERAND (t, 1));
21924 tree op2 = RECUR (TREE_OPERAND (t, 2));
21925 RETURN (build_x_vec_perm_expr (input_location, op0, op1, op2,
21926 complain));
21929 case REQUIRES_EXPR:
21931 complain &= ~tf_warning_or_error;
21932 tree r = tsubst_requires_expr (t, args, complain, in_decl);
21933 RETURN (r);
21936 case RANGE_EXPR:
21937 /* No need to substitute further, a RANGE_EXPR will always be built
21938 with constant operands. */
21939 RETURN (t);
21941 case NON_LVALUE_EXPR:
21942 case VIEW_CONVERT_EXPR:
21944 tree op = RECUR (TREE_OPERAND (t, 0));
21946 if (location_wrapper_p (t))
21947 /* We need to do this here as well as in tsubst_copy so we get the
21948 other tsubst_copy_and_build semantics for a PARM_DECL operand. */
21949 RETURN (maybe_wrap_with_location (op, EXPR_LOCATION (t)));
21951 gcc_checking_assert (TREE_CODE (t) == VIEW_CONVERT_EXPR);
21952 if (REF_PARENTHESIZED_P (t))
21953 /* force_paren_expr can also create a VIEW_CONVERT_EXPR. */
21954 RETURN (finish_parenthesized_expr (op));
21956 /* Otherwise, we're dealing with a wrapper to make a C++20 template
21957 parameter object const. */
21958 if (TREE_TYPE (op) == NULL_TREE
21959 || !CP_TYPE_CONST_P (TREE_TYPE (op)))
21961 /* The template argument is not const, presumably because
21962 it is still dependent, and so not the const template parm
21963 object. */
21964 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
21965 if (TREE_CODE (op) == CONSTRUCTOR
21966 || TREE_CODE (op) == IMPLICIT_CONV_EXPR)
21968 /* Don't add a wrapper to these. */
21969 op = copy_node (op);
21970 TREE_TYPE (op) = type;
21972 else
21973 /* Do add a wrapper otherwise (in particular, if op is
21974 another TEMPLATE_PARM_INDEX). */
21975 op = build1 (VIEW_CONVERT_EXPR, type, op);
21977 RETURN (op);
21980 default:
21981 /* Handle Objective-C++ constructs, if appropriate. */
21982 if (tree subst = objcp_tsubst_expr (t, args, complain, in_decl))
21983 RETURN (subst);
21985 /* We shouldn't get here, but keep going if !flag_checking. */
21986 if (flag_checking)
21987 gcc_unreachable ();
21988 RETURN (t);
21991 #undef RECUR
21992 #undef RETURN
21993 out:
21994 input_location = save_loc;
21995 return retval;
21998 /* Verify that the instantiated ARGS are valid. For type arguments,
21999 make sure that the type's linkage is ok. For non-type arguments,
22000 make sure they are constants if they are integral or enumerations.
22001 Emit an error under control of COMPLAIN, and return TRUE on error. */
22003 static bool
22004 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
22006 if (dependent_template_arg_p (t))
22007 return false;
22008 if (ARGUMENT_PACK_P (t))
22010 tree vec = ARGUMENT_PACK_ARGS (t);
22011 int len = TREE_VEC_LENGTH (vec);
22012 bool result = false;
22013 int i;
22015 for (i = 0; i < len; ++i)
22016 if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
22017 result = true;
22018 return result;
22020 else if (TYPE_P (t))
22022 /* [basic.link]: A name with no linkage (notably, the name
22023 of a class or enumeration declared in a local scope)
22024 shall not be used to declare an entity with linkage.
22025 This implies that names with no linkage cannot be used as
22026 template arguments
22028 DR 757 relaxes this restriction for C++0x. */
22029 tree nt = (cxx_dialect > cxx98 ? NULL_TREE
22030 : no_linkage_check (t, /*relaxed_p=*/false));
22032 if (nt)
22034 /* DR 488 makes use of a type with no linkage cause
22035 type deduction to fail. */
22036 if (complain & tf_error)
22038 if (TYPE_UNNAMED_P (nt))
22039 error ("%qT is/uses unnamed type", t);
22040 else
22041 error ("template argument for %qD uses local type %qT",
22042 tmpl, t);
22044 return true;
22046 /* In order to avoid all sorts of complications, we do not
22047 allow variably-modified types as template arguments. */
22048 else if (variably_modified_type_p (t, NULL_TREE))
22050 if (complain & tf_error)
22051 error ("%qT is a variably modified type", t);
22052 return true;
22055 /* Class template and alias template arguments should be OK. */
22056 else if (DECL_TYPE_TEMPLATE_P (t))
22058 /* A non-type argument of integral or enumerated type must be a
22059 constant. */
22060 else if (TREE_TYPE (t)
22061 && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
22062 && !REFERENCE_REF_P (t)
22063 && !TREE_CONSTANT (t))
22065 if (complain & tf_error)
22066 error ("integral expression %qE is not constant", t);
22067 return true;
22069 return false;
22072 static bool
22073 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
22075 int ix, len = DECL_NTPARMS (tmpl);
22076 bool result = false;
22078 for (ix = 0; ix != len; ix++)
22080 if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
22081 result = true;
22083 if (result && (complain & tf_error))
22084 error (" trying to instantiate %qD", tmpl);
22085 return result;
22088 /* Call mark_used on each entity within the non-type template arguments in
22089 ARGS for an instantiation of TMPL, to ensure that each such entity is
22090 considered odr-used (and therefore marked for instantiation) regardless of
22091 whether the specialization was first formed in a template context (which
22092 inhibits mark_used).
22094 This function assumes push_to_top_level has been called beforehand. */
22096 static void
22097 mark_template_arguments_used (tree tmpl, tree args)
22099 /* It suffices to do this only when instantiating a primary template. */
22100 if (TREE_CODE (tmpl) != TEMPLATE_DECL || !PRIMARY_TEMPLATE_P (tmpl))
22101 return;
22103 /* We already marked outer arguments when specializing the context. */
22104 args = INNERMOST_TEMPLATE_ARGS (args);
22106 for (tree arg : tree_vec_range (args))
22108 /* A (pointer/reference to) function or variable NTTP argument. */
22109 if (TREE_CODE (arg) == ADDR_EXPR
22110 || TREE_CODE (arg) == INDIRECT_REF)
22112 while (TREE_CODE (arg) == ADDR_EXPR
22113 || REFERENCE_REF_P (arg)
22114 || CONVERT_EXPR_P (arg))
22115 arg = TREE_OPERAND (arg, 0);
22116 if (VAR_OR_FUNCTION_DECL_P (arg))
22118 /* Pass tf_none to avoid duplicate diagnostics: if this call
22119 fails then an earlier call to mark_used for this argument
22120 must have also failed and emitted a diagnostic. */
22121 bool ok = mark_used (arg, tf_none);
22122 gcc_checking_assert (ok || seen_error ());
22125 /* A class NTTP argument. */
22126 else if (VAR_P (arg)
22127 && DECL_NTTP_OBJECT_P (arg))
22129 auto mark_used_r = [](tree *tp, int *, void *) {
22130 if (VAR_OR_FUNCTION_DECL_P (*tp))
22132 bool ok = mark_used (*tp, tf_none);
22133 gcc_checking_assert (ok || seen_error ());
22135 return NULL_TREE;
22137 cp_walk_tree_without_duplicates (&DECL_INITIAL (arg),
22138 mark_used_r, nullptr);
22143 /* We're out of SFINAE context now, so generate diagnostics for the access
22144 errors we saw earlier when instantiating D from TMPL and ARGS. */
22146 static void
22147 recheck_decl_substitution (tree d, tree tmpl, tree args)
22149 tree pattern = DECL_TEMPLATE_RESULT (tmpl);
22150 tree type = TREE_TYPE (pattern);
22151 location_t loc = input_location;
22153 push_access_scope (d);
22154 push_deferring_access_checks (dk_no_deferred);
22155 input_location = DECL_SOURCE_LOCATION (pattern);
22156 tsubst (type, args, tf_warning_or_error, d);
22157 input_location = loc;
22158 pop_deferring_access_checks ();
22159 pop_access_scope (d);
22162 /* Instantiate the indicated variable, function, or alias template TMPL with
22163 the template arguments in TARG_PTR. */
22165 tree
22166 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
22168 auto_timevar tv (TV_TEMPLATE_INST);
22170 tree targ_ptr = orig_args;
22171 tree fndecl;
22172 tree gen_tmpl;
22173 bool access_ok = true;
22175 if (tmpl == error_mark_node)
22176 return error_mark_node;
22178 /* The other flags are not relevant anymore here, especially tf_partial
22179 shouldn't be set. For instance, we may be called while doing a partial
22180 substitution of a template variable, but the type of the variable
22181 template may be auto, in which case we will call do_auto_deduction
22182 in mark_used (which clears tf_partial) and the auto must be properly
22183 reduced at that time for the deduction to work. */
22184 complain &= tf_warning_or_error;
22186 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
22188 if (modules_p ())
22189 lazy_load_pendings (tmpl);
22191 /* If this function is a clone, handle it specially. */
22192 if (DECL_CLONED_FUNCTION_P (tmpl))
22194 tree spec;
22195 tree clone;
22197 /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
22198 DECL_CLONED_FUNCTION. */
22199 spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
22200 targ_ptr, complain);
22201 if (spec == error_mark_node)
22202 return error_mark_node;
22204 /* Look for the clone. */
22205 FOR_EACH_CLONE (clone, spec)
22206 if (DECL_NAME (clone) == DECL_NAME (tmpl))
22207 return clone;
22208 /* We should always have found the clone by now. */
22209 gcc_unreachable ();
22210 return NULL_TREE;
22213 if (targ_ptr == error_mark_node)
22214 return error_mark_node;
22216 /* Check to see if we already have this specialization. */
22217 gen_tmpl = most_general_template (tmpl);
22218 if (TMPL_ARGS_DEPTH (targ_ptr)
22219 < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)))
22220 /* targ_ptr only has the innermost template args, so add the outer ones
22221 from tmpl, which could be either a partial instantiation or gen_tmpl (in
22222 the case of a non-dependent call within a template definition). */
22223 targ_ptr = (add_outermost_template_args
22224 (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (tmpl)),
22225 targ_ptr));
22227 hashval_t hash = spec_hasher::hash (gen_tmpl, targ_ptr);
22228 tree spec = retrieve_specialization (gen_tmpl, targ_ptr, hash);
22230 gcc_checking_assert (tmpl == gen_tmpl
22231 || ((fndecl
22232 = retrieve_specialization (tmpl, orig_args, 0))
22233 == spec)
22234 || fndecl == NULL_TREE);
22236 if (spec != NULL_TREE)
22238 if (FNDECL_HAS_ACCESS_ERRORS (spec))
22240 if (complain & tf_error)
22241 recheck_decl_substitution (spec, gen_tmpl, targ_ptr);
22242 return error_mark_node;
22244 return spec;
22247 if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
22248 complain))
22249 return error_mark_node;
22251 /* We are building a FUNCTION_DECL, during which the access of its
22252 parameters and return types have to be checked. However this
22253 FUNCTION_DECL which is the desired context for access checking
22254 is not built yet. We solve this chicken-and-egg problem by
22255 deferring all checks until we have the FUNCTION_DECL. */
22256 push_deferring_access_checks (dk_deferred);
22258 /* Instantiation of the function happens in the context of the function
22259 template, not the context of the overload resolution we're doing. */
22260 push_to_top_level ();
22261 /* If there are dependent arguments, e.g. because we're doing partial
22262 ordering, make sure processing_template_decl stays set. */
22263 if (uses_template_parms (targ_ptr))
22264 ++processing_template_decl;
22265 if (DECL_CLASS_SCOPE_P (gen_tmpl))
22267 tree ctx;
22268 if (!uses_template_parms (DECL_CONTEXT (tmpl)))
22269 /* If the context of the partially instantiated template is
22270 already non-dependent, then we might as well use it. */
22271 ctx = DECL_CONTEXT (tmpl);
22272 else
22273 ctx = tsubst_entering_scope (DECL_CONTEXT (gen_tmpl), targ_ptr,
22274 complain, gen_tmpl);
22275 push_nested_class (ctx);
22278 tree pattern = DECL_TEMPLATE_RESULT (gen_tmpl);
22280 tree partial_ti = NULL_TREE;
22281 fndecl = NULL_TREE;
22282 if (VAR_P (pattern))
22284 /* We need to determine if we're using a partial or explicit
22285 specialization now, because the type of the variable could be
22286 different. */
22287 tree tid = build2 (TEMPLATE_ID_EXPR, NULL_TREE, tmpl, targ_ptr);
22288 partial_ti = most_specialized_partial_spec (tid, complain);
22289 if (partial_ti == error_mark_node)
22290 pattern = error_mark_node;
22291 else if (partial_ti)
22293 tree partial_tmpl = TI_TEMPLATE (partial_ti);
22294 tree partial_args = TI_ARGS (partial_ti);
22295 tree partial_pat = DECL_TEMPLATE_RESULT (partial_tmpl);
22296 fndecl = tsubst_decl (partial_pat, partial_args, complain,
22297 /*use_spec_table=*/false);
22301 /* Substitute template parameters to obtain the specialization. */
22302 if (fndecl == NULL_TREE)
22303 fndecl = tsubst_decl (pattern, targ_ptr, complain, /*use_spec_table=*/false);
22304 if (DECL_CLASS_SCOPE_P (gen_tmpl))
22305 pop_nested_class ();
22306 pop_from_top_level ();
22308 if (fndecl == error_mark_node)
22310 pop_deferring_access_checks ();
22311 return error_mark_node;
22314 /* The DECL_TI_TEMPLATE should always be the immediate parent
22315 template, not the most general template. */
22316 DECL_TI_TEMPLATE (fndecl) = tmpl;
22317 DECL_TI_ARGS (fndecl) = targ_ptr;
22318 if (VAR_P (pattern))
22320 /* Now that we we've formed this variable template specialization,
22321 remember the result of most_specialized_partial_spec for it. */
22322 TI_PARTIAL_INFO (DECL_TEMPLATE_INFO (fndecl)) = partial_ti;
22324 /* And remember if the variable was declared with []. */
22325 if (TREE_CODE (TREE_TYPE (fndecl)) == ARRAY_TYPE
22326 && TYPE_DOMAIN (TREE_TYPE (fndecl)) == NULL_TREE)
22327 SET_VAR_HAD_UNKNOWN_BOUND (fndecl);
22330 fndecl = register_specialization (fndecl, gen_tmpl, targ_ptr, false, hash);
22331 if (fndecl == error_mark_node)
22332 return error_mark_node;
22334 set_instantiating_module (fndecl);
22336 /* Now we know the specialization, compute access previously
22337 deferred. Do no access control for inheriting constructors,
22338 as we already checked access for the inherited constructor. */
22339 if (!(flag_new_inheriting_ctors
22340 && DECL_INHERITED_CTOR (fndecl)))
22342 push_access_scope (fndecl);
22343 if (!perform_deferred_access_checks (complain))
22344 access_ok = false;
22345 pop_access_scope (fndecl);
22347 pop_deferring_access_checks ();
22349 /* If we've just instantiated the main entry point for a function,
22350 instantiate all the alternate entry points as well. We do this
22351 by cloning the instantiation of the main entry point, not by
22352 instantiating the template clones. */
22353 if (tree chain = DECL_CHAIN (gen_tmpl))
22354 if (DECL_P (chain) && DECL_CLONED_FUNCTION_P (chain))
22355 clone_cdtor (fndecl, /*update_methods=*/false);
22357 if (!access_ok)
22359 if (!(complain & tf_error))
22361 /* Remember to reinstantiate when we're out of SFINAE so the user
22362 can see the errors. */
22363 FNDECL_HAS_ACCESS_ERRORS (fndecl) = true;
22365 return error_mark_node;
22368 return fndecl;
22371 /* Instantiate the alias template TMPL with ARGS. Also push a template
22372 instantiation level, which instantiate_template doesn't do because
22373 functions and variables have sufficient context established by the
22374 callers. */
22376 static tree
22377 instantiate_alias_template (tree tmpl, tree args, tsubst_flags_t complain)
22379 if (tmpl == error_mark_node || args == error_mark_node)
22380 return error_mark_node;
22382 args = coerce_template_parms (DECL_TEMPLATE_PARMS (tmpl),
22383 args, tmpl, complain);
22384 if (args == error_mark_node)
22385 return error_mark_node;
22387 /* FIXME check for satisfaction in check_instantiated_args. */
22388 if (!constraints_satisfied_p (tmpl, args))
22390 if (complain & tf_error)
22392 auto_diagnostic_group d;
22393 error ("template constraint failure for %qD", tmpl);
22394 diagnose_constraints (input_location, tmpl, args);
22396 return error_mark_node;
22399 if (!push_tinst_level (tmpl, args))
22400 return error_mark_node;
22401 tree r = instantiate_template (tmpl, args, complain);
22402 pop_tinst_level ();
22404 if (tree d = dependent_alias_template_spec_p (TREE_TYPE (r), nt_opaque))
22406 /* Note this is also done at parse time from push_template_decl. */
22407 /* An alias template specialization can be dependent
22408 even if its underlying type is not. */
22409 TYPE_DEPENDENT_P (d) = true;
22410 TYPE_DEPENDENT_P_VALID (d) = true;
22411 /* Sometimes a dependent alias spec is equivalent to its expansion,
22412 sometimes not. So always use structural_comptypes. */
22413 SET_TYPE_STRUCTURAL_EQUALITY (d);
22416 return r;
22419 /* PARM is a template parameter pack for FN. Returns true iff
22420 PARM is used in a deducible way in the argument list of FN. */
22422 static bool
22423 pack_deducible_p (tree parm, tree fn)
22425 tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
22426 for (; t; t = TREE_CHAIN (t))
22428 tree type = TREE_VALUE (t);
22429 tree packs;
22430 if (!PACK_EXPANSION_P (type))
22431 continue;
22432 for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
22433 packs; packs = TREE_CHAIN (packs))
22434 if (template_args_equal (TREE_VALUE (packs), parm))
22436 /* The template parameter pack is used in a function parameter
22437 pack. If this is the end of the parameter list, the
22438 template parameter pack is deducible. */
22439 if (TREE_CHAIN (t) == void_list_node)
22440 return true;
22441 else
22442 /* Otherwise, not. Well, it could be deduced from
22443 a non-pack parameter, but doing so would end up with
22444 a deduction mismatch, so don't bother. */
22445 return false;
22448 /* The template parameter pack isn't used in any function parameter
22449 packs, but it might be used deeper, e.g. tuple<Args...>. */
22450 return true;
22453 /* Subroutine of fn_type_unification: check non-dependent parms for
22454 convertibility. */
22456 static int
22457 check_non_deducible_conversions (tree parms, const tree *args, unsigned nargs,
22458 tree fn, unification_kind_t strict, int flags,
22459 struct conversion **convs, bool explain_p,
22460 bool noninst_only_p)
22462 /* Non-constructor methods need to leave a conversion for 'this', which
22463 isn't included in nargs here. */
22464 unsigned offset = (DECL_IOBJ_MEMBER_FUNCTION_P (fn)
22465 && !DECL_CONSTRUCTOR_P (fn));
22467 for (unsigned ia = 0;
22468 parms && parms != void_list_node && ia < nargs; )
22470 tree parm = TREE_VALUE (parms);
22472 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
22473 && (!TREE_CHAIN (parms)
22474 || TREE_CHAIN (parms) == void_list_node))
22475 /* For a function parameter pack that occurs at the end of the
22476 parameter-declaration-list, the type A of each remaining
22477 argument of the call is compared with the type P of the
22478 declarator-id of the function parameter pack. */
22479 break;
22481 parms = TREE_CHAIN (parms);
22483 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
22484 /* For a function parameter pack that does not occur at the
22485 end of the parameter-declaration-list, the type of the
22486 parameter pack is a non-deduced context. */
22487 continue;
22489 if (!uses_template_parms (parm))
22491 tree arg = args[ia];
22492 conversion **conv_p = convs ? &convs[ia+offset] : NULL;
22493 int lflags = conv_flags (ia, nargs, fn, arg, flags);
22495 if (check_non_deducible_conversion (parm, arg, strict, lflags,
22496 conv_p, explain_p, noninst_only_p))
22497 return 1;
22500 ++ia;
22503 return 0;
22506 /* The FN is a TEMPLATE_DECL for a function. ARGS is an array with
22507 NARGS elements of the arguments that are being used when calling
22508 it. TARGS is a vector into which the deduced template arguments
22509 are placed.
22511 Returns either a FUNCTION_DECL for the matching specialization of FN or
22512 NULL_TREE if no suitable specialization can be found. If EXPLAIN_P is
22513 true, diagnostics will be printed to explain why it failed.
22515 If FN is a conversion operator, or we are trying to produce a specific
22516 specialization, RETURN_TYPE is the return type desired.
22518 The EXPLICIT_TARGS are explicit template arguments provided via a
22519 template-id.
22521 The parameter STRICT is one of:
22523 DEDUCE_CALL:
22524 We are deducing arguments for a function call, as in
22525 [temp.deduct.call]. If RETURN_TYPE is non-null, we are
22526 deducing arguments for a call to the result of a conversion
22527 function template, as in [over.call.object].
22529 DEDUCE_CONV:
22530 We are deducing arguments for a conversion function, as in
22531 [temp.deduct.conv].
22533 DEDUCE_EXACT:
22534 We are deducing arguments when doing an explicit instantiation
22535 as in [temp.explicit], when determining an explicit specialization
22536 as in [temp.expl.spec], or when taking the address of a function
22537 template, as in [temp.deduct.funcaddr]. */
22539 tree
22540 fn_type_unification (tree fn,
22541 tree explicit_targs,
22542 tree targs,
22543 const tree *args,
22544 unsigned int nargs,
22545 tree return_type,
22546 unification_kind_t strict,
22547 int flags,
22548 struct conversion **convs,
22549 bool explain_p,
22550 bool decltype_p)
22552 tree parms;
22553 tree fntype;
22554 tree decl = NULL_TREE;
22555 tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
22556 bool ok;
22557 static int deduction_depth;
22558 /* type_unification_real will pass back any access checks from default
22559 template argument substitution. */
22560 vec<deferred_access_check, va_gc> *checks = NULL;
22561 /* We don't have all the template args yet. */
22562 bool incomplete = true;
22564 tree orig_fn = fn;
22565 if (flag_new_inheriting_ctors)
22566 fn = strip_inheriting_ctors (fn);
22568 tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
22569 tree r = error_mark_node;
22571 tree full_targs = targs;
22572 if (TMPL_ARGS_DEPTH (targs)
22573 < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (fn)))
22574 full_targs = (add_outermost_template_args
22575 (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (fn)),
22576 targs));
22578 if (decltype_p)
22579 complain |= tf_decltype;
22581 /* In C++0x, it's possible to have a function template whose type depends
22582 on itself recursively. This is most obvious with decltype, but can also
22583 occur with enumeration scope (c++/48969). So we need to catch infinite
22584 recursion and reject the substitution at deduction time; this function
22585 will return error_mark_node for any repeated substitution.
22587 This also catches excessive recursion such as when f<N> depends on
22588 f<N-1> across all integers, and returns error_mark_node for all the
22589 substitutions back up to the initial one.
22591 This is, of course, not reentrant. */
22592 if (excessive_deduction_depth)
22593 return error_mark_node;
22594 ++deduction_depth;
22596 gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
22598 fntype = TREE_TYPE (fn);
22599 if (explicit_targs)
22601 /* [temp.deduct]
22603 The specified template arguments must match the template
22604 parameters in kind (i.e., type, nontype, template), and there
22605 must not be more arguments than there are parameters;
22606 otherwise type deduction fails.
22608 Nontype arguments must match the types of the corresponding
22609 nontype template parameters, or must be convertible to the
22610 types of the corresponding nontype parameters as specified in
22611 _temp.arg.nontype_, otherwise type deduction fails.
22613 All references in the function type of the function template
22614 to the corresponding template parameters are replaced by the
22615 specified template argument values. If a substitution in a
22616 template parameter or in the function type of the function
22617 template results in an invalid type, type deduction fails. */
22618 int i, len = TREE_VEC_LENGTH (tparms);
22619 location_t loc = input_location;
22620 incomplete = false;
22622 if (explicit_targs == error_mark_node)
22623 goto fail;
22625 if (TMPL_ARGS_DEPTH (explicit_targs)
22626 < TMPL_ARGS_DEPTH (full_targs))
22627 explicit_targs = add_outermost_template_args (full_targs,
22628 explicit_targs);
22630 /* Adjust any explicit template arguments before entering the
22631 substitution context. */
22632 explicit_targs
22633 = (coerce_template_parms (tparms, explicit_targs, fn,
22634 complain|tf_partial,
22635 /*require_all_args=*/false));
22636 if (explicit_targs == error_mark_node)
22637 goto fail;
22639 /* Substitute the explicit args into the function type. This is
22640 necessary so that, for instance, explicitly declared function
22641 arguments can match null pointed constants. If we were given
22642 an incomplete set of explicit args, we must not do semantic
22643 processing during substitution as we could create partial
22644 instantiations. */
22645 for (i = 0; i < len; i++)
22647 tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
22648 bool parameter_pack = false;
22649 tree targ = TREE_VEC_ELT (explicit_targs, i);
22651 /* Dig out the actual parm. */
22652 if (TREE_CODE (parm) == TYPE_DECL
22653 || TREE_CODE (parm) == TEMPLATE_DECL)
22655 parm = TREE_TYPE (parm);
22656 parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
22658 else if (TREE_CODE (parm) == PARM_DECL)
22660 parm = DECL_INITIAL (parm);
22661 parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
22664 if (targ == NULL_TREE)
22665 /* No explicit argument for this template parameter. */
22666 incomplete = true;
22667 else if (parameter_pack && pack_deducible_p (parm, fn))
22669 /* Mark the argument pack as "incomplete". We could
22670 still deduce more arguments during unification.
22671 We remove this mark in type_unification_real. */
22672 ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
22673 ARGUMENT_PACK_EXPLICIT_ARGS (targ)
22674 = ARGUMENT_PACK_ARGS (targ);
22676 /* We have some incomplete argument packs. */
22677 incomplete = true;
22681 if (incomplete)
22683 if (!push_tinst_level (fn, explicit_targs))
22685 excessive_deduction_depth = true;
22686 goto fail;
22688 ++processing_template_decl;
22689 input_location = DECL_SOURCE_LOCATION (fn);
22690 /* Ignore any access checks; we'll see them again in
22691 instantiate_template and they might have the wrong
22692 access path at this point. */
22693 push_deferring_access_checks (dk_deferred);
22694 tsubst_flags_t ecomplain = complain | tf_partial | tf_fndecl_type;
22695 fntype = tsubst (TREE_TYPE (fn), explicit_targs, ecomplain, NULL_TREE);
22696 pop_deferring_access_checks ();
22697 input_location = loc;
22698 --processing_template_decl;
22699 pop_tinst_level ();
22701 if (fntype == error_mark_node)
22702 goto fail;
22705 /* Place the explicitly specified arguments in TARGS. */
22706 explicit_targs = INNERMOST_TEMPLATE_ARGS (explicit_targs);
22707 for (i = NUM_TMPL_ARGS (explicit_targs); i--;)
22708 TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (explicit_targs, i);
22709 if (!incomplete && CHECKING_P
22710 && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
22711 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
22712 (targs, NUM_TMPL_ARGS (explicit_targs));
22715 if (return_type && strict != DEDUCE_CALL)
22717 tree *new_args = XALLOCAVEC (tree, nargs + 1);
22718 new_args[0] = return_type;
22719 memcpy (new_args + 1, args, nargs * sizeof (tree));
22720 args = new_args;
22721 ++nargs;
22724 if (!incomplete)
22725 goto deduced;
22727 /* Never do unification on the 'this' parameter. */
22728 parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
22730 if (return_type && strict == DEDUCE_CALL)
22732 /* We're deducing for a call to the result of a template conversion
22733 function. The parms we really want are in return_type. */
22734 if (INDIRECT_TYPE_P (return_type))
22735 return_type = TREE_TYPE (return_type);
22736 parms = TYPE_ARG_TYPES (return_type);
22738 else if (return_type)
22740 parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
22743 /* We allow incomplete unification without an error message here
22744 because the standard doesn't seem to explicitly prohibit it. Our
22745 callers must be ready to deal with unification failures in any
22746 event. */
22748 /* If we aren't explaining yet, push tinst context so we can see where
22749 any errors (e.g. from class instantiations triggered by instantiation
22750 of default template arguments) come from. If we are explaining, this
22751 context is redundant. */
22752 if (!explain_p && !push_tinst_level (fn, targs))
22754 excessive_deduction_depth = true;
22755 goto fail;
22758 ok = !type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
22759 full_targs, parms, args, nargs, /*subr=*/0,
22760 strict, &checks, explain_p);
22761 if (!explain_p)
22762 pop_tinst_level ();
22763 if (!ok)
22764 goto fail;
22766 /* Now that we have bindings for all of the template arguments,
22767 ensure that the arguments deduced for the template template
22768 parameters have compatible template parameter lists. We cannot
22769 check this property before we have deduced all template
22770 arguments, because the template parameter types of a template
22771 template parameter might depend on prior template parameters
22772 deduced after the template template parameter. The following
22773 ill-formed example illustrates this issue:
22775 template<typename T, template<T> class C> void f(C<5>, T);
22777 template<int N> struct X {};
22779 void g() {
22780 f(X<5>(), 5l); // error: template argument deduction fails
22783 The template parameter list of 'C' depends on the template type
22784 parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
22785 'long'. Thus, we can't check that 'C' cannot bind to 'X' at the
22786 time that we deduce 'C'. */
22787 if (!template_template_parm_bindings_ok_p
22788 (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
22790 unify_inconsistent_template_template_parameters (explain_p);
22791 goto fail;
22794 deduced:
22796 /* As a refinement of CWG2369, check first and foremost non-dependent
22797 conversions that we know are not going to induce template instantiation
22798 (PR99599). */
22799 if (strict == DEDUCE_CALL
22800 && incomplete
22801 && check_non_deducible_conversions (parms, args, nargs, fn, strict, flags,
22802 convs, explain_p,
22803 /*noninst_only_p=*/true))
22804 goto fail;
22806 /* CWG2369: Check satisfaction before non-deducible conversions. */
22807 if (!constraints_satisfied_p (fn, targs))
22809 if (explain_p)
22810 diagnose_constraints (DECL_SOURCE_LOCATION (fn), fn, targs);
22811 goto fail;
22814 /* DR 1391: All parameters have args, now check non-dependent parms for
22815 convertibility. We don't do this if all args were explicitly specified,
22816 as the standard says that we substitute explicit args immediately. */
22817 if (incomplete
22818 && check_non_deducible_conversions (parms, args, nargs, fn, strict, flags,
22819 convs, explain_p,
22820 /*noninst_only_p=*/false))
22821 goto fail;
22823 /* All is well so far. Now, check:
22825 [temp.deduct]
22827 When all template arguments have been deduced, all uses of
22828 template parameters in nondeduced contexts are replaced with
22829 the corresponding deduced argument values. If the
22830 substitution results in an invalid type, as described above,
22831 type deduction fails. */
22832 if (!push_tinst_level (fn, targs))
22834 excessive_deduction_depth = true;
22835 goto fail;
22838 /* Also collect access checks from the instantiation. */
22839 reopen_deferring_access_checks (checks);
22841 decl = instantiate_template (fn, targs, complain);
22843 checks = get_deferred_access_checks ();
22844 pop_deferring_access_checks ();
22846 pop_tinst_level ();
22848 if (decl == error_mark_node)
22849 goto fail;
22851 /* Now perform any access checks encountered during substitution. */
22852 push_access_scope (decl);
22853 ok = perform_access_checks (checks, complain);
22854 pop_access_scope (decl);
22855 if (!ok)
22856 goto fail;
22858 /* If we're looking for an exact match, check that what we got
22859 is indeed an exact match. It might not be if some template
22860 parameters are used in non-deduced contexts. But don't check
22861 for an exact match if we have dependent template arguments;
22862 in that case we're doing partial ordering, and we already know
22863 that we have two candidates that will provide the actual type. */
22864 if (strict == DEDUCE_EXACT && !any_dependent_template_arguments_p (targs))
22866 tree substed = TREE_TYPE (decl);
22867 unsigned int i;
22869 tree sarg
22870 = skip_artificial_parms_for (decl, TYPE_ARG_TYPES (substed));
22871 if (return_type)
22872 sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
22873 for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
22874 if (!same_type_p (args[i], TREE_VALUE (sarg)))
22876 unify_type_mismatch (explain_p, args[i],
22877 TREE_VALUE (sarg));
22878 goto fail;
22880 if ((i < nargs || sarg)
22881 /* add_candidates uses DEDUCE_EXACT for x.operator foo(), but args
22882 doesn't contain the trailing void, and conv fns are always (). */
22883 && !DECL_CONV_FN_P (decl))
22885 unsigned nsargs = i + list_length (sarg);
22886 unify_arity (explain_p, nargs, nsargs);
22887 goto fail;
22891 /* After doing deduction with the inherited constructor, actually return an
22892 instantiation of the inheriting constructor. */
22893 if (orig_fn != fn)
22894 decl = instantiate_template (orig_fn, targs, complain);
22896 r = decl;
22898 fail:
22899 --deduction_depth;
22900 if (excessive_deduction_depth)
22902 if (deduction_depth == 0)
22903 /* Reset once we're all the way out. */
22904 excessive_deduction_depth = false;
22907 return r;
22910 /* Returns true iff PARM is a forwarding reference in the context of
22911 template argument deduction for TMPL. */
22913 static bool
22914 forwarding_reference_p (tree parm, tree tmpl)
22916 /* [temp.deduct.call], "A forwarding reference is an rvalue reference to a
22917 cv-unqualified template parameter ..." */
22918 if (TYPE_REF_P (parm)
22919 && TYPE_REF_IS_RVALUE (parm)
22920 && TREE_CODE (TREE_TYPE (parm)) == TEMPLATE_TYPE_PARM
22921 && cp_type_quals (TREE_TYPE (parm)) == TYPE_UNQUALIFIED)
22923 parm = TREE_TYPE (parm);
22924 /* [temp.deduct.call], "... that does not represent a template parameter
22925 of a class template (during class template argument deduction)." */
22926 if (tmpl
22927 && deduction_guide_p (tmpl)
22928 && DECL_ARTIFICIAL (tmpl))
22930 /* Since the template parameters of a synthesized guide consist of
22931 the template parameters of the class template followed by those of
22932 the constructor (if any), we can tell if PARM represents a template
22933 parameter of the class template by comparing its index with the
22934 arity of the class template. */
22935 tree ctmpl = CLASSTYPE_TI_TEMPLATE (TREE_TYPE (TREE_TYPE (tmpl)));
22936 if (TEMPLATE_TYPE_IDX (parm)
22937 < TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (ctmpl)))
22938 return false;
22940 return true;
22942 return false;
22945 /* Adjust types before performing type deduction, as described in
22946 [temp.deduct.call] and [temp.deduct.conv]. The rules in these two
22947 sections are symmetric. PARM is the type of a function parameter
22948 or the return type of the conversion function. ARG is the type of
22949 the argument passed to the call, or the type of the value
22950 initialized with the result of the conversion function.
22951 ARG_EXPR is the original argument expression, which may be null. */
22953 static int
22954 maybe_adjust_types_for_deduction (tree tparms,
22955 unification_kind_t strict,
22956 tree* parm,
22957 tree* arg,
22958 tree arg_expr)
22960 int result = 0;
22962 switch (strict)
22964 case DEDUCE_CALL:
22965 break;
22967 case DEDUCE_CONV:
22968 /* [temp.deduct.conv] First remove a reference type on parm.
22969 DRs 322 & 976 affected this. */
22970 if (TYPE_REF_P (*parm))
22971 *parm = TREE_TYPE (*parm);
22973 /* Swap PARM and ARG throughout the remainder of this
22974 function; the handling is precisely symmetric since PARM
22975 will initialize ARG rather than vice versa. */
22976 std::swap (parm, arg);
22978 break;
22980 case DEDUCE_EXACT:
22981 /* Core issue #873: Do the DR606 thing (see below) for these cases,
22982 too, but here handle it by stripping the reference from PARM
22983 rather than by adding it to ARG. */
22984 if (forwarding_reference_p (*parm, TPARMS_PRIMARY_TEMPLATE (tparms))
22985 && TYPE_REF_P (*arg)
22986 && !TYPE_REF_IS_RVALUE (*arg))
22987 *parm = TREE_TYPE (*parm);
22988 /* Nothing else to do in this case. */
22989 return 0;
22991 default:
22992 gcc_unreachable ();
22995 if (!TYPE_REF_P (*parm))
22997 /* [temp.deduct.call]
22999 If P is not a reference type:
23001 --If A is an array type, the pointer type produced by the
23002 array-to-pointer standard conversion (_conv.array_) is
23003 used in place of A for type deduction; otherwise,
23005 --If A is a function type, the pointer type produced by
23006 the function-to-pointer standard conversion
23007 (_conv.func_) is used in place of A for type deduction;
23008 otherwise,
23010 --If A is a cv-qualified type, the top level
23011 cv-qualifiers of A's type are ignored for type
23012 deduction. */
23013 if (TREE_CODE (*arg) == ARRAY_TYPE)
23014 *arg = build_pointer_type (TREE_TYPE (*arg));
23015 else if (TREE_CODE (*arg) == FUNCTION_TYPE)
23016 *arg = build_pointer_type (*arg);
23017 else
23018 *arg = TYPE_MAIN_VARIANT (*arg);
23021 /* [temp.deduct.call], "If P is a forwarding reference and the argument is
23022 an lvalue, the type 'lvalue reference to A' is used in place of A for
23023 type deduction." */
23024 if (forwarding_reference_p (*parm, TPARMS_PRIMARY_TEMPLATE (tparms))
23025 && (arg_expr ? lvalue_p (arg_expr)
23026 /* try_one_overload doesn't provide an arg_expr, but
23027 functions are always lvalues. */
23028 : TREE_CODE (*arg) == FUNCTION_TYPE))
23029 *arg = build_reference_type (*arg);
23031 /* [temp.deduct.call]
23033 If P is a cv-qualified type, the top level cv-qualifiers
23034 of P's type are ignored for type deduction. If P is a
23035 reference type, the type referred to by P is used for
23036 type deduction. */
23037 *parm = TYPE_MAIN_VARIANT (*parm);
23038 if (TYPE_REF_P (*parm))
23040 *parm = TREE_TYPE (*parm);
23041 result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
23044 return result;
23047 /* Return true if computing a conversion from FROM to TO might induce template
23048 instantiation. Conversely, if this predicate returns false then computing
23049 the conversion definitely won't induce template instantiation. */
23051 static bool
23052 conversion_may_instantiate_p (tree to, tree from)
23054 to = non_reference (to);
23055 from = non_reference (from);
23057 bool ptr_conv_p = false;
23058 if (TYPE_PTR_P (to)
23059 && TYPE_PTR_P (from))
23061 to = TREE_TYPE (to);
23062 from = TREE_TYPE (from);
23063 ptr_conv_p = true;
23066 /* If one of the types is a not-yet-instantiated class template
23067 specialization, then computing the conversion might instantiate
23068 it in order to inspect bases, conversion functions and/or
23069 converting constructors. */
23070 if ((CLASS_TYPE_P (to)
23071 && !COMPLETE_TYPE_P (to)
23072 && CLASSTYPE_TEMPLATE_INSTANTIATION (to))
23073 || (CLASS_TYPE_P (from)
23074 && !COMPLETE_TYPE_P (from)
23075 && CLASSTYPE_TEMPLATE_INSTANTIATION (from)))
23076 return true;
23078 /* Converting from one pointer type to another, or between
23079 reference-related types, always yields a standard conversion. */
23080 if (ptr_conv_p || reference_related_p (to, from))
23081 return false;
23083 /* Converting to a non-aggregate class type will consider its
23084 user-declared constructors, which might induce instantiation. */
23085 if (CLASS_TYPE_P (to)
23086 && CLASSTYPE_NON_AGGREGATE (to))
23087 return true;
23089 /* Similarly, converting from a class type will consider its conversion
23090 functions. */
23091 if (CLASS_TYPE_P (from)
23092 && TYPE_HAS_CONVERSION (from))
23093 return true;
23095 /* Otherwise, computing this conversion definitely won't induce
23096 template instantiation. */
23097 return false;
23100 /* Subroutine of fn_type_unification. PARM is a function parameter of a
23101 template which doesn't contain any deducible template parameters; check if
23102 ARG is a suitable match for it. STRICT, FLAGS and EXPLAIN_P are as in
23103 unify_one_argument. */
23105 static int
23106 check_non_deducible_conversion (tree parm, tree arg, unification_kind_t strict,
23107 int flags, struct conversion **conv_p,
23108 bool explain_p, bool noninst_only_p)
23110 tree type;
23112 if (!TYPE_P (arg))
23113 type = TREE_TYPE (arg);
23114 else
23115 type = arg;
23117 if (same_type_p (parm, type))
23118 return unify_success (explain_p);
23120 tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
23121 if (strict == DEDUCE_CONV)
23123 if (can_convert_arg (type, parm, NULL_TREE, flags, complain))
23124 return unify_success (explain_p);
23126 else if (strict == DEDUCE_CALL)
23128 if (conv_p && *conv_p)
23130 /* This conversion was already computed earlier (when
23131 computing only non-instantiating conversions). */
23132 gcc_checking_assert (!noninst_only_p);
23133 return unify_success (explain_p);
23136 if (noninst_only_p
23137 && conversion_may_instantiate_p (parm, type))
23138 return unify_success (explain_p);
23140 bool ok = false;
23141 tree conv_arg = TYPE_P (arg) ? NULL_TREE : arg;
23142 if (conv_p)
23143 /* Avoid recalculating this in add_function_candidate. */
23144 ok = (*conv_p
23145 = good_conversion (parm, type, conv_arg, flags, complain));
23146 else
23147 ok = can_convert_arg (parm, type, conv_arg, flags, complain);
23148 if (ok)
23149 return unify_success (explain_p);
23152 if (strict == DEDUCE_EXACT)
23153 return unify_type_mismatch (explain_p, parm, arg);
23154 else
23155 return unify_arg_conversion (explain_p, parm, type, arg);
23158 static bool uses_deducible_template_parms (tree type);
23160 /* Returns true iff the expression EXPR is one from which a template
23161 argument can be deduced. In other words, if it's an undecorated
23162 use of a template non-type parameter. */
23164 static bool
23165 deducible_expression (tree expr)
23167 /* Strip implicit conversions and implicit INDIRECT_REFs. */
23168 while (CONVERT_EXPR_P (expr)
23169 || TREE_CODE (expr) == VIEW_CONVERT_EXPR
23170 || TREE_CODE (expr) == IMPLICIT_CONV_EXPR
23171 || REFERENCE_REF_P (expr))
23172 expr = TREE_OPERAND (expr, 0);
23173 return (TREE_CODE (expr) == TEMPLATE_PARM_INDEX);
23176 /* Returns true iff the array domain DOMAIN uses a template parameter in a
23177 deducible way; that is, if it has a max value of <PARM> - 1. */
23179 static bool
23180 deducible_array_bound (tree domain)
23182 if (domain == NULL_TREE)
23183 return false;
23185 tree max = TYPE_MAX_VALUE (domain);
23186 if (TREE_CODE (max) != MINUS_EXPR)
23187 return false;
23189 return deducible_expression (TREE_OPERAND (max, 0));
23192 /* Returns true iff the template arguments ARGS use a template parameter
23193 in a deducible way. */
23195 static bool
23196 deducible_template_args (tree args)
23198 for (tree elt : tree_vec_range (args))
23200 bool deducible;
23201 if (ARGUMENT_PACK_P (elt))
23202 deducible = deducible_template_args (ARGUMENT_PACK_ARGS (elt));
23203 else
23205 if (PACK_EXPANSION_P (elt))
23206 elt = PACK_EXPANSION_PATTERN (elt);
23207 if (TREE_CODE (elt) == TEMPLATE_TEMPLATE_PARM)
23208 deducible = true;
23209 else if (TYPE_P (elt))
23210 deducible = uses_deducible_template_parms (elt);
23211 else
23212 deducible = deducible_expression (elt);
23214 if (deducible)
23215 return true;
23217 return false;
23220 /* Returns true iff TYPE contains any deducible references to template
23221 parameters, as per 14.8.2.5. */
23223 static bool
23224 uses_deducible_template_parms (tree type)
23226 if (PACK_EXPANSION_P (type))
23227 type = PACK_EXPANSION_PATTERN (type);
23229 /* T
23230 cv-list T
23231 TT<T>
23232 TT<i>
23233 TT<> */
23234 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
23235 || TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
23236 return true;
23238 /* T*
23240 T&& */
23241 if (INDIRECT_TYPE_P (type))
23242 return uses_deducible_template_parms (TREE_TYPE (type));
23244 /* T[integer-constant ]
23245 type [i] */
23246 if (TREE_CODE (type) == ARRAY_TYPE)
23247 return (uses_deducible_template_parms (TREE_TYPE (type))
23248 || deducible_array_bound (TYPE_DOMAIN (type)));
23250 /* T type ::*
23251 type T::*
23252 T T::*
23253 T (type ::*)()
23254 type (T::*)()
23255 type (type ::*)(T)
23256 type (T::*)(T)
23257 T (type ::*)(T)
23258 T (T::*)()
23259 T (T::*)(T) */
23260 if (TYPE_PTRMEM_P (type))
23261 return (uses_deducible_template_parms (TYPE_PTRMEM_CLASS_TYPE (type))
23262 || (uses_deducible_template_parms
23263 (TYPE_PTRMEM_POINTED_TO_TYPE (type))));
23265 /* template-name <T> (where template-name refers to a class template)
23266 template-name <i> (where template-name refers to a class template) */
23267 if (CLASS_TYPE_P (type)
23268 && CLASSTYPE_TEMPLATE_INFO (type)
23269 && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type)))
23270 return deducible_template_args (INNERMOST_TEMPLATE_ARGS
23271 (CLASSTYPE_TI_ARGS (type)));
23273 /* type (T)
23275 T(T) */
23276 if (FUNC_OR_METHOD_TYPE_P (type))
23278 if (uses_deducible_template_parms (TREE_TYPE (type)))
23279 return true;
23280 tree parm = TYPE_ARG_TYPES (type);
23281 if (TREE_CODE (type) == METHOD_TYPE)
23282 parm = TREE_CHAIN (parm);
23283 for (; parm; parm = TREE_CHAIN (parm))
23284 if (uses_deducible_template_parms (TREE_VALUE (parm)))
23285 return true;
23286 if (flag_noexcept_type
23287 && TYPE_RAISES_EXCEPTIONS (type)
23288 && TREE_PURPOSE (TYPE_RAISES_EXCEPTIONS (type))
23289 && deducible_expression (TREE_PURPOSE (TYPE_RAISES_EXCEPTIONS (type))))
23290 return true;
23293 return false;
23296 /* Subroutine of type_unification_real and unify_pack_expansion to
23297 handle unification of a single P/A pair. Parameters are as
23298 for those functions. */
23300 static int
23301 unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
23302 int subr, unification_kind_t strict,
23303 bool explain_p)
23305 tree arg_expr = NULL_TREE;
23306 int arg_strict;
23308 if (arg == error_mark_node || parm == error_mark_node)
23309 return unify_invalid (explain_p);
23310 if (arg == unknown_type_node)
23311 /* We can't deduce anything from this, but we might get all the
23312 template args from other function args. */
23313 return unify_success (explain_p);
23315 /* Implicit conversions (Clause 4) will be performed on a function
23316 argument to convert it to the type of the corresponding function
23317 parameter if the parameter type contains no template-parameters that
23318 participate in template argument deduction. */
23319 if (strict != DEDUCE_EXACT
23320 && TYPE_P (parm) && !uses_deducible_template_parms (parm))
23321 /* For function parameters with no deducible template parameters,
23322 just return. We'll check non-dependent conversions later. */
23323 return unify_success (explain_p);
23325 switch (strict)
23327 case DEDUCE_CALL:
23328 arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
23329 | UNIFY_ALLOW_MORE_CV_QUAL
23330 | UNIFY_ALLOW_DERIVED);
23331 break;
23333 case DEDUCE_CONV:
23334 arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
23335 break;
23337 case DEDUCE_EXACT:
23338 arg_strict = UNIFY_ALLOW_NONE;
23339 break;
23341 default:
23342 gcc_unreachable ();
23345 /* We only do these transformations if this is the top-level
23346 parameter_type_list in a call or declaration matching; in other
23347 situations (nested function declarators, template argument lists) we
23348 won't be comparing a type to an expression, and we don't do any type
23349 adjustments. */
23350 if (!subr)
23352 if (!TYPE_P (arg))
23354 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
23355 if (type_unknown_p (arg))
23357 /* [temp.deduct.type] A template-argument can be
23358 deduced from a pointer to function or pointer
23359 to member function argument if the set of
23360 overloaded functions does not contain function
23361 templates and at most one of a set of
23362 overloaded functions provides a unique
23363 match. */
23364 resolve_overloaded_unification (tparms, targs, parm,
23365 arg, strict,
23366 arg_strict, explain_p);
23367 /* If a unique match was not found, this is a
23368 non-deduced context, so we still succeed. */
23369 return unify_success (explain_p);
23372 arg_expr = arg;
23373 arg = unlowered_expr_type (arg);
23374 if (arg == error_mark_node)
23375 return unify_invalid (explain_p);
23378 arg_strict |= maybe_adjust_types_for_deduction (tparms, strict,
23379 &parm, &arg, arg_expr);
23381 else
23382 if ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
23383 != (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL))
23384 return unify_template_argument_mismatch (explain_p, parm, arg);
23386 /* For deduction from an init-list we need the actual list. */
23387 if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
23388 arg = arg_expr;
23389 return unify (tparms, targs, parm, arg, arg_strict, explain_p);
23392 /* for_each_template_parm callback that always returns 0. */
23394 static int
23395 zero_r (tree, void *)
23397 return 0;
23400 /* for_each_template_parm any_fn callback to handle deduction of a template
23401 type argument from the type of an array bound. */
23403 static int
23404 array_deduction_r (tree t, void *data)
23406 tree_pair_p d = (tree_pair_p)data;
23407 tree &tparms = d->purpose;
23408 tree &targs = d->value;
23410 if (TREE_CODE (t) == ARRAY_TYPE)
23411 if (tree dom = TYPE_DOMAIN (t))
23412 if (tree max = TYPE_MAX_VALUE (dom))
23414 if (TREE_CODE (max) == MINUS_EXPR)
23415 max = TREE_OPERAND (max, 0);
23416 if (TREE_CODE (max) == TEMPLATE_PARM_INDEX)
23417 unify (tparms, targs, TREE_TYPE (max), size_type_node,
23418 UNIFY_ALLOW_NONE, /*explain*/false);
23421 /* Keep walking. */
23422 return 0;
23425 /* Try to deduce any not-yet-deduced template type arguments from the type of
23426 an array bound. This is handled separately from unify because 14.8.2.5 says
23427 "The type of a type parameter is only deduced from an array bound if it is
23428 not otherwise deduced." */
23430 static void
23431 try_array_deduction (tree tparms, tree targs, tree parm)
23433 tree_pair_s data = { tparms, targs };
23434 hash_set<tree> visited;
23435 for_each_template_parm (parm, zero_r, &data, &visited,
23436 /*nondeduced*/false, array_deduction_r);
23439 /* Most parms like fn_type_unification.
23441 If SUBR is 1, we're being called recursively (to unify the
23442 arguments of a function or method parameter of a function
23443 template).
23445 CHECKS is a pointer to a vector of access checks encountered while
23446 substituting default template arguments. */
23448 static int
23449 type_unification_real (tree tparms,
23450 tree full_targs,
23451 tree xparms,
23452 const tree *xargs,
23453 unsigned int xnargs,
23454 int subr,
23455 unification_kind_t strict,
23456 vec<deferred_access_check, va_gc> **checks,
23457 bool explain_p)
23459 tree parm, arg;
23460 int i;
23461 int ntparms = TREE_VEC_LENGTH (tparms);
23462 int saw_undeduced = 0;
23463 tree parms;
23464 const tree *args;
23465 unsigned int nargs;
23466 unsigned int ia;
23468 gcc_assert (TREE_CODE (tparms) == TREE_VEC);
23469 gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
23470 gcc_assert (ntparms > 0);
23472 tree targs = INNERMOST_TEMPLATE_ARGS (full_targs);
23474 /* Reset the number of non-defaulted template arguments contained
23475 in TARGS. */
23476 NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
23478 again:
23479 parms = xparms;
23480 args = xargs;
23481 nargs = xnargs;
23483 /* Only fn_type_unification cares about terminal void. */
23484 if (nargs && args[nargs-1] == void_type_node)
23485 --nargs;
23487 ia = 0;
23488 while (parms && parms != void_list_node
23489 && ia < nargs)
23491 parm = TREE_VALUE (parms);
23493 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
23494 && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
23495 /* For a function parameter pack that occurs at the end of the
23496 parameter-declaration-list, the type A of each remaining
23497 argument of the call is compared with the type P of the
23498 declarator-id of the function parameter pack. */
23499 break;
23501 parms = TREE_CHAIN (parms);
23503 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
23504 /* For a function parameter pack that does not occur at the
23505 end of the parameter-declaration-list, the type of the
23506 parameter pack is a non-deduced context. */
23507 continue;
23509 /* [temp.deduct.conv] only applies to the deduction of the return
23510 type, which is always the first argument here. Other arguments
23511 (notably, explicit object parameters) should undergo normal
23512 call-like unification. */
23513 unification_kind_t kind = strict;
23514 if (strict == DEDUCE_CONV && ia > 0)
23515 kind = DEDUCE_CALL;
23517 arg = args[ia];
23518 ++ia;
23520 if (unify_one_argument (tparms, full_targs, parm, arg, subr, kind,
23521 explain_p))
23522 return 1;
23525 if (parms
23526 && parms != void_list_node
23527 && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
23529 gcc_assert (strict != DEDUCE_CONV);
23531 /* Unify the remaining arguments with the pack expansion type. */
23532 tree argvec;
23533 tree parmvec = make_tree_vec (1);
23535 /* Allocate a TREE_VEC and copy in all of the arguments */
23536 argvec = make_tree_vec (nargs - ia);
23537 for (i = 0; ia < nargs; ++ia, ++i)
23538 TREE_VEC_ELT (argvec, i) = args[ia];
23540 /* Copy the parameter into parmvec. */
23541 TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
23542 if (unify_pack_expansion (tparms, full_targs, parmvec, argvec, strict,
23543 /*subr=*/subr, explain_p))
23544 return 1;
23546 /* Advance to the end of the list of parameters. */
23547 parms = TREE_CHAIN (parms);
23550 /* Fail if we've reached the end of the parm list, and more args
23551 are present, and the parm list isn't variadic. */
23552 if (ia < nargs && parms == void_list_node)
23553 return unify_too_many_arguments (explain_p, nargs, ia);
23554 /* Fail if parms are left and they don't have default values and
23555 they aren't all deduced as empty packs (c++/57397). This is
23556 consistent with sufficient_parms_p. */
23557 if (parms && parms != void_list_node
23558 && TREE_PURPOSE (parms) == NULL_TREE)
23560 unsigned int count = nargs;
23561 tree p = parms;
23562 bool type_pack_p;
23565 type_pack_p = TREE_CODE (TREE_VALUE (p)) == TYPE_PACK_EXPANSION;
23566 if (!type_pack_p)
23567 count++;
23568 p = TREE_CHAIN (p);
23570 while (p && p != void_list_node);
23571 if (count != nargs)
23572 return unify_too_few_arguments (explain_p, ia, count,
23573 type_pack_p);
23576 if (!subr)
23578 tsubst_flags_t complain = (explain_p
23579 ? tf_warning_or_error
23580 : tf_none);
23581 bool tried_array_deduction = (cxx_dialect < cxx17);
23583 for (i = 0; i < ntparms; i++)
23585 tree targ = TREE_VEC_ELT (targs, i);
23586 tree tparm = TREE_VEC_ELT (tparms, i);
23588 /* Clear the "incomplete" flags on all argument packs now so that
23589 substituting them into later default arguments works. */
23590 if (targ && ARGUMENT_PACK_P (targ))
23592 ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
23593 ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
23596 if (targ || tparm == error_mark_node)
23597 continue;
23598 tparm = TREE_VALUE (tparm);
23600 if (TREE_CODE (tparm) == TYPE_DECL
23601 && !tried_array_deduction)
23603 try_array_deduction (tparms, targs, xparms);
23604 tried_array_deduction = true;
23605 if (TREE_VEC_ELT (targs, i))
23606 continue;
23609 /* If this is an undeduced nontype parameter that depends on
23610 a type parameter, try another pass; its type may have been
23611 deduced from a later argument than the one from which
23612 this parameter can be deduced. */
23613 if (TREE_CODE (tparm) == PARM_DECL
23614 && !is_auto (TREE_TYPE (tparm))
23615 && uses_template_parms (TREE_TYPE (tparm))
23616 && saw_undeduced < 2)
23618 saw_undeduced = 1;
23619 continue;
23622 /* Core issue #226 (C++0x) [temp.deduct]:
23624 If a template argument has not been deduced, its
23625 default template argument, if any, is used.
23627 When we are in C++98 mode, TREE_PURPOSE will either
23628 be NULL_TREE or ERROR_MARK_NODE, so we do not need
23629 to explicitly check cxx_dialect here. */
23630 if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
23631 /* OK, there is a default argument. Wait until after the
23632 conversion check to do substitution. */
23633 continue;
23635 /* If the type parameter is a parameter pack, then it will
23636 be deduced to an empty parameter pack. */
23637 if (template_parameter_pack_p (tparm))
23639 tree arg;
23641 if (TREE_CODE (tparm) == PARM_DECL)
23643 arg = make_node (NONTYPE_ARGUMENT_PACK);
23644 TREE_CONSTANT (arg) = 1;
23646 else
23647 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
23649 ARGUMENT_PACK_ARGS (arg) = make_tree_vec (0);
23651 TREE_VEC_ELT (targs, i) = arg;
23652 continue;
23655 return unify_parameter_deduction_failure (explain_p, tparm);
23658 /* During partial ordering, we deduce dependent template args. */
23659 bool any_dependent_targs = false;
23661 /* Now substitute into the default template arguments. */
23662 for (i = 0; i < ntparms; i++)
23664 tree targ = TREE_VEC_ELT (targs, i);
23665 tree tparm = TREE_VEC_ELT (tparms, i);
23667 if (targ)
23669 if (!any_dependent_targs && dependent_template_arg_p (targ))
23670 any_dependent_targs = true;
23671 continue;
23673 if (tparm == error_mark_node)
23674 continue;
23676 tree parm = TREE_VALUE (tparm);
23677 tree arg = TREE_PURPOSE (tparm);
23678 reopen_deferring_access_checks (*checks);
23679 location_t save_loc = input_location;
23680 if (DECL_P (parm))
23681 input_location = DECL_SOURCE_LOCATION (parm);
23683 if (saw_undeduced == 1
23684 && TREE_CODE (parm) == PARM_DECL
23685 && !is_auto (TREE_TYPE (parm))
23686 && uses_template_parms (TREE_TYPE (parm)))
23688 /* The type of this non-type parameter depends on undeduced
23689 parameters. Don't try to use its default argument yet,
23690 since we might deduce an argument for it on the next pass,
23691 but do check whether the arguments we already have cause
23692 substitution failure, so that that happens before we try
23693 later default arguments (78489). */
23694 ++processing_template_decl;
23695 tree type = tsubst (TREE_TYPE (parm), full_targs, complain,
23696 NULL_TREE);
23697 --processing_template_decl;
23698 if (type == error_mark_node)
23699 arg = error_mark_node;
23700 else
23701 arg = NULL_TREE;
23703 else
23705 /* Even if the call is happening in template context, getting
23706 here means it's non-dependent, and a default argument is
23707 considered a separate definition under [temp.decls], so we can
23708 do this substitution without processing_template_decl. This
23709 is important if the default argument contains something that
23710 might be instantiation-dependent like access (87480). */
23711 processing_template_decl_sentinel s (!any_dependent_targs);
23713 tree used_tparms = NULL_TREE;
23714 if (saw_undeduced == 1)
23716 tree tparms_list = build_tree_list (size_int (1), tparms);
23717 used_tparms = find_template_parameters (arg, tparms_list);
23718 for (; used_tparms; used_tparms = TREE_CHAIN (used_tparms))
23720 int level, index;
23721 template_parm_level_and_index (TREE_VALUE (used_tparms),
23722 &level, &index);
23723 if (TREE_VEC_ELT (targs, index) == NULL_TREE)
23724 break;
23728 if (!used_tparms)
23730 /* All template parameters within this default argument are
23731 deduced, so we can use it. */
23732 arg = tsubst_template_arg (arg, full_targs, complain,
23733 NULL_TREE);
23734 arg = convert_template_argument (parm, arg, full_targs,
23735 complain, i, NULL_TREE);
23737 else if (saw_undeduced == 1)
23738 arg = NULL_TREE;
23739 else if (!any_dependent_targs)
23740 arg = error_mark_node;
23743 input_location = save_loc;
23744 *checks = get_deferred_access_checks ();
23745 pop_deferring_access_checks ();
23747 if (arg == error_mark_node)
23748 return 1;
23749 else if (arg)
23751 TREE_VEC_ELT (targs, i) = arg;
23752 /* The position of the first default template argument,
23753 is also the number of non-defaulted arguments in TARGS.
23754 Record that. */
23755 if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
23756 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
23760 if (saw_undeduced++ == 1)
23761 goto again;
23764 if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
23765 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
23767 return unify_success (explain_p);
23770 /* Subroutine of type_unification_real. Args are like the variables
23771 at the call site. ARG is an overloaded function (or template-id);
23772 we try deducing template args from each of the overloads, and if
23773 only one succeeds, we go with that. Modifies TARGS and returns
23774 true on success. */
23776 static bool
23777 resolve_overloaded_unification (tree tparms,
23778 tree targs,
23779 tree parm,
23780 tree arg,
23781 unification_kind_t strict,
23782 int sub_strict,
23783 bool explain_p)
23785 tree tempargs = copy_node (targs);
23786 int good = 0;
23787 tree goodfn = NULL_TREE;
23788 bool addr_p;
23790 if (TREE_CODE (arg) == ADDR_EXPR)
23792 arg = TREE_OPERAND (arg, 0);
23793 addr_p = true;
23795 else
23796 addr_p = false;
23798 if (TREE_CODE (arg) == COMPONENT_REF)
23799 /* Handle `&x' where `x' is some static or non-static member
23800 function name. */
23801 arg = TREE_OPERAND (arg, 1);
23803 if (TREE_CODE (arg) == OFFSET_REF)
23804 arg = TREE_OPERAND (arg, 1);
23806 /* Strip baselink information. */
23807 if (BASELINK_P (arg))
23808 arg = BASELINK_FUNCTIONS (arg);
23810 if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
23812 /* If we got some explicit template args, we need to plug them into
23813 the affected templates before we try to unify, in case the
23814 explicit args will completely resolve the templates in question. */
23816 int ok = 0;
23817 tree expl_subargs = TREE_OPERAND (arg, 1);
23818 arg = TREE_OPERAND (arg, 0);
23820 for (lkp_iterator iter (arg); iter; ++iter)
23822 tree fn = *iter;
23823 tree subargs, elem;
23825 if (TREE_CODE (fn) != TEMPLATE_DECL)
23826 continue;
23828 subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
23829 expl_subargs, NULL_TREE, tf_none);
23830 if (subargs != error_mark_node
23831 && !any_dependent_template_arguments_p (subargs))
23833 fn = instantiate_template (fn, subargs, tf_none);
23834 if (!constraints_satisfied_p (fn))
23835 continue;
23836 if (undeduced_auto_decl (fn))
23838 /* Instantiate the function to deduce its return type. */
23839 ++function_depth;
23840 instantiate_decl (fn, /*defer*/false, /*class*/false);
23841 --function_depth;
23844 if (flag_noexcept_type)
23845 maybe_instantiate_noexcept (fn, tf_none);
23847 elem = TREE_TYPE (fn);
23848 if (try_one_overload (tparms, targs, tempargs, parm,
23849 elem, strict, sub_strict, addr_p, explain_p)
23850 && (!goodfn || !same_type_p (goodfn, elem)))
23852 goodfn = elem;
23853 ++good;
23856 else if (subargs)
23857 ++ok;
23859 /* If no templates (or more than one) are fully resolved by the
23860 explicit arguments, this template-id is a non-deduced context; it
23861 could still be OK if we deduce all template arguments for the
23862 enclosing call through other arguments. */
23863 if (good != 1)
23864 good = ok;
23866 else if (!OVL_P (arg))
23867 /* If ARG is, for example, "(0, &f)" then its type will be unknown
23868 -- but the deduction does not succeed because the expression is
23869 not just the function on its own. */
23870 return false;
23871 else
23872 for (lkp_iterator iter (arg); iter; ++iter)
23874 tree fn = *iter;
23875 if (flag_noexcept_type)
23876 maybe_instantiate_noexcept (fn, tf_none);
23877 if (TREE_CODE (fn) == FUNCTION_DECL && !constraints_satisfied_p (fn))
23878 continue;
23879 tree elem = TREE_TYPE (fn);
23880 if (try_one_overload (tparms, targs, tempargs, parm, elem,
23881 strict, sub_strict, addr_p, explain_p)
23882 && (!goodfn || !same_type_p (goodfn, elem)))
23884 goodfn = elem;
23885 ++good;
23889 /* [temp.deduct.type] A template-argument can be deduced from a pointer
23890 to function or pointer to member function argument if the set of
23891 overloaded functions does not contain function templates and at most
23892 one of a set of overloaded functions provides a unique match.
23894 CWG2918 allows multiple functions to match if they all have the same type,
23895 so that we can choose the most constrained later.
23897 So if we found multiple possibilities, we return success but don't
23898 deduce anything. */
23900 if (good == 1)
23902 int i = TREE_VEC_LENGTH (targs);
23903 for (; i--; )
23904 if (TREE_VEC_ELT (tempargs, i))
23906 tree old = TREE_VEC_ELT (targs, i);
23907 tree new_ = TREE_VEC_ELT (tempargs, i);
23908 if (new_ && old && ARGUMENT_PACK_P (old)
23909 && ARGUMENT_PACK_EXPLICIT_ARGS (old))
23910 /* Don't forget explicit template arguments in a pack. */
23911 ARGUMENT_PACK_EXPLICIT_ARGS (new_)
23912 = ARGUMENT_PACK_EXPLICIT_ARGS (old);
23913 TREE_VEC_ELT (targs, i) = new_;
23916 if (good)
23917 return true;
23919 return false;
23922 /* Core DR 115: In contexts where deduction is done and fails, or in
23923 contexts where deduction is not done, if a template argument list is
23924 specified and it, along with any default template arguments, identifies
23925 a single function template specialization, then the template-id is an
23926 lvalue for the function template specialization. */
23928 tree
23929 resolve_nondeduced_context (tree orig_expr, tsubst_flags_t complain)
23931 tree expr, offset, baselink;
23932 bool addr;
23934 if (!type_unknown_p (orig_expr))
23935 return orig_expr;
23937 expr = orig_expr;
23938 addr = false;
23939 offset = NULL_TREE;
23940 baselink = NULL_TREE;
23942 if (TREE_CODE (expr) == ADDR_EXPR)
23944 expr = TREE_OPERAND (expr, 0);
23945 addr = true;
23947 if (TREE_CODE (expr) == OFFSET_REF)
23949 offset = expr;
23950 expr = TREE_OPERAND (expr, 1);
23952 if (BASELINK_P (expr))
23954 baselink = expr;
23955 expr = BASELINK_FUNCTIONS (expr);
23958 if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
23960 int good = 0;
23961 tree goodfn = NULL_TREE;
23963 /* If we got some explicit template args, we need to plug them into
23964 the affected templates before we try to unify, in case the
23965 explicit args will completely resolve the templates in question. */
23967 tree expl_subargs = TREE_OPERAND (expr, 1);
23968 tree arg = TREE_OPERAND (expr, 0);
23969 tree badfn = NULL_TREE;
23970 tree badargs = NULL_TREE;
23972 for (lkp_iterator iter (arg); iter; ++iter)
23974 tree fn = *iter;
23975 tree subargs, elem;
23977 if (TREE_CODE (fn) != TEMPLATE_DECL)
23978 continue;
23980 subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
23981 expl_subargs, NULL_TREE, tf_none);
23982 if (subargs != error_mark_node
23983 && !any_dependent_template_arguments_p (subargs))
23985 elem = instantiate_template (fn, subargs, tf_none);
23986 if (elem == error_mark_node)
23988 badfn = fn;
23989 badargs = subargs;
23991 else if (elem && (!goodfn || !decls_match (goodfn, elem))
23992 && constraints_satisfied_p (elem))
23994 goodfn = elem;
23995 ++good;
23999 if (good == 1)
24001 mark_used (goodfn);
24002 expr = goodfn;
24003 if (baselink)
24004 expr = build_baselink (BASELINK_BINFO (baselink),
24005 BASELINK_ACCESS_BINFO (baselink),
24006 expr, BASELINK_OPTYPE (baselink));
24007 if (offset)
24009 tree base
24010 = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
24011 expr = build_offset_ref (base, expr, addr, complain);
24013 if (addr)
24014 expr = cp_build_addr_expr (expr, complain);
24015 return expr;
24017 else if (good == 0 && badargs && (complain & tf_error))
24018 /* There were no good options and at least one bad one, so let the
24019 user know what the problem is. */
24020 instantiate_template (badfn, badargs, complain);
24022 return orig_expr;
24025 /* As above, but error out if the expression remains overloaded. */
24027 tree
24028 resolve_nondeduced_context_or_error (tree exp, tsubst_flags_t complain)
24030 exp = resolve_nondeduced_context (exp, complain);
24031 if (type_unknown_p (exp))
24033 if (complain & tf_error)
24034 cxx_incomplete_type_error (exp, TREE_TYPE (exp));
24035 return error_mark_node;
24037 return exp;
24040 /* Subroutine of resolve_overloaded_unification; does deduction for a single
24041 overload. Fills TARGS with any deduced arguments, or error_mark_node if
24042 different overloads deduce different arguments for a given parm.
24043 ADDR_P is true if the expression for which deduction is being
24044 performed was of the form "& fn" rather than simply "fn".
24046 Returns 1 on success. */
24048 static int
24049 try_one_overload (tree tparms,
24050 tree orig_targs,
24051 tree targs,
24052 tree parm,
24053 tree arg,
24054 unification_kind_t strict,
24055 int sub_strict,
24056 bool addr_p,
24057 bool explain_p)
24059 int nargs;
24060 tree tempargs;
24061 int i;
24063 if (arg == error_mark_node)
24064 return 0;
24066 /* [temp.deduct.type] A template-argument can be deduced from a pointer
24067 to function or pointer to member function argument if the set of
24068 overloaded functions does not contain function templates and at most
24069 one of a set of overloaded functions provides a unique match.
24071 So if this is a template, just return success. */
24073 if (uses_template_parms (arg))
24074 return 1;
24076 if (TREE_CODE (arg) == METHOD_TYPE)
24077 arg = build_ptrmemfunc_type (build_pointer_type (arg));
24078 else if (addr_p)
24079 arg = build_pointer_type (arg);
24081 sub_strict |= maybe_adjust_types_for_deduction (tparms, strict,
24082 &parm, &arg, NULL_TREE);
24084 /* We don't copy orig_targs for this because if we have already deduced
24085 some template args from previous args, unify would complain when we
24086 try to deduce a template parameter for the same argument, even though
24087 there isn't really a conflict. */
24088 nargs = TREE_VEC_LENGTH (targs);
24089 tempargs = make_tree_vec (nargs);
24091 if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
24092 return 0;
24094 /* First make sure we didn't deduce anything that conflicts with
24095 explicitly specified args. */
24096 for (i = nargs; i--; )
24098 tree elt = TREE_VEC_ELT (tempargs, i);
24099 tree oldelt = TREE_VEC_ELT (orig_targs, i);
24101 if (!elt)
24102 /*NOP*/;
24103 else if (uses_template_parms (elt))
24104 /* Since we're unifying against ourselves, we will fill in
24105 template args used in the function parm list with our own
24106 template parms. Discard them. */
24107 TREE_VEC_ELT (tempargs, i) = NULL_TREE;
24108 else if (oldelt && ARGUMENT_PACK_P (oldelt))
24110 /* Check that the argument at each index of the deduced argument pack
24111 is equivalent to the corresponding explicitly specified argument.
24112 We may have deduced more arguments than were explicitly specified,
24113 and that's OK. */
24115 /* We used to assert ARGUMENT_PACK_INCOMPLETE_P (oldelt) here, but
24116 that's wrong if we deduce the same argument pack from multiple
24117 function arguments: it's only incomplete the first time. */
24119 tree explicit_pack = ARGUMENT_PACK_ARGS (oldelt);
24120 tree deduced_pack = ARGUMENT_PACK_ARGS (elt);
24122 if (TREE_VEC_LENGTH (deduced_pack)
24123 < TREE_VEC_LENGTH (explicit_pack))
24124 return 0;
24126 for (int j = 0; j < TREE_VEC_LENGTH (explicit_pack); j++)
24127 if (!template_args_equal (TREE_VEC_ELT (explicit_pack, j),
24128 TREE_VEC_ELT (deduced_pack, j)))
24129 return 0;
24131 else if (oldelt && !template_args_equal (oldelt, elt))
24132 return 0;
24135 for (i = nargs; i--; )
24137 tree elt = TREE_VEC_ELT (tempargs, i);
24139 if (elt)
24140 TREE_VEC_ELT (targs, i) = elt;
24143 return 1;
24146 /* PARM is a template class (perhaps with unbound template
24147 parameters). ARG is a fully instantiated type. If ARG can be
24148 bound to PARM, return ARG, otherwise return NULL_TREE. TPARMS and
24149 TARGS are as for unify. */
24151 static tree
24152 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
24153 bool explain_p)
24155 if (!CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
24156 return NULL_TREE;
24157 else if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
24158 /* Matches anything. */;
24159 else if (CLASSTYPE_TI_TEMPLATE (arg) != CLASSTYPE_TI_TEMPLATE (parm))
24160 return NULL_TREE;
24162 /* We need to make a new template argument vector for the call to
24163 unify. If we used TARGS, we'd clutter it up with the result of
24164 the attempted unification, even if this class didn't work out.
24165 We also don't want to commit ourselves to all the unifications
24166 we've already done, since unification is supposed to be done on
24167 an argument-by-argument basis. In other words, consider the
24168 following pathological case:
24170 template <int I, int J, int K>
24171 struct S {};
24173 template <int I, int J>
24174 struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
24176 template <int I, int J, int K>
24177 void f(S<I, J, K>, S<I, I, I>);
24179 void g() {
24180 S<0, 0, 0> s0;
24181 S<0, 1, 2> s2;
24183 f(s0, s2);
24186 Now, by the time we consider the unification involving `s2', we
24187 already know that we must have `f<0, 0, 0>'. But, even though
24188 `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
24189 because there are two ways to unify base classes of S<0, 1, 2>
24190 with S<I, I, I>. If we kept the already deduced knowledge, we
24191 would reject the possibility I=1. */
24192 targs = copy_template_args (targs);
24193 for (tree& targ : tree_vec_range (INNERMOST_TEMPLATE_ARGS (targs)))
24194 targ = NULL_TREE;
24196 int err;
24197 if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
24198 err = unify_bound_ttp_args (tparms, targs, parm, arg, explain_p);
24199 else
24200 err = unify (tparms, targs,
24201 INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (parm)),
24202 INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (arg)),
24203 UNIFY_ALLOW_NONE, explain_p);
24205 return err ? NULL_TREE : arg;
24208 /* Given a template type PARM and a class type ARG, find the unique
24209 base type in ARG that is an instance of PARM. We do not examine
24210 ARG itself; only its base-classes. If there is not exactly one
24211 appropriate base class, return NULL_TREE. PARM may be the type of
24212 a partial specialization, as well as a plain template type. Used
24213 by unify. */
24215 static enum template_base_result
24216 get_template_base (tree tparms, tree targs, tree parm, tree arg,
24217 bool explain_p, tree *result)
24219 tree rval = NULL_TREE;
24220 tree binfo;
24222 gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
24224 binfo = TYPE_BINFO (complete_type (arg));
24225 if (!binfo)
24227 /* The type could not be completed. */
24228 *result = NULL_TREE;
24229 return tbr_incomplete_type;
24232 /* Walk in inheritance graph order. The search order is not
24233 important, and this avoids multiple walks of virtual bases. */
24234 for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
24236 tree r = try_class_unification (tparms, targs, parm,
24237 BINFO_TYPE (binfo), explain_p);
24239 if (r)
24241 /* If there is more than one satisfactory baseclass, then:
24243 [temp.deduct.call]
24245 If they yield more than one possible deduced A, the type
24246 deduction fails.
24248 applies. */
24249 if (rval && !same_type_p (r, rval))
24251 /* [temp.deduct.call]/4.3: If there is a class C that is a
24252 (direct or indirect) base class of D and derived (directly or
24253 indirectly) from a class B and that would be a valid deduced
24254 A, the deduced A cannot be B or pointer to B, respectively. */
24255 if (DERIVED_FROM_P (r, rval))
24256 /* Ignore r. */
24257 continue;
24258 else if (DERIVED_FROM_P (rval, r))
24259 /* Ignore rval. */;
24260 else
24262 *result = NULL_TREE;
24263 return tbr_ambiguous_baseclass;
24267 rval = r;
24271 *result = rval;
24272 return tbr_success;
24275 /* Returns the level of DECL, which declares a template parameter. */
24277 static int
24278 template_decl_level (tree decl)
24280 switch (TREE_CODE (decl))
24282 case TYPE_DECL:
24283 case TEMPLATE_DECL:
24284 return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
24286 case PARM_DECL:
24287 return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
24289 default:
24290 gcc_unreachable ();
24292 return 0;
24295 /* Decide whether ARG can be unified with PARM, considering only the
24296 cv-qualifiers of each type, given STRICT as documented for unify.
24297 Returns nonzero iff the unification is OK on that basis. */
24299 static int
24300 check_cv_quals_for_unify (int strict, tree arg, tree parm)
24302 int arg_quals = cp_type_quals (arg);
24303 int parm_quals = cp_type_quals (parm);
24305 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
24306 && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
24308 /* Although a CVR qualifier is ignored when being applied to a
24309 substituted template parameter ([8.3.2]/1 for example), that
24310 does not allow us to unify "const T" with "int&" because both
24311 types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
24312 It is ok when we're allowing additional CV qualifiers
24313 at the outer level [14.8.2.1]/3,1st bullet. */
24314 if ((TYPE_REF_P (arg)
24315 || FUNC_OR_METHOD_TYPE_P (arg))
24316 && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
24317 return 0;
24319 if ((!INDIRECT_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
24320 && (parm_quals & TYPE_QUAL_RESTRICT))
24321 return 0;
24324 if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
24325 && (arg_quals & parm_quals) != parm_quals)
24326 return 0;
24328 if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
24329 && (parm_quals & arg_quals) != arg_quals)
24330 return 0;
24332 return 1;
24335 /* Determines the LEVEL and INDEX for the template parameter PARM. */
24336 void
24337 template_parm_level_and_index (tree parm, int* level, int* index)
24339 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
24340 || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
24341 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
24343 *index = TEMPLATE_TYPE_IDX (parm);
24344 *level = TEMPLATE_TYPE_LEVEL (parm);
24346 else
24348 *index = TEMPLATE_PARM_IDX (parm);
24349 *level = TEMPLATE_PARM_LEVEL (parm);
24353 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP) \
24354 do { \
24355 if (unify (TP, TA, P, A, S, EP)) \
24356 return 1; \
24357 } while (0)
24359 /* Unifies the remaining arguments in PACKED_ARGS with the pack
24360 expansion at the end of PACKED_PARMS. Returns 0 if the type
24361 deduction succeeds, 1 otherwise. STRICT is the same as in
24362 fn_type_unification. CALL_ARGS_P is true iff PACKED_ARGS is actually a
24363 function call argument list. We'll need to adjust the arguments to make them
24364 types. SUBR tells us if this is from a recursive call to
24365 type_unification_real, or for comparing two template argument
24366 lists. */
24368 static int
24369 unify_pack_expansion (tree tparms, tree targs, tree packed_parms,
24370 tree packed_args, unification_kind_t strict,
24371 bool subr, bool explain_p)
24373 tree parm
24374 = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
24375 tree pattern = PACK_EXPANSION_PATTERN (parm);
24376 tree pack, packs = NULL_TREE;
24377 int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
24379 /* Add in any args remembered from an earlier partial instantiation. */
24380 targs = add_to_template_args (PACK_EXPANSION_EXTRA_ARGS (parm), targs);
24381 int levels = TMPL_ARGS_DEPTH (targs);
24383 packed_args = expand_template_argument_pack (packed_args);
24385 int len = TREE_VEC_LENGTH (packed_args);
24387 /* Determine the parameter packs we will be deducing from the
24388 pattern, and record their current deductions. */
24389 for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm);
24390 pack; pack = TREE_CHAIN (pack))
24392 tree parm_pack = TREE_VALUE (pack);
24393 int idx, level;
24395 /* Only template parameter packs can be deduced, not e.g. function
24396 parameter packs or __bases or __integer_pack. */
24397 if (!TEMPLATE_PARM_P (parm_pack))
24398 continue;
24400 /* Determine the index and level of this parameter pack. */
24401 template_parm_level_and_index (parm_pack, &level, &idx);
24402 if (level > levels)
24403 continue;
24405 /* Keep track of the parameter packs and their corresponding
24406 argument packs. */
24407 packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
24408 TREE_TYPE (packs) = make_tree_vec (len - start);
24411 /* Loop through all of the arguments that have not yet been
24412 unified and unify each with the pattern. */
24413 for (i = start; i < len; i++)
24415 tree parm;
24416 bool any_explicit = false;
24417 tree arg = TREE_VEC_ELT (packed_args, i);
24419 /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
24420 or the element of its argument pack at the current index if
24421 this argument was explicitly specified. */
24422 for (pack = packs; pack; pack = TREE_CHAIN (pack))
24424 int idx, level;
24425 tree arg, pargs;
24426 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
24428 arg = NULL_TREE;
24429 if (TREE_VALUE (pack)
24430 && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
24431 && (i - start < TREE_VEC_LENGTH (pargs)))
24433 any_explicit = true;
24434 arg = TREE_VEC_ELT (pargs, i - start);
24436 TMPL_ARG (targs, level, idx) = arg;
24439 /* If we had explicit template arguments, substitute them into the
24440 pattern before deduction. */
24441 if (any_explicit)
24443 /* Some arguments might still be unspecified or dependent. */
24444 bool dependent;
24445 ++processing_template_decl;
24446 dependent = any_dependent_template_arguments_p (targs);
24447 if (!dependent)
24448 --processing_template_decl;
24449 parm = tsubst (pattern, targs,
24450 explain_p ? tf_warning_or_error : tf_none,
24451 NULL_TREE);
24452 if (dependent)
24453 --processing_template_decl;
24454 if (parm == error_mark_node)
24455 return 1;
24457 else
24458 parm = pattern;
24460 /* Unify the pattern with the current argument. */
24461 if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
24462 explain_p))
24463 return 1;
24465 /* For each parameter pack, collect the deduced value. */
24466 for (pack = packs; pack; pack = TREE_CHAIN (pack))
24468 int idx, level;
24469 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
24471 TREE_VEC_ELT (TREE_TYPE (pack), i - start) =
24472 TMPL_ARG (targs, level, idx);
24476 /* Verify that the results of unification with the parameter packs
24477 produce results consistent with what we've seen before, and make
24478 the deduced argument packs available. */
24479 for (pack = packs; pack; pack = TREE_CHAIN (pack))
24481 tree old_pack = TREE_VALUE (pack);
24482 tree new_args = TREE_TYPE (pack);
24483 int i, len = TREE_VEC_LENGTH (new_args);
24484 int idx, level;
24485 bool nondeduced_p = false;
24487 /* By default keep the original deduced argument pack.
24488 If necessary, more specific code is going to update the
24489 resulting deduced argument later down in this function. */
24490 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
24491 TMPL_ARG (targs, level, idx) = old_pack;
24493 /* If NEW_ARGS contains any NULL_TREE entries, we didn't
24494 actually deduce anything. */
24495 for (i = 0; i < len && !nondeduced_p; ++i)
24496 if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
24497 nondeduced_p = true;
24498 if (nondeduced_p)
24499 continue;
24501 if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
24503 /* If we had fewer function args than explicit template args,
24504 just use the explicits. */
24505 tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
24506 int explicit_len = TREE_VEC_LENGTH (explicit_args);
24507 if (len < explicit_len)
24508 new_args = explicit_args;
24511 if (!old_pack)
24513 tree result;
24514 /* Build the deduced *_ARGUMENT_PACK. */
24515 if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
24517 result = make_node (NONTYPE_ARGUMENT_PACK);
24518 TREE_CONSTANT (result) = 1;
24520 else
24521 result = cxx_make_type (TYPE_ARGUMENT_PACK);
24523 ARGUMENT_PACK_ARGS (result) = new_args;
24525 /* Note the deduced argument packs for this parameter
24526 pack. */
24527 TMPL_ARG (targs, level, idx) = result;
24529 else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
24530 && (ARGUMENT_PACK_ARGS (old_pack)
24531 == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
24533 /* We only had the explicitly-provided arguments before, but
24534 now we have a complete set of arguments. */
24535 tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
24537 ARGUMENT_PACK_ARGS (old_pack) = new_args;
24538 ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
24539 ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
24541 else
24543 tree bad_old_arg = NULL_TREE, bad_new_arg = NULL_TREE;
24544 tree old_args = ARGUMENT_PACK_ARGS (old_pack);
24545 temp_override<int> ovl (TREE_VEC_LENGTH (old_args));
24546 /* During template argument deduction for the aggregate deduction
24547 candidate, the number of elements in a trailing parameter pack
24548 is only deduced from the number of remaining function
24549 arguments if it is not otherwise deduced. */
24550 if (cxx_dialect >= cxx20
24551 && TREE_VEC_LENGTH (new_args) < TREE_VEC_LENGTH (old_args)
24552 /* FIXME This isn't set properly for partial instantiations. */
24553 && TPARMS_PRIMARY_TEMPLATE (tparms)
24554 && builtin_guide_p (TPARMS_PRIMARY_TEMPLATE (tparms)))
24555 TREE_VEC_LENGTH (old_args) = TREE_VEC_LENGTH (new_args);
24556 if (!comp_template_args (old_args, new_args,
24557 &bad_old_arg, &bad_new_arg))
24558 /* Inconsistent unification of this parameter pack. */
24559 return unify_parameter_pack_inconsistent (explain_p,
24560 bad_old_arg,
24561 bad_new_arg);
24565 return unify_success (explain_p);
24568 /* Handle unification of the domain of an array. PARM_DOM and ARG_DOM are
24569 INTEGER_TYPEs representing the TYPE_DOMAIN of ARRAY_TYPEs. The other
24570 parameters and return value are as for unify. */
24572 static int
24573 unify_array_domain (tree tparms, tree targs,
24574 tree parm_dom, tree arg_dom,
24575 bool explain_p)
24577 tree parm_max;
24578 tree arg_max;
24579 bool parm_cst;
24580 bool arg_cst;
24582 /* Our representation of array types uses "N - 1" as the
24583 TYPE_MAX_VALUE for an array with "N" elements, if "N" is
24584 not an integer constant. We cannot unify arbitrarily
24585 complex expressions, so we eliminate the MINUS_EXPRs
24586 here. */
24587 parm_max = TYPE_MAX_VALUE (parm_dom);
24588 parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
24589 if (!parm_cst)
24591 gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
24592 parm_max = TREE_OPERAND (parm_max, 0);
24594 arg_max = TYPE_MAX_VALUE (arg_dom);
24595 arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
24596 if (!arg_cst)
24598 /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
24599 trying to unify the type of a variable with the type
24600 of a template parameter. For example:
24602 template <unsigned int N>
24603 void f (char (&) [N]);
24604 int g();
24605 void h(int i) {
24606 char a[g(i)];
24607 f(a);
24610 Here, the type of the ARG will be "int [g(i)]", and
24611 may be a SAVE_EXPR, etc. */
24612 if (TREE_CODE (arg_max) != MINUS_EXPR)
24613 return unify_vla_arg (explain_p, arg_dom);
24614 arg_max = TREE_OPERAND (arg_max, 0);
24617 /* If only one of the bounds used a MINUS_EXPR, compensate
24618 by adding one to the other bound. */
24619 if (parm_cst && !arg_cst)
24620 parm_max = fold_build2_loc (input_location, PLUS_EXPR,
24621 integer_type_node,
24622 parm_max,
24623 integer_one_node);
24624 else if (arg_cst && !parm_cst)
24625 arg_max = fold_build2_loc (input_location, PLUS_EXPR,
24626 integer_type_node,
24627 arg_max,
24628 integer_one_node);
24630 return unify (tparms, targs, parm_max, arg_max,
24631 UNIFY_ALLOW_INTEGER, explain_p);
24634 /* Returns whether T, a P or A in unify, is a type, template or expression. */
24636 enum pa_kind_t { pa_type, pa_tmpl, pa_expr };
24638 static pa_kind_t
24639 pa_kind (tree t)
24641 if (PACK_EXPANSION_P (t))
24642 t = PACK_EXPANSION_PATTERN (t);
24643 if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM
24644 || TREE_CODE (t) == UNBOUND_CLASS_TEMPLATE
24645 || DECL_TYPE_TEMPLATE_P (t))
24646 return pa_tmpl;
24647 else if (TYPE_P (t))
24648 return pa_type;
24649 else
24650 return pa_expr;
24653 /* Deduce the value of template parameters. TPARMS is the (innermost)
24654 set of template parameters to a template. TARGS is the bindings
24655 for those template parameters, as determined thus far; TARGS may
24656 include template arguments for outer levels of template parameters
24657 as well. PARM is a parameter to a template function, or a
24658 subcomponent of that parameter; ARG is the corresponding argument.
24659 This function attempts to match PARM with ARG in a manner
24660 consistent with the existing assignments in TARGS. If more values
24661 are deduced, then TARGS is updated.
24663 Returns 0 if the type deduction succeeds, 1 otherwise. The
24664 parameter STRICT is a bitwise or of the following flags:
24666 UNIFY_ALLOW_NONE:
24667 Require an exact match between PARM and ARG.
24668 UNIFY_ALLOW_MORE_CV_QUAL:
24669 Allow the deduced ARG to be more cv-qualified (by qualification
24670 conversion) than ARG.
24671 UNIFY_ALLOW_LESS_CV_QUAL:
24672 Allow the deduced ARG to be less cv-qualified than ARG.
24673 UNIFY_ALLOW_DERIVED:
24674 Allow the deduced ARG to be a template base class of ARG,
24675 or a pointer to a template base class of the type pointed to by
24676 ARG.
24677 UNIFY_ALLOW_INTEGER:
24678 Allow any integral type to be deduced. See the TEMPLATE_PARM_INDEX
24679 case for more information.
24680 UNIFY_ALLOW_OUTER_LEVEL:
24681 This is the outermost level of a deduction. Used to determine validity
24682 of qualification conversions. A valid qualification conversion must
24683 have const qualified pointers leading up to the inner type which
24684 requires additional CV quals, except at the outer level, where const
24685 is not required [conv.qual]. It would be normal to set this flag in
24686 addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
24687 UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
24688 This is the outermost level of a deduction, and PARM can be more CV
24689 qualified at this point.
24690 UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
24691 This is the outermost level of a deduction, and PARM can be less CV
24692 qualified at this point. */
24694 static int
24695 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
24696 bool explain_p)
24698 int idx;
24699 tree targ;
24700 tree tparm;
24701 int strict_in = strict;
24702 tsubst_flags_t complain = (explain_p
24703 ? tf_warning_or_error
24704 : tf_none);
24706 /* I don't think this will do the right thing with respect to types.
24707 But the only case I've seen it in so far has been array bounds, where
24708 signedness is the only information lost, and I think that will be
24709 okay. VIEW_CONVERT_EXPR can appear with class NTTP, thanks to
24710 finish_id_expression_1, and are also OK. */
24711 while (CONVERT_EXPR_P (parm) || TREE_CODE (parm) == VIEW_CONVERT_EXPR
24712 || TREE_CODE (parm) == IMPLICIT_CONV_EXPR)
24713 parm = TREE_OPERAND (parm, 0);
24715 if (arg == error_mark_node)
24716 return unify_invalid (explain_p);
24717 if (arg == unknown_type_node
24718 || arg == init_list_type_node)
24719 /* We can't deduce anything from this, but we might get all the
24720 template args from other function args. */
24721 return unify_success (explain_p);
24723 if (parm == any_targ_node || arg == any_targ_node)
24724 return unify_success (explain_p);
24726 /* Stripping IMPLICIT_CONV_EXPR above can produce this mismatch
24727 (g++.dg/abi/mangle57.C). */
24728 if (TREE_CODE (parm) == FUNCTION_DECL
24729 && TREE_CODE (arg) == ADDR_EXPR)
24730 arg = TREE_OPERAND (arg, 0);
24732 /* If PARM uses template parameters, then we can't bail out here,
24733 even if ARG == PARM, since we won't record unifications for the
24734 template parameters. We might need them if we're trying to
24735 figure out which of two things is more specialized. */
24736 if (arg == parm
24737 && (DECL_P (parm) || !uses_template_parms (parm)))
24738 return unify_success (explain_p);
24740 /* Handle init lists early, so the rest of the function can assume
24741 we're dealing with a type. */
24742 if (BRACE_ENCLOSED_INITIALIZER_P (arg))
24744 tree elttype;
24745 tree orig_parm = parm;
24747 if (!is_std_init_list (parm)
24748 && TREE_CODE (parm) != ARRAY_TYPE)
24749 /* We can only deduce from an initializer list argument if the
24750 parameter is std::initializer_list or an array; otherwise this
24751 is a non-deduced context. */
24752 return unify_success (explain_p);
24754 if (TREE_CODE (parm) == ARRAY_TYPE)
24755 elttype = TREE_TYPE (parm);
24756 else
24758 elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
24759 /* Deduction is defined in terms of a single type, so just punt
24760 on the (bizarre) std::initializer_list<T...>. */
24761 if (PACK_EXPANSION_P (elttype))
24762 return unify_success (explain_p);
24765 if (strict != DEDUCE_EXACT
24766 && TYPE_P (elttype)
24767 && !uses_deducible_template_parms (elttype))
24768 /* If ELTTYPE has no deducible template parms, skip deduction from
24769 the list elements. */;
24770 else
24771 for (auto &e: CONSTRUCTOR_ELTS (arg))
24773 tree elt = e.value;
24774 int elt_strict = strict;
24776 if (elt == error_mark_node)
24777 return unify_invalid (explain_p);
24779 if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
24781 tree type = TREE_TYPE (elt);
24782 if (type == error_mark_node)
24783 return unify_invalid (explain_p);
24784 /* It should only be possible to get here for a call. */
24785 gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
24786 elt_strict |= maybe_adjust_types_for_deduction
24787 (tparms, DEDUCE_CALL, &elttype, &type, elt);
24788 elt = type;
24791 RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
24792 explain_p);
24795 if (TREE_CODE (parm) == ARRAY_TYPE
24796 && deducible_array_bound (TYPE_DOMAIN (parm)))
24798 /* Also deduce from the length of the initializer list. */
24799 tree max = size_int (CONSTRUCTOR_NELTS (arg));
24800 tree idx = compute_array_index_type (NULL_TREE, max, tf_none);
24801 if (idx == error_mark_node)
24802 return unify_invalid (explain_p);
24803 return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
24804 idx, explain_p);
24807 /* If the std::initializer_list<T> deduction worked, replace the
24808 deduced A with std::initializer_list<A>. */
24809 if (orig_parm != parm)
24811 idx = TEMPLATE_TYPE_IDX (orig_parm);
24812 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
24813 targ = listify (targ);
24814 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
24816 return unify_success (explain_p);
24819 /* If parm and arg aren't the same kind of thing (template, type, or
24820 expression), fail early. */
24821 if (pa_kind (parm) != pa_kind (arg))
24822 return unify_invalid (explain_p);
24824 /* Immediately reject some pairs that won't unify because of
24825 cv-qualification mismatches. */
24826 if (TREE_CODE (arg) == TREE_CODE (parm)
24827 && TYPE_P (arg)
24828 /* It is the elements of the array which hold the cv quals of an array
24829 type, and the elements might be template type parms. We'll check
24830 when we recurse. */
24831 && TREE_CODE (arg) != ARRAY_TYPE
24832 /* We check the cv-qualifiers when unifying with template type
24833 parameters below. We want to allow ARG `const T' to unify with
24834 PARM `T' for example, when computing which of two templates
24835 is more specialized, for example. */
24836 && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
24837 && !check_cv_quals_for_unify (strict_in, arg, parm))
24838 return unify_cv_qual_mismatch (explain_p, parm, arg);
24840 if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
24841 && TYPE_P (parm) && !CP_TYPE_CONST_P (parm)
24842 && !FUNC_OR_METHOD_TYPE_P (parm))
24843 strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
24844 /* PMFs recurse at the same level, so don't strip this yet. */
24845 if (!TYPE_PTRMEMFUNC_P (parm))
24846 strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
24847 strict &= ~UNIFY_ALLOW_DERIVED;
24848 strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
24849 strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
24851 switch (TREE_CODE (parm))
24853 case TYPENAME_TYPE:
24854 case SCOPE_REF:
24855 case UNBOUND_CLASS_TEMPLATE:
24856 /* In a type which contains a nested-name-specifier, template
24857 argument values cannot be deduced for template parameters used
24858 within the nested-name-specifier. */
24859 return unify_success (explain_p);
24861 case TEMPLATE_TYPE_PARM:
24862 case TEMPLATE_TEMPLATE_PARM:
24863 case BOUND_TEMPLATE_TEMPLATE_PARM:
24864 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
24865 if (error_operand_p (tparm))
24866 return unify_invalid (explain_p);
24868 if (TEMPLATE_TYPE_LEVEL (parm)
24869 != template_decl_level (tparm))
24870 /* The PARM is not one we're trying to unify. Just check
24871 to see if it matches ARG. */
24873 if (TREE_CODE (arg) == TREE_CODE (parm)
24874 && (is_auto (parm) ? is_auto (arg)
24875 : same_type_p (parm, arg)))
24876 return unify_success (explain_p);
24877 else
24878 return unify_type_mismatch (explain_p, parm, arg);
24880 idx = TEMPLATE_TYPE_IDX (parm);
24881 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
24882 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
24883 if (error_operand_p (tparm))
24884 return unify_invalid (explain_p);
24886 /* Check for mixed types and values. */
24887 if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
24888 && TREE_CODE (tparm) != TYPE_DECL)
24889 || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
24890 && TREE_CODE (tparm) != TEMPLATE_DECL))
24891 gcc_unreachable ();
24893 if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
24895 if ((strict_in & UNIFY_ALLOW_DERIVED)
24896 && CLASS_TYPE_P (arg))
24898 /* First try to match ARG directly. */
24899 tree t = try_class_unification (tparms, targs, parm, arg,
24900 explain_p);
24901 if (!t)
24903 /* Otherwise, look for a suitable base of ARG, as below. */
24904 enum template_base_result r;
24905 r = get_template_base (tparms, targs, parm, arg,
24906 explain_p, &t);
24907 if (!t)
24908 return unify_no_common_base (explain_p, r, parm, arg);
24909 arg = t;
24912 /* ARG must be constructed from a template class or a template
24913 template parameter. */
24914 else if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
24915 && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
24916 return unify_template_deduction_failure (explain_p, parm, arg);
24918 /* Deduce arguments T, i from TT<T> or TT<i>. */
24919 if (unify_bound_ttp_args (tparms, targs, parm, arg, explain_p))
24920 return 1;
24922 arg = TYPE_TI_TEMPLATE (arg);
24923 if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg))
24924 /* If the template is a template template parameter, use the
24925 TEMPLATE_TEMPLATE_PARM for matching. */
24926 arg = TREE_TYPE (arg);
24928 /* Fall through to deduce template name. */
24931 if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
24932 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
24934 /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>. */
24936 /* Simple cases: Value already set, does match or doesn't. */
24937 if (targ != NULL_TREE && template_args_equal (targ, arg))
24938 return unify_success (explain_p);
24939 else if (targ)
24940 return unify_inconsistency (explain_p, parm, targ, arg);
24942 else
24944 /* If PARM is `const T' and ARG is only `int', we don't have
24945 a match unless we are allowing additional qualification.
24946 If ARG is `const int' and PARM is just `T' that's OK;
24947 that binds `const int' to `T'. */
24948 if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
24949 arg, parm))
24950 return unify_cv_qual_mismatch (explain_p, parm, arg);
24952 /* Consider the case where ARG is `const volatile int' and
24953 PARM is `const T'. Then, T should be `volatile int'. */
24954 arg = cp_build_qualified_type
24955 (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
24956 if (arg == error_mark_node)
24957 return unify_invalid (explain_p);
24959 /* Simple cases: Value already set, does match or doesn't. */
24960 if (targ != NULL_TREE && same_type_p (targ, arg))
24961 return unify_success (explain_p);
24962 else if (targ)
24963 return unify_inconsistency (explain_p, parm, targ, arg);
24965 /* Make sure that ARG is not a variable-sized array. (Note
24966 that were talking about variable-sized arrays (like
24967 `int[n]'), rather than arrays of unknown size (like
24968 `int[]').) We'll get very confused by such a type since
24969 the bound of the array is not constant, and therefore
24970 not mangleable. Besides, such types are not allowed in
24971 ISO C++, so we can do as we please here. We do allow
24972 them for 'auto' deduction, since that isn't ABI-exposed. */
24973 if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
24974 return unify_vla_arg (explain_p, arg);
24976 /* Strip typedefs as in convert_template_argument. */
24977 arg = canonicalize_type_argument (arg, tf_none);
24980 /* If ARG is a parameter pack or an expansion, we cannot unify
24981 against it unless PARM is also a parameter pack. */
24982 if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
24983 && !template_parameter_pack_p (parm))
24984 return unify_parameter_pack_mismatch (explain_p, parm, arg);
24986 /* If the argument deduction results is a METHOD_TYPE,
24987 then there is a problem.
24988 METHOD_TYPE doesn't map to any real C++ type the result of
24989 the deduction cannot be of that type. */
24990 if (TREE_CODE (arg) == METHOD_TYPE)
24991 return unify_method_type_error (explain_p, arg);
24993 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
24994 return unify_success (explain_p);
24996 case TEMPLATE_PARM_INDEX:
24997 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
24998 if (error_operand_p (tparm))
24999 return unify_invalid (explain_p);
25001 if (TEMPLATE_PARM_LEVEL (parm)
25002 != template_decl_level (tparm))
25004 /* The PARM is not one we're trying to unify. Just check
25005 to see if it matches ARG. */
25006 int result = !(TREE_CODE (arg) == TREE_CODE (parm)
25007 && cp_tree_equal (parm, arg));
25008 if (result)
25009 unify_expression_unequal (explain_p, parm, arg);
25010 return result;
25013 idx = TEMPLATE_PARM_IDX (parm);
25014 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
25016 if (targ)
25018 if ((strict & UNIFY_ALLOW_INTEGER)
25019 && TREE_TYPE (targ) && TREE_TYPE (arg)
25020 && CP_INTEGRAL_TYPE_P (TREE_TYPE (targ)))
25021 /* We're deducing from an array bound, the type doesn't matter.
25022 This conversion should match the one below. */
25023 arg = fold (build_nop (TREE_TYPE (targ), arg));
25024 int x = !cp_tree_equal (targ, arg);
25025 if (x)
25026 unify_inconsistency (explain_p, parm, targ, arg);
25027 return x;
25030 /* [temp.deduct.type] If, in the declaration of a function template
25031 with a non-type template-parameter, the non-type
25032 template-parameter is used in an expression in the function
25033 parameter-list and, if the corresponding template-argument is
25034 deduced, the template-argument type shall match the type of the
25035 template-parameter exactly, except that a template-argument
25036 deduced from an array bound may be of any integral type.
25037 The non-type parameter might use already deduced type parameters. */
25038 tparm = TREE_TYPE (parm);
25039 if (TEMPLATE_PARM_LEVEL (parm) > TMPL_ARGS_DEPTH (targs))
25040 /* We don't have enough levels of args to do any substitution. This
25041 can happen in the context of -fnew-ttp-matching. */;
25042 else
25044 ++processing_template_decl;
25045 tparm = tsubst (tparm, targs, tf_none, NULL_TREE);
25046 --processing_template_decl;
25048 if (tree a = type_uses_auto (tparm))
25050 tparm = do_auto_deduction (tparm, arg, a,
25051 complain, adc_unify, targs,
25052 LOOKUP_NORMAL,
25053 TPARMS_PRIMARY_TEMPLATE (tparms));
25054 if (tparm == error_mark_node)
25055 return 1;
25059 if (!TREE_TYPE (arg)
25060 || TREE_CODE (TREE_TYPE (arg)) == DEPENDENT_OPERATOR_TYPE)
25061 /* Template-parameter dependent expression. Just accept it for now.
25062 It will later be processed in convert_template_argument. */
25064 else if (same_type_ignoring_top_level_qualifiers_p
25065 (non_reference (TREE_TYPE (arg)),
25066 non_reference (tparm)))
25067 /* OK. Ignore top-level quals here because a class-type template
25068 parameter object is const. */;
25069 else if ((strict & UNIFY_ALLOW_INTEGER)
25070 && CP_INTEGRAL_TYPE_P (tparm))
25071 /* Convert the ARG to the type of PARM; the deduced non-type
25072 template argument must exactly match the types of the
25073 corresponding parameter. This conversion should match the
25074 one above. */
25075 arg = fold (build_nop (tparm, arg));
25076 else if (uses_template_parms (tparm))
25078 /* We haven't deduced the type of this parameter yet. */
25079 if (cxx_dialect >= cxx17
25080 /* We deduce from array bounds in try_array_deduction. */
25081 && !(strict & UNIFY_ALLOW_INTEGER)
25082 && TEMPLATE_PARM_LEVEL (parm) <= TMPL_ARGS_DEPTH (targs))
25084 /* Deduce it from the non-type argument. As above, ignore
25085 top-level quals here too. */
25086 tree atype = cv_unqualified (TREE_TYPE (arg));
25087 RECUR_AND_CHECK_FAILURE (tparms, targs,
25088 tparm, atype,
25089 UNIFY_ALLOW_NONE, explain_p);
25090 /* Now check whether the type of this parameter is still
25091 dependent, and give up if so. */
25092 ++processing_template_decl;
25093 tparm = tsubst (TREE_TYPE (parm), targs, tf_none, NULL_TREE);
25094 --processing_template_decl;
25095 if (uses_template_parms (tparm))
25096 return unify_success (explain_p);
25098 else
25099 /* Try again later. */
25100 return unify_success (explain_p);
25102 else
25103 return unify_type_mismatch (explain_p, tparm, TREE_TYPE (arg));
25105 /* If ARG is a parameter pack or an expansion, we cannot unify
25106 against it unless PARM is also a parameter pack. */
25107 if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
25108 && !TEMPLATE_PARM_PARAMETER_PACK (parm))
25109 return unify_parameter_pack_mismatch (explain_p, parm, arg);
25112 bool removed_attr = false;
25113 arg = strip_typedefs_expr (arg, &removed_attr);
25115 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
25116 return unify_success (explain_p);
25118 case PTRMEM_CST:
25120 /* A pointer-to-member constant can be unified only with
25121 another constant. */
25122 if (TREE_CODE (arg) != PTRMEM_CST)
25123 return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
25125 /* Just unify the class member. It would be useless (and possibly
25126 wrong, depending on the strict flags) to unify also
25127 PTRMEM_CST_CLASS, because we want to be sure that both parm and
25128 arg refer to the same variable, even if through different
25129 classes. For instance:
25131 struct A { int x; };
25132 struct B : A { };
25134 Unification of &A::x and &B::x must succeed. */
25135 return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
25136 PTRMEM_CST_MEMBER (arg), strict, explain_p);
25139 case POINTER_TYPE:
25141 if (!TYPE_PTR_P (arg))
25142 return unify_type_mismatch (explain_p, parm, arg);
25144 /* [temp.deduct.call]
25146 A can be another pointer or pointer to member type that can
25147 be converted to the deduced A via a qualification
25148 conversion (_conv.qual_).
25150 We pass down STRICT here rather than UNIFY_ALLOW_NONE.
25151 This will allow for additional cv-qualification of the
25152 pointed-to types if appropriate. */
25154 if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
25155 /* The derived-to-base conversion only persists through one
25156 level of pointers. */
25157 strict |= (strict_in & UNIFY_ALLOW_DERIVED);
25159 return unify (tparms, targs, TREE_TYPE (parm),
25160 TREE_TYPE (arg), strict, explain_p);
25163 case REFERENCE_TYPE:
25164 if (!TYPE_REF_P (arg)
25165 || TYPE_REF_IS_RVALUE (parm) != TYPE_REF_IS_RVALUE (arg))
25166 return unify_type_mismatch (explain_p, parm, arg);
25167 return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
25168 strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
25170 case ARRAY_TYPE:
25171 if (TREE_CODE (arg) != ARRAY_TYPE)
25172 return unify_type_mismatch (explain_p, parm, arg);
25173 if ((TYPE_DOMAIN (parm) == NULL_TREE)
25174 != (TYPE_DOMAIN (arg) == NULL_TREE))
25175 return unify_type_mismatch (explain_p, parm, arg);
25176 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
25177 strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
25178 if (TYPE_DOMAIN (parm) != NULL_TREE)
25179 return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
25180 TYPE_DOMAIN (arg), explain_p);
25181 return unify_success (explain_p);
25183 case REAL_TYPE:
25184 case COMPLEX_TYPE:
25185 case VECTOR_TYPE:
25186 case INTEGER_TYPE:
25187 case BOOLEAN_TYPE:
25188 case ENUMERAL_TYPE:
25189 case VOID_TYPE:
25190 case OPAQUE_TYPE:
25191 case NULLPTR_TYPE:
25192 if (TREE_CODE (arg) != TREE_CODE (parm))
25193 return unify_type_mismatch (explain_p, parm, arg);
25195 /* We have already checked cv-qualification at the top of the
25196 function. */
25197 if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
25198 return unify_type_mismatch (explain_p, parm, arg);
25200 /* As far as unification is concerned, this wins. Later checks
25201 will invalidate it if necessary. */
25202 return unify_success (explain_p);
25204 /* Types INTEGER_CST and MINUS_EXPR can come from array bounds. */
25205 /* Type INTEGER_CST can come from ordinary constant template args. */
25206 case INTEGER_CST:
25207 case REAL_CST:
25208 if (TREE_TYPE (arg) == NULL_TREE
25209 || !same_type_p (TREE_TYPE (parm), TREE_TYPE (arg)))
25210 return unify_template_argument_mismatch (explain_p, parm, arg);
25211 while (CONVERT_EXPR_P (arg))
25212 arg = TREE_OPERAND (arg, 0);
25214 if (TREE_CODE (arg) != TREE_CODE (parm))
25215 return unify_template_argument_mismatch (explain_p, parm, arg);
25216 return (simple_cst_equal (parm, arg)
25217 ? unify_success (explain_p)
25218 : unify_template_argument_mismatch (explain_p, parm, arg));
25220 case TREE_VEC:
25222 int i, len, argslen;
25223 int parm_variadic_p = 0;
25225 if (TREE_CODE (arg) != TREE_VEC)
25226 return unify_template_argument_mismatch (explain_p, parm, arg);
25228 len = TREE_VEC_LENGTH (parm);
25229 argslen = TREE_VEC_LENGTH (arg);
25231 /* Check for pack expansions in the parameters. */
25232 for (i = 0; i < len; ++i)
25234 if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
25236 if (i == len - 1)
25237 /* We can unify against something with a trailing
25238 parameter pack. */
25239 parm_variadic_p = 1;
25240 else
25241 /* [temp.deduct.type]/9: If the template argument list of
25242 P contains a pack expansion that is not the last
25243 template argument, the entire template argument list
25244 is a non-deduced context. */
25245 return unify_success (explain_p);
25249 /* If we don't have enough arguments to satisfy the parameters
25250 (not counting the pack expression at the end), or we have
25251 too many arguments for a parameter list that doesn't end in
25252 a pack expression, we can't unify. */
25253 if (parm_variadic_p
25254 ? argslen < len - parm_variadic_p
25255 : argslen != len)
25256 return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
25258 /* Unify all of the parameters that precede the (optional)
25259 pack expression. */
25260 for (i = 0; i < len - parm_variadic_p; ++i)
25262 RECUR_AND_CHECK_FAILURE (tparms, targs,
25263 TREE_VEC_ELT (parm, i),
25264 TREE_VEC_ELT (arg, i),
25265 UNIFY_ALLOW_NONE, explain_p);
25267 if (parm_variadic_p)
25268 return unify_pack_expansion (tparms, targs, parm, arg,
25269 DEDUCE_EXACT,
25270 /*subr=*/true, explain_p);
25271 return unify_success (explain_p);
25274 case RECORD_TYPE:
25275 case UNION_TYPE:
25276 if (TREE_CODE (arg) != TREE_CODE (parm))
25277 return unify_type_mismatch (explain_p, parm, arg);
25279 if (TYPE_PTRMEMFUNC_P (parm))
25281 if (!TYPE_PTRMEMFUNC_P (arg))
25282 return unify_type_mismatch (explain_p, parm, arg);
25284 return unify (tparms, targs,
25285 TYPE_PTRMEMFUNC_FN_TYPE (parm),
25286 TYPE_PTRMEMFUNC_FN_TYPE (arg),
25287 strict, explain_p);
25289 else if (TYPE_PTRMEMFUNC_P (arg))
25290 return unify_type_mismatch (explain_p, parm, arg);
25292 if (CLASSTYPE_TEMPLATE_INFO (parm))
25294 tree t = NULL_TREE;
25296 if (strict_in & UNIFY_ALLOW_DERIVED)
25298 /* First, we try to unify the PARM and ARG directly. */
25299 t = try_class_unification (tparms, targs,
25300 parm, arg, explain_p);
25302 if (!t)
25304 /* Fallback to the special case allowed in
25305 [temp.deduct.call]:
25307 If P is a class, and P has the form
25308 template-id, then A can be a derived class of
25309 the deduced A. Likewise, if P is a pointer to
25310 a class of the form template-id, A can be a
25311 pointer to a derived class pointed to by the
25312 deduced A. */
25313 enum template_base_result r;
25314 r = get_template_base (tparms, targs, parm, arg,
25315 explain_p, &t);
25317 if (!t)
25319 /* Don't give the derived diagnostic if we're
25320 already dealing with the same template. */
25321 bool same_template
25322 = (CLASSTYPE_TEMPLATE_INFO (arg)
25323 && (CLASSTYPE_TI_TEMPLATE (parm)
25324 == CLASSTYPE_TI_TEMPLATE (arg)));
25325 return unify_no_common_base (explain_p && !same_template,
25326 r, parm, arg);
25330 else if (CLASSTYPE_TEMPLATE_INFO (arg)
25331 && (CLASSTYPE_TI_TEMPLATE (parm)
25332 == CLASSTYPE_TI_TEMPLATE (arg)))
25333 /* Perhaps PARM is something like S<U> and ARG is S<int>.
25334 Then, we should unify `int' and `U'. */
25335 t = arg;
25336 else
25337 /* There's no chance of unification succeeding. */
25338 return unify_type_mismatch (explain_p, parm, arg);
25340 if (PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)))
25341 return unify (tparms, targs,
25342 INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (parm)),
25343 INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (t)),
25344 UNIFY_ALLOW_NONE, explain_p);
25345 else
25346 return unify_success (explain_p);
25348 else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
25349 return unify_type_mismatch (explain_p, parm, arg);
25350 return unify_success (explain_p);
25352 case METHOD_TYPE:
25353 case FUNCTION_TYPE:
25355 unsigned int nargs;
25356 tree *args;
25357 tree a;
25358 unsigned int i;
25360 if (TREE_CODE (arg) != TREE_CODE (parm))
25361 return unify_type_mismatch (explain_p, parm, arg);
25363 /* CV qualifications for methods can never be deduced, they must
25364 match exactly. We need to check them explicitly here,
25365 because type_unification_real treats them as any other
25366 cv-qualified parameter. */
25367 if (TREE_CODE (parm) == METHOD_TYPE
25368 && (!check_cv_quals_for_unify
25369 (UNIFY_ALLOW_NONE,
25370 class_of_this_parm (arg),
25371 class_of_this_parm (parm))))
25372 return unify_cv_qual_mismatch (explain_p, parm, arg);
25373 if (TREE_CODE (arg) == FUNCTION_TYPE
25374 && type_memfn_quals (parm) != type_memfn_quals (arg))
25375 return unify_cv_qual_mismatch (explain_p, parm, arg);
25376 if (type_memfn_rqual (parm) != type_memfn_rqual (arg))
25377 return unify_type_mismatch (explain_p, parm, arg);
25379 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
25380 TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
25382 nargs = list_length (TYPE_ARG_TYPES (arg));
25383 args = XALLOCAVEC (tree, nargs);
25384 for (a = TYPE_ARG_TYPES (arg), i = 0;
25385 a != NULL_TREE && a != void_list_node;
25386 a = TREE_CHAIN (a), ++i)
25387 args[i] = TREE_VALUE (a);
25388 nargs = i;
25390 if (type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
25391 args, nargs, 1, DEDUCE_EXACT,
25392 NULL, explain_p))
25393 return 1;
25395 if (flag_noexcept_type)
25397 tree pspec = TYPE_RAISES_EXCEPTIONS (parm);
25398 tree aspec = canonical_eh_spec (TYPE_RAISES_EXCEPTIONS (arg));
25399 if (pspec == NULL_TREE) pspec = noexcept_false_spec;
25400 if (aspec == NULL_TREE) aspec = noexcept_false_spec;
25401 if (TREE_PURPOSE (pspec) && TREE_PURPOSE (aspec)
25402 && uses_template_parms (TREE_PURPOSE (pspec)))
25403 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_PURPOSE (pspec),
25404 TREE_PURPOSE (aspec),
25405 UNIFY_ALLOW_NONE, explain_p);
25406 else
25408 bool pn = nothrow_spec_p (pspec);
25409 bool an = nothrow_spec_p (aspec);
25410 /* Here "less cv-qual" means the deduced arg (i.e. parm) has
25411 /more/ noexcept, since function pointer conversions are the
25412 reverse of qualification conversions. */
25413 if (an == pn
25414 || (an < pn && (strict & UNIFY_ALLOW_LESS_CV_QUAL))
25415 || (an > pn && (strict & UNIFY_ALLOW_MORE_CV_QUAL)))
25416 /* OK. */;
25417 else
25418 return unify_type_mismatch (explain_p, parm, arg);
25421 if (flag_tm)
25423 /* As for noexcept. */
25424 bool pn = tx_safe_fn_type_p (parm);
25425 bool an = tx_safe_fn_type_p (arg);
25426 if (an == pn
25427 || (an < pn && (strict & UNIFY_ALLOW_LESS_CV_QUAL))
25428 || (an > pn && (strict & UNIFY_ALLOW_MORE_CV_QUAL)))
25429 /* OK. */;
25430 else
25431 return unify_type_mismatch (explain_p, parm, arg);
25434 return 0;
25437 case OFFSET_TYPE:
25438 /* Unify a pointer to member with a pointer to member function, which
25439 deduces the type of the member as a function type. */
25440 if (TYPE_PTRMEMFUNC_P (arg))
25442 /* Check top-level cv qualifiers */
25443 if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
25444 return unify_cv_qual_mismatch (explain_p, parm, arg);
25446 RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
25447 TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
25448 UNIFY_ALLOW_NONE, explain_p);
25450 /* Determine the type of the function we are unifying against. */
25451 tree fntype = static_fn_type (arg);
25453 return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
25456 if (TREE_CODE (arg) != OFFSET_TYPE)
25457 return unify_type_mismatch (explain_p, parm, arg);
25458 RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
25459 TYPE_OFFSET_BASETYPE (arg),
25460 UNIFY_ALLOW_NONE, explain_p);
25461 return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
25462 strict, explain_p);
25464 case CONST_DECL:
25465 /* CONST_DECL should already have been folded to its DECL_INITIAL. */
25466 gcc_unreachable ();
25468 case FIELD_DECL:
25469 case FUNCTION_DECL:
25470 case TEMPLATE_DECL:
25471 /* Matched cases are handled by the ARG == PARM test above. */
25472 return unify_template_argument_mismatch (explain_p, parm, arg);
25474 case VAR_DECL:
25475 /* We might get a variable as a non-type template argument in parm if the
25476 corresponding parameter is type-dependent. Make any necessary
25477 adjustments based on whether arg is a reference. */
25478 if (CONSTANT_CLASS_P (arg))
25479 parm = fold_non_dependent_expr (parm, complain);
25480 else if (REFERENCE_REF_P (arg))
25482 tree sub = TREE_OPERAND (arg, 0);
25483 STRIP_NOPS (sub);
25484 if (TREE_CODE (sub) == ADDR_EXPR)
25485 arg = TREE_OPERAND (sub, 0);
25487 /* Now use the normal expression code to check whether they match. */
25488 goto expr;
25490 case TYPE_ARGUMENT_PACK:
25491 case NONTYPE_ARGUMENT_PACK:
25492 return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
25493 ARGUMENT_PACK_ARGS (arg), strict, explain_p);
25495 case TYPEOF_TYPE:
25496 case DECLTYPE_TYPE:
25497 case TRAIT_TYPE:
25498 /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
25499 or TRAIT_TYPE nodes. */
25500 return unify_success (explain_p);
25502 case ERROR_MARK:
25503 /* Unification fails if we hit an error node. */
25504 return unify_invalid (explain_p);
25506 case INDIRECT_REF:
25507 if (REFERENCE_REF_P (parm))
25509 bool pexp = PACK_EXPANSION_P (arg);
25510 if (pexp)
25511 arg = PACK_EXPANSION_PATTERN (arg);
25512 if (REFERENCE_REF_P (arg))
25513 arg = TREE_OPERAND (arg, 0);
25514 if (pexp)
25515 arg = make_pack_expansion (arg, complain);
25516 return unify (tparms, targs, TREE_OPERAND (parm, 0), arg,
25517 strict, explain_p);
25519 /* FALLTHRU */
25521 default:
25522 /* An unresolved overload is a nondeduced context. */
25523 if (is_overloaded_fn (parm) || type_unknown_p (parm))
25524 return unify_success (explain_p);
25525 gcc_assert (EXPR_P (parm)
25526 || TREE_CODE (parm) == CONSTRUCTOR
25527 || TREE_CODE (parm) == TRAIT_EXPR);
25528 expr:
25529 /* We must be looking at an expression. This can happen with
25530 something like:
25532 template <int I>
25533 void foo(S<I>, S<I + 2>);
25537 template<typename T>
25538 void foo(A<T, T{}>);
25540 This is a "non-deduced context":
25542 [deduct.type]
25544 The non-deduced contexts are:
25546 --A non-type template argument or an array bound in which
25547 a subexpression references a template parameter.
25549 In these cases, we assume deduction succeeded, but don't
25550 actually infer any unifications. */
25552 if (!uses_template_parms (parm)
25553 && !template_args_equal (parm, arg))
25554 return unify_expression_unequal (explain_p, parm, arg);
25555 else
25556 return unify_success (explain_p);
25559 #undef RECUR_AND_CHECK_FAILURE
25561 /* Note that DECL can be defined in this translation unit, if
25562 required. */
25564 static void
25565 mark_definable (tree decl)
25567 tree clone;
25568 DECL_NOT_REALLY_EXTERN (decl) = 1;
25569 FOR_EACH_CLONE (clone, decl)
25570 DECL_NOT_REALLY_EXTERN (clone) = 1;
25573 /* Called if RESULT is explicitly instantiated, or is a member of an
25574 explicitly instantiated class. */
25576 void
25577 mark_decl_instantiated (tree result, int extern_p)
25579 SET_DECL_EXPLICIT_INSTANTIATION (result);
25581 /* If this entity has already been written out, it's too late to
25582 make any modifications. */
25583 if (TREE_ASM_WRITTEN (result))
25584 return;
25586 /* consteval functions are never emitted. */
25587 if (TREE_CODE (result) == FUNCTION_DECL
25588 && DECL_IMMEDIATE_FUNCTION_P (result))
25589 return;
25591 /* For anonymous namespace we don't need to do anything. */
25592 if (decl_internal_context_p (result))
25594 gcc_assert (!TREE_PUBLIC (result));
25595 return;
25598 if (TREE_CODE (result) != FUNCTION_DECL)
25599 /* The TREE_PUBLIC flag for function declarations will have been
25600 set correctly by tsubst. */
25601 TREE_PUBLIC (result) = 1;
25603 if (extern_p)
25605 DECL_EXTERNAL (result) = 1;
25606 DECL_NOT_REALLY_EXTERN (result) = 0;
25608 else
25610 mark_definable (result);
25611 mark_needed (result);
25612 /* Always make artificials weak. */
25613 if (DECL_ARTIFICIAL (result) && flag_weak)
25614 comdat_linkage (result);
25615 /* For WIN32 we also want to put explicit instantiations in
25616 linkonce sections. */
25617 else if (TREE_PUBLIC (result))
25618 maybe_make_one_only (result);
25619 if (TREE_CODE (result) == FUNCTION_DECL
25620 && DECL_TEMPLATE_INSTANTIATED (result))
25621 /* If the function has already been instantiated, clear DECL_EXTERNAL,
25622 since start_preparsed_function wouldn't have if we had an earlier
25623 extern explicit instantiation. */
25624 DECL_EXTERNAL (result) = 0;
25627 /* If EXTERN_P, then this function will not be emitted -- unless
25628 followed by an explicit instantiation, at which point its linkage
25629 will be adjusted. If !EXTERN_P, then this function will be
25630 emitted here. In neither circumstance do we want
25631 import_export_decl to adjust the linkage. */
25632 DECL_INTERFACE_KNOWN (result) = 1;
25635 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
25636 important template arguments. If any are missing, we check whether
25637 they're important by using error_mark_node for substituting into any
25638 args that were used for partial ordering (the ones between ARGS and END)
25639 and seeing if it bubbles up. */
25641 static bool
25642 check_undeduced_parms (tree targs, tree args, tree end)
25644 bool found = false;
25645 for (tree& targ : tree_vec_range (targs))
25646 if (targ == NULL_TREE)
25648 found = true;
25649 targ = error_mark_node;
25651 if (found)
25653 tree substed = tsubst_arg_types (args, targs, end, tf_none, NULL_TREE);
25654 if (substed == error_mark_node)
25655 return true;
25657 return false;
25660 /* Given two function templates PAT1 and PAT2, return:
25662 1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
25663 -1 if PAT2 is more specialized than PAT1.
25664 0 if neither is more specialized.
25666 LEN indicates the number of parameters we should consider
25667 (defaulted parameters should not be considered).
25669 The 1998 std underspecified function template partial ordering, and
25670 DR214 addresses the issue. We take pairs of arguments, one from
25671 each of the templates, and deduce them against each other. One of
25672 the templates will be more specialized if all the *other*
25673 template's arguments deduce against its arguments and at least one
25674 of its arguments *does* *not* deduce against the other template's
25675 corresponding argument. Deduction is done as for class templates.
25676 The arguments used in deduction have reference and top level cv
25677 qualifiers removed. Iff both arguments were originally reference
25678 types *and* deduction succeeds in both directions, an lvalue reference
25679 wins against an rvalue reference and otherwise the template
25680 with the more cv-qualified argument wins for that pairing (if
25681 neither is more cv-qualified, they both are equal). Unlike regular
25682 deduction, after all the arguments have been deduced in this way,
25683 we do *not* verify the deduced template argument values can be
25684 substituted into non-deduced contexts.
25686 The logic can be a bit confusing here, because we look at deduce1 and
25687 targs1 to see if pat2 is at least as specialized, and vice versa; if we
25688 can find template arguments for pat1 to make arg1 look like arg2, that
25689 means that arg2 is at least as specialized as arg1. */
25692 more_specialized_fn (tree pat1, tree pat2, int len)
25694 tree decl1 = DECL_TEMPLATE_RESULT (pat1);
25695 tree decl2 = DECL_TEMPLATE_RESULT (pat2);
25696 tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
25697 tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
25698 tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
25699 tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
25700 tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
25701 tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
25702 tree origs1, origs2;
25703 bool lose1 = false;
25704 bool lose2 = false;
25706 /* C++17 [temp.func.order]/3 (CWG532)
25708 If only one of the function templates M is a non-static member of some
25709 class A, M is considered to have a new first parameter inserted in its
25710 function parameter list. Given cv as the cv-qualifiers of M (if any), the
25711 new parameter is of type "rvalue reference to cv A" if the optional
25712 ref-qualifier of M is && or if M has no ref-qualifier and the first
25713 parameter of the other template has rvalue reference type. Otherwise, the
25714 new parameter is of type "lvalue reference to cv A". */
25716 if (DECL_STATIC_FUNCTION_P (decl1) || DECL_STATIC_FUNCTION_P (decl2))
25718 /* Note C++20 DR2445 extended the above to static member functions, but
25719 I think the old G++ behavior of just skipping the object
25720 parameter when comparing to a static member function was better, so
25721 let's stick with that for now. This is CWG2834. --jason 2023-12 */
25722 if (DECL_OBJECT_MEMBER_FUNCTION_P (decl1))
25724 len--; /* LEN is the number of significant arguments for DECL1 */
25725 args1 = TREE_CHAIN (args1);
25727 else if (DECL_OBJECT_MEMBER_FUNCTION_P (decl2))
25728 args2 = TREE_CHAIN (args2);
25730 else if (DECL_IOBJ_MEMBER_FUNCTION_P (decl1)
25731 && DECL_IOBJ_MEMBER_FUNCTION_P (decl2))
25733 /* Note DR2445 also (IMO wrongly) removed the "only one" above, which
25734 would break e.g. cpp1y/lambda-generic-variadic5.C. */
25735 len--;
25736 args1 = TREE_CHAIN (args1);
25737 args2 = TREE_CHAIN (args2);
25739 else if (DECL_IOBJ_MEMBER_FUNCTION_P (decl1)
25740 || DECL_IOBJ_MEMBER_FUNCTION_P (decl2))
25742 /* The other is a non-member or explicit object member function;
25743 rewrite the implicit object parameter to a reference. */
25744 tree ns = DECL_IOBJ_MEMBER_FUNCTION_P (decl2) ? decl2 : decl1;
25745 tree &nsargs = ns == decl2 ? args2 : args1;
25746 tree obtype = TREE_TYPE (TREE_VALUE (nsargs));
25748 nsargs = TREE_CHAIN (nsargs);
25750 cp_ref_qualifier rqual = type_memfn_rqual (TREE_TYPE (ns));
25751 if (rqual == REF_QUAL_NONE)
25753 tree otherfirst = ns == decl1 ? args2 : args1;
25754 otherfirst = TREE_VALUE (otherfirst);
25755 if (TREE_CODE (otherfirst) == REFERENCE_TYPE
25756 && TYPE_REF_IS_RVALUE (otherfirst))
25757 rqual = REF_QUAL_RVALUE;
25759 obtype = cp_build_reference_type (obtype, rqual == REF_QUAL_RVALUE);
25760 nsargs = tree_cons (NULL_TREE, obtype, nsargs);
25763 /* If only one is a conversion operator, they are unordered. */
25764 if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
25765 return 0;
25767 /* Consider the return type for a conversion function */
25768 if (DECL_CONV_FN_P (decl1))
25770 args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
25771 args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
25772 len++;
25775 processing_template_decl++;
25777 origs1 = args1;
25778 origs2 = args2;
25780 while (len--
25781 /* Stop when an ellipsis is seen. */
25782 && args1 != NULL_TREE && args2 != NULL_TREE)
25784 tree arg1 = TREE_VALUE (args1);
25785 tree arg2 = TREE_VALUE (args2);
25786 int deduce1, deduce2;
25787 int quals1 = -1;
25788 int quals2 = -1;
25789 int ref1 = 0;
25790 int ref2 = 0;
25792 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
25793 && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25795 /* When both arguments are pack expansions, we need only
25796 unify the patterns themselves. */
25797 arg1 = PACK_EXPANSION_PATTERN (arg1);
25798 arg2 = PACK_EXPANSION_PATTERN (arg2);
25800 /* This is the last comparison we need to do. */
25801 len = 0;
25804 if (TYPE_REF_P (arg1))
25806 ref1 = TYPE_REF_IS_RVALUE (arg1) + 1;
25807 arg1 = TREE_TYPE (arg1);
25808 quals1 = cp_type_quals (arg1);
25811 if (TYPE_REF_P (arg2))
25813 ref2 = TYPE_REF_IS_RVALUE (arg2) + 1;
25814 arg2 = TREE_TYPE (arg2);
25815 quals2 = cp_type_quals (arg2);
25818 arg1 = TYPE_MAIN_VARIANT (arg1);
25819 arg2 = TYPE_MAIN_VARIANT (arg2);
25821 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
25823 int i, len2 = remaining_arguments (args2);
25824 tree parmvec = make_tree_vec (1);
25825 tree argvec = make_tree_vec (len2);
25826 tree ta = args2;
25828 /* Setup the parameter vector, which contains only ARG1. */
25829 TREE_VEC_ELT (parmvec, 0) = arg1;
25831 /* Setup the argument vector, which contains the remaining
25832 arguments. */
25833 for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
25834 TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
25836 deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
25837 argvec, DEDUCE_EXACT,
25838 /*subr=*/true, /*explain_p=*/false)
25839 == 0);
25841 /* We cannot deduce in the other direction, because ARG1 is
25842 a pack expansion but ARG2 is not. */
25843 deduce2 = 0;
25845 else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25847 int i, len1 = remaining_arguments (args1);
25848 tree parmvec = make_tree_vec (1);
25849 tree argvec = make_tree_vec (len1);
25850 tree ta = args1;
25852 /* Setup the parameter vector, which contains only ARG1. */
25853 TREE_VEC_ELT (parmvec, 0) = arg2;
25855 /* Setup the argument vector, which contains the remaining
25856 arguments. */
25857 for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
25858 TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
25860 deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
25861 argvec, DEDUCE_EXACT,
25862 /*subr=*/true, /*explain_p=*/false)
25863 == 0);
25865 /* We cannot deduce in the other direction, because ARG2 is
25866 a pack expansion but ARG1 is not.*/
25867 deduce1 = 0;
25870 else
25872 /* The normal case, where neither argument is a pack
25873 expansion. */
25874 deduce1 = (unify (tparms1, targs1, arg1, arg2,
25875 UNIFY_ALLOW_NONE, /*explain_p=*/false)
25876 == 0);
25877 deduce2 = (unify (tparms2, targs2, arg2, arg1,
25878 UNIFY_ALLOW_NONE, /*explain_p=*/false)
25879 == 0);
25882 /* If we couldn't deduce arguments for tparms1 to make arg1 match
25883 arg2, then arg2 is not as specialized as arg1. */
25884 if (!deduce1)
25885 lose2 = true;
25886 if (!deduce2)
25887 lose1 = true;
25889 /* "If, for a given type, deduction succeeds in both directions
25890 (i.e., the types are identical after the transformations above)
25891 and both P and A were reference types (before being replaced with
25892 the type referred to above):
25893 - if the type from the argument template was an lvalue reference and
25894 the type from the parameter template was not, the argument type is
25895 considered to be more specialized than the other; otherwise,
25896 - if the type from the argument template is more cv-qualified
25897 than the type from the parameter template (as described above),
25898 the argument type is considered to be more specialized than the other;
25899 otherwise,
25900 - neither type is more specialized than the other." */
25902 if (deduce1 && deduce2)
25904 if (ref1 && ref2 && ref1 != ref2)
25906 if (ref1 > ref2)
25907 lose1 = true;
25908 else
25909 lose2 = true;
25911 else if (quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
25913 if ((quals1 & quals2) == quals2)
25914 lose2 = true;
25915 if ((quals1 & quals2) == quals1)
25916 lose1 = true;
25920 if (lose1 && lose2)
25921 /* We've failed to deduce something in either direction.
25922 These must be unordered. */
25923 break;
25925 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
25926 || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25927 /* We have already processed all of the arguments in our
25928 handing of the pack expansion type. */
25929 len = 0;
25931 args1 = TREE_CHAIN (args1);
25932 args2 = TREE_CHAIN (args2);
25935 /* "In most cases, all template parameters must have values in order for
25936 deduction to succeed, but for partial ordering purposes a template
25937 parameter may remain without a value provided it is not used in the
25938 types being used for partial ordering."
25940 Thus, if we are missing any of the targs1 we need to substitute into
25941 origs1, then pat2 is not as specialized as pat1. This can happen when
25942 there is a nondeduced context. */
25943 if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
25944 lose2 = true;
25945 if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
25946 lose1 = true;
25948 processing_template_decl--;
25950 /* If both deductions succeed, the partial ordering selects the more
25951 constrained template. */
25952 /* P2113: If the corresponding template-parameters of the
25953 template-parameter-lists are not equivalent ([temp.over.link]) or if
25954 the function parameters that positionally correspond between the two
25955 templates are not of the same type, neither template is more
25956 specialized than the other. */
25957 if (!lose1 && !lose2
25958 && comp_template_parms (DECL_TEMPLATE_PARMS (pat1),
25959 DECL_TEMPLATE_PARMS (pat2))
25960 && compparms (origs1, origs2))
25962 int winner = more_constrained (decl1, decl2);
25963 if (winner > 0)
25964 lose2 = true;
25965 else if (winner < 0)
25966 lose1 = true;
25969 /* All things being equal, if the next argument is a pack expansion
25970 for one function but not for the other, prefer the
25971 non-variadic function. FIXME this is bogus; see c++/41958. */
25972 if (lose1 == lose2
25973 && args1 && TREE_VALUE (args1)
25974 && args2 && TREE_VALUE (args2))
25976 lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
25977 lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
25980 if (lose1 == lose2)
25981 return 0;
25982 else if (!lose1)
25983 return 1;
25984 else
25985 return -1;
25988 /* Determine which of two partial specializations of TMPL is more
25989 specialized.
25991 PAT1 is a TREE_LIST whose TREE_VALUE is the TEMPLATE_DECL corresponding
25992 to the first partial specialization. The TREE_PURPOSE is the
25993 innermost set of template parameters for the partial
25994 specialization. PAT2 is similar, but for the second template.
25996 Return 1 if the first partial specialization is more specialized;
25997 -1 if the second is more specialized; 0 if neither is more
25998 specialized.
26000 See [temp.class.order] for information about determining which of
26001 two templates is more specialized. */
26003 static int
26004 more_specialized_partial_spec (tree tmpl, tree pat1, tree pat2)
26006 tree targs;
26007 int winner = 0;
26008 bool any_deductions = false;
26010 tree tmpl1 = TREE_VALUE (pat1);
26011 tree tmpl2 = TREE_VALUE (pat2);
26012 tree specargs1 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl1)));
26013 tree specargs2 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl2)));
26015 /* Just like what happens for functions, if we are ordering between
26016 different template specializations, we may encounter dependent
26017 types in the arguments, and we need our dependency check functions
26018 to behave correctly. */
26019 ++processing_template_decl;
26020 targs = get_partial_spec_bindings (tmpl, tmpl1, specargs2);
26021 if (targs)
26023 --winner;
26024 any_deductions = true;
26027 targs = get_partial_spec_bindings (tmpl, tmpl2, specargs1);
26028 if (targs)
26030 ++winner;
26031 any_deductions = true;
26033 --processing_template_decl;
26035 /* If both deductions succeed, the partial ordering selects the more
26036 constrained template. */
26037 if (!winner && any_deductions)
26038 winner = more_constrained (tmpl1, tmpl2);
26040 /* In the case of a tie where at least one of the templates
26041 has a parameter pack at the end, the template with the most
26042 non-packed parameters wins. */
26043 if (winner == 0
26044 && any_deductions
26045 && (template_args_variadic_p (TREE_PURPOSE (pat1))
26046 || template_args_variadic_p (TREE_PURPOSE (pat2))))
26048 tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
26049 tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
26050 int len1 = TREE_VEC_LENGTH (args1);
26051 int len2 = TREE_VEC_LENGTH (args2);
26053 /* We don't count the pack expansion at the end. */
26054 if (template_args_variadic_p (TREE_PURPOSE (pat1)))
26055 --len1;
26056 if (template_args_variadic_p (TREE_PURPOSE (pat2)))
26057 --len2;
26059 if (len1 > len2)
26060 return 1;
26061 else if (len1 < len2)
26062 return -1;
26065 return winner;
26068 /* Return the template arguments that will produce the function signature
26069 DECL from the function template FN, with the explicit template
26070 arguments EXPLICIT_ARGS. If CHECK_RETTYPE is true, the return type must
26071 also match. Return NULL_TREE if no satisfactory arguments could be
26072 found. */
26074 static tree
26075 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
26077 int ntparms = DECL_NTPARMS (fn);
26078 tree targs = make_tree_vec (ntparms);
26079 tree decl_type = TREE_TYPE (decl);
26080 tree decl_arg_types;
26081 tree *args;
26082 unsigned int nargs, ix;
26083 tree arg;
26085 gcc_assert (decl != DECL_TEMPLATE_RESULT (fn));
26087 /* Never do unification on the 'this' parameter. */
26088 decl_arg_types = skip_artificial_parms_for (decl,
26089 TYPE_ARG_TYPES (decl_type));
26091 nargs = list_length (decl_arg_types);
26092 args = XALLOCAVEC (tree, nargs);
26093 for (arg = decl_arg_types, ix = 0;
26094 arg != NULL_TREE;
26095 arg = TREE_CHAIN (arg), ++ix)
26096 args[ix] = TREE_VALUE (arg);
26098 if (fn_type_unification (fn, explicit_args, targs,
26099 args, ix,
26100 (check_rettype || DECL_CONV_FN_P (fn)
26101 ? TREE_TYPE (decl_type) : NULL_TREE),
26102 DEDUCE_EXACT, LOOKUP_NORMAL, NULL,
26103 /*explain_p=*/false,
26104 /*decltype*/false)
26105 == error_mark_node)
26106 return NULL_TREE;
26108 return targs;
26111 /* Return the innermost template arguments that, when applied to a partial
26112 specialization SPEC_TMPL of TMPL, yield the ARGS.
26114 For example, suppose we have:
26116 template <class T, class U> struct S {};
26117 template <class T> struct S<T*, int> {};
26119 Then, suppose we want to get `S<double*, int>'. SPEC_TMPL will be the
26120 partial specialization and the ARGS will be {double*, int}. The resulting
26121 vector will be {double}, indicating that `T' is bound to `double'. */
26123 static tree
26124 get_partial_spec_bindings (tree tmpl, tree spec_tmpl, tree args)
26126 tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (spec_tmpl);
26127 tree spec_args
26128 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (spec_tmpl)));
26129 int i, ntparms = TREE_VEC_LENGTH (tparms);
26130 tree deduced_args;
26131 tree innermost_deduced_args;
26133 innermost_deduced_args = make_tree_vec (ntparms);
26134 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
26136 deduced_args = copy_node (args);
26137 SET_TMPL_ARGS_LEVEL (deduced_args,
26138 TMPL_ARGS_DEPTH (deduced_args),
26139 innermost_deduced_args);
26141 else
26142 deduced_args = innermost_deduced_args;
26144 bool tried_array_deduction = (cxx_dialect < cxx17);
26145 again:
26146 if (unify (tparms, deduced_args,
26147 INNERMOST_TEMPLATE_ARGS (spec_args),
26148 INNERMOST_TEMPLATE_ARGS (args),
26149 UNIFY_ALLOW_NONE, /*explain_p=*/false))
26150 return NULL_TREE;
26152 for (i = 0; i < ntparms; ++i)
26153 if (! TREE_VEC_ELT (innermost_deduced_args, i))
26155 if (!tried_array_deduction)
26157 try_array_deduction (tparms, innermost_deduced_args,
26158 INNERMOST_TEMPLATE_ARGS (spec_args));
26159 tried_array_deduction = true;
26160 if (TREE_VEC_ELT (innermost_deduced_args, i))
26161 goto again;
26163 return NULL_TREE;
26166 if (!push_tinst_level (spec_tmpl, deduced_args))
26168 excessive_deduction_depth = true;
26169 return NULL_TREE;
26172 /* Verify that nondeduced template arguments agree with the type
26173 obtained from argument deduction.
26175 For example:
26177 struct A { typedef int X; };
26178 template <class T, class U> struct C {};
26179 template <class T> struct C<T, typename T::X> {};
26181 Then with the instantiation `C<A, int>', we can deduce that
26182 `T' is `A' but unify () does not check whether `typename T::X'
26183 is `int'. */
26184 spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
26186 if (spec_args != error_mark_node)
26187 spec_args = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
26188 INNERMOST_TEMPLATE_ARGS (spec_args),
26189 tmpl, tf_none, false);
26191 pop_tinst_level ();
26193 if (spec_args == error_mark_node
26194 /* We only need to check the innermost arguments; the other
26195 arguments will always agree. */
26196 || !comp_template_args_porder (INNERMOST_TEMPLATE_ARGS (spec_args),
26197 INNERMOST_TEMPLATE_ARGS (args)))
26198 return NULL_TREE;
26200 /* Now that we have bindings for all of the template arguments,
26201 ensure that the arguments deduced for the template template
26202 parameters have compatible template parameter lists. See the use
26203 of template_template_parm_bindings_ok_p in fn_type_unification
26204 for more information. */
26205 if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
26206 return NULL_TREE;
26208 return deduced_args;
26211 // Compare two function templates T1 and T2 by deducing bindings
26212 // from one against the other. If both deductions succeed, compare
26213 // constraints to see which is more constrained.
26214 static int
26215 more_specialized_inst (tree t1, tree t2)
26217 int fate = 0;
26218 int count = 0;
26220 if (get_bindings (t1, DECL_TEMPLATE_RESULT (t2), NULL_TREE, true))
26222 --fate;
26223 ++count;
26226 if (get_bindings (t2, DECL_TEMPLATE_RESULT (t1), NULL_TREE, true))
26228 ++fate;
26229 ++count;
26232 // If both deductions succeed, then one may be more constrained.
26233 if (count == 2 && fate == 0)
26234 fate = more_constrained (t1, t2);
26236 return fate;
26239 /* TEMPLATES is a TREE_LIST. Each TREE_VALUE is a TEMPLATE_DECL.
26240 Return the TREE_LIST node with the most specialized template, if
26241 any. If there is no most specialized template, the error_mark_node
26242 is returned.
26244 Note that this function does not look at, or modify, the
26245 TREE_PURPOSE or TREE_TYPE of any of the nodes. Since the node
26246 returned is one of the elements of INSTANTIATIONS, callers may
26247 store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
26248 and retrieve it from the value returned. */
26250 tree
26251 most_specialized_instantiation (tree templates)
26253 tree fn, champ;
26255 ++processing_template_decl;
26257 champ = templates;
26258 for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
26260 gcc_assert (TREE_VALUE (champ) != TREE_VALUE (fn));
26261 int fate = more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn));
26262 if (fate == -1)
26263 champ = fn;
26264 else if (!fate)
26266 /* Equally specialized, move to next function. If there
26267 is no next function, nothing's most specialized. */
26268 fn = TREE_CHAIN (fn);
26269 champ = fn;
26270 if (!fn)
26271 break;
26275 if (champ)
26276 /* Now verify that champ is better than everything earlier in the
26277 instantiation list. */
26278 for (fn = templates; fn != champ; fn = TREE_CHAIN (fn)) {
26279 if (more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn)) != 1)
26281 champ = NULL_TREE;
26282 break;
26286 processing_template_decl--;
26288 if (!champ)
26289 return error_mark_node;
26291 return champ;
26294 /* If DECL is a specialization of some template, return the most
26295 general such template. Otherwise, returns NULL_TREE.
26297 For example, given:
26299 template <class T> struct S { template <class U> void f(U); };
26301 if TMPL is `template <class U> void S<int>::f(U)' this will return
26302 the full template. This function will not trace past partial
26303 specializations, however. For example, given in addition:
26305 template <class T> struct S<T*> { template <class U> void f(U); };
26307 if TMPL is `template <class U> void S<int*>::f(U)' this will return
26308 `template <class T> template <class U> S<T*>::f(U)'. */
26310 tree
26311 most_general_template (const_tree decl)
26313 if (TREE_CODE (decl) != TEMPLATE_DECL)
26315 if (tree tinfo = get_template_info (decl))
26316 decl = TI_TEMPLATE (tinfo);
26317 /* The TI_TEMPLATE can be an IDENTIFIER_NODE for a
26318 template friend, or a FIELD_DECL for a capture pack. */
26319 if (TREE_CODE (decl) != TEMPLATE_DECL)
26320 return NULL_TREE;
26323 if (DECL_TEMPLATE_TEMPLATE_PARM_P (decl))
26324 return DECL_TI_TEMPLATE (DECL_TEMPLATE_RESULT (decl));
26326 /* Look for more and more general templates. */
26327 while (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
26329 /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
26330 (See cp-tree.h for details.) */
26331 if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
26332 break;
26334 if (CLASS_TYPE_P (TREE_TYPE (decl))
26335 && !TYPE_DECL_ALIAS_P (TYPE_NAME (TREE_TYPE (decl)))
26336 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
26337 break;
26339 /* Stop if we run into an explicitly specialized class template. */
26340 if (!DECL_NAMESPACE_SCOPE_P (decl)
26341 && DECL_CONTEXT (decl)
26342 && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
26343 break;
26345 decl = DECL_TI_TEMPLATE (decl);
26348 return CONST_CAST_TREE (decl);
26351 /* Return the most specialized of the template partial specializations
26352 which can produce TARGET, a specialization of some class or variable
26353 template. The value returned is a TEMPLATE_INFO; the TI_TEMPLATE is a
26354 TEMPLATE_DECL node corresponding to the partial specialization, while
26355 the TI_ARGS is the set of template arguments that must be substituted
26356 into the template pattern in order to generate TARGET. The result is
26357 cached in the TI_PARTIAL_INFO of the corresponding TEMPLATE_INFO unless
26358 RECHECKING is true.
26360 If the choice of partial specialization is ambiguous, a diagnostic
26361 is issued, and the error_mark_node is returned. If there are no
26362 partial specializations matching TARGET, then NULL_TREE is
26363 returned, indicating that the primary template should be used. */
26365 tree
26366 most_specialized_partial_spec (tree target, tsubst_flags_t complain,
26367 bool rechecking /* = false */)
26369 tree tinfo = NULL_TREE;
26370 tree tmpl, args, decl;
26371 if (TYPE_P (target))
26373 tinfo = CLASSTYPE_TEMPLATE_INFO (target);
26374 tmpl = TI_TEMPLATE (tinfo);
26375 args = TI_ARGS (tinfo);
26376 decl = TYPE_NAME (target);
26378 else if (TREE_CODE (target) == TEMPLATE_ID_EXPR)
26380 tmpl = TREE_OPERAND (target, 0);
26381 args = TREE_OPERAND (target, 1);
26382 decl = DECL_TEMPLATE_RESULT (tmpl);
26384 else if (VAR_P (target))
26386 tinfo = DECL_TEMPLATE_INFO (target);
26387 tmpl = TI_TEMPLATE (tinfo);
26388 args = TI_ARGS (tinfo);
26389 decl = target;
26391 else
26392 gcc_unreachable ();
26394 if (!PRIMARY_TEMPLATE_P (tmpl))
26395 return NULL_TREE;
26397 if (!rechecking
26398 && tinfo
26399 && (VAR_P (target) || COMPLETE_TYPE_P (target)))
26400 return TI_PARTIAL_INFO (tinfo);
26402 tree main_tmpl = most_general_template (tmpl);
26403 tree specs = DECL_TEMPLATE_SPECIALIZATIONS (main_tmpl);
26404 if (!specs)
26405 /* There are no partial specializations of this template. */
26406 return NULL_TREE;
26408 push_access_scope_guard pas (decl);
26409 deferring_access_check_sentinel acs (dk_no_deferred);
26411 /* For determining which partial specialization to use, only the
26412 innermost args are interesting. */
26413 tree outer_args = NULL_TREE;
26414 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
26416 outer_args = strip_innermost_template_args (args, 1);
26417 args = INNERMOST_TEMPLATE_ARGS (args);
26420 /* The caller hasn't called push_to_top_level yet, but we need
26421 get_partial_spec_bindings to be done in non-template context so that we'll
26422 fully resolve everything. */
26423 processing_template_decl_sentinel ptds;
26425 tree list = NULL_TREE;
26426 for (tree t = specs; t; t = TREE_CHAIN (t))
26428 const tree ospec_tmpl = TREE_VALUE (t);
26430 tree spec_tmpl;
26431 if (outer_args)
26433 /* Substitute in the template args from the enclosing class. */
26434 ++processing_template_decl;
26435 spec_tmpl = tsubst (ospec_tmpl, outer_args, tf_none, NULL_TREE);
26436 --processing_template_decl;
26437 if (spec_tmpl == error_mark_node)
26438 return error_mark_node;
26440 else
26441 spec_tmpl = ospec_tmpl;
26443 tree spec_args = get_partial_spec_bindings (tmpl, spec_tmpl, args);
26444 if (spec_args)
26446 if (outer_args)
26447 spec_args = add_to_template_args (outer_args, spec_args);
26449 /* Keep the candidate only if its constraints are satisfied. */
26450 if (constraints_satisfied_p (ospec_tmpl, spec_args))
26451 list = tree_cons (spec_args, ospec_tmpl, list);
26455 if (! list)
26456 return NULL_TREE;
26458 tree champ = list;
26459 bool ambiguous_p = false;
26460 for (tree t = TREE_CHAIN (list); t; t = TREE_CHAIN (t))
26462 int fate = more_specialized_partial_spec (tmpl, champ, t);
26463 if (fate == 1)
26465 else
26467 if (fate == 0)
26469 t = TREE_CHAIN (t);
26470 if (! t)
26472 ambiguous_p = true;
26473 break;
26476 champ = t;
26480 if (!ambiguous_p)
26481 for (tree t = list; t && t != champ; t = TREE_CHAIN (t))
26483 int fate = more_specialized_partial_spec (tmpl, champ, t);
26484 if (fate != 1)
26486 ambiguous_p = true;
26487 break;
26491 if (ambiguous_p)
26493 const char *str;
26494 char *spaces = NULL;
26495 if (!(complain & tf_error))
26496 return error_mark_node;
26497 auto_diagnostic_group d;
26498 if (TYPE_P (target))
26499 error ("ambiguous template instantiation for %q#T", target);
26500 else
26501 error ("ambiguous template instantiation for %q#D", target);
26502 str = ngettext ("candidate is:", "candidates are:", list_length (list));
26503 for (tree t = list; t; t = TREE_CHAIN (t))
26505 tree subst = build_tree_list (TREE_VALUE (t), TREE_PURPOSE (t));
26506 inform (DECL_SOURCE_LOCATION (TREE_VALUE (t)),
26507 "%s %#qS", spaces ? spaces : str, subst);
26508 spaces = spaces ? spaces : get_spaces (str);
26510 free (spaces);
26511 return error_mark_node;
26514 tree result = build_template_info (TREE_VALUE (champ), TREE_PURPOSE (champ));
26515 if (!rechecking && tinfo)
26516 TI_PARTIAL_INFO (tinfo) = result;
26517 return result;
26520 /* Explicitly instantiate DECL. */
26522 void
26523 do_decl_instantiation (tree decl, tree storage)
26525 tree result = NULL_TREE;
26526 int extern_p = 0;
26528 if (!decl || decl == error_mark_node)
26529 /* An error occurred, for which grokdeclarator has already issued
26530 an appropriate message. */
26531 return;
26532 else if (! DECL_LANG_SPECIFIC (decl))
26534 error ("explicit instantiation of non-template %q#D", decl);
26535 return;
26538 bool var_templ = (DECL_TEMPLATE_INFO (decl)
26539 && variable_template_p (DECL_TI_TEMPLATE (decl)));
26541 if (VAR_P (decl) && !var_templ)
26543 /* There is an asymmetry here in the way VAR_DECLs and
26544 FUNCTION_DECLs are handled by grokdeclarator. In the case of
26545 the latter, the DECL we get back will be marked as a
26546 template instantiation, and the appropriate
26547 DECL_TEMPLATE_INFO will be set up. This does not happen for
26548 VAR_DECLs so we do the lookup here. Probably, grokdeclarator
26549 should handle VAR_DECLs as it currently handles
26550 FUNCTION_DECLs. */
26551 if (!DECL_CLASS_SCOPE_P (decl))
26553 error ("%qD is not a static data member of a class template", decl);
26554 return;
26556 result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
26557 if (!result || !VAR_P (result))
26559 error ("no matching template for %qD found", decl);
26560 return;
26562 if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
26564 error ("type %qT for explicit instantiation %qD does not match "
26565 "declared type %qT", TREE_TYPE (result), decl,
26566 TREE_TYPE (decl));
26567 return;
26570 else if (TREE_CODE (decl) != FUNCTION_DECL && !var_templ)
26572 error ("explicit instantiation of %q#D", decl);
26573 return;
26575 else
26576 result = decl;
26578 /* Check for various error cases. Note that if the explicit
26579 instantiation is valid the RESULT will currently be marked as an
26580 *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
26581 until we get here. */
26583 if (DECL_TEMPLATE_SPECIALIZATION (result))
26585 /* DR 259 [temp.spec].
26587 Both an explicit instantiation and a declaration of an explicit
26588 specialization shall not appear in a program unless the explicit
26589 instantiation follows a declaration of the explicit specialization.
26591 For a given set of template parameters, if an explicit
26592 instantiation of a template appears after a declaration of an
26593 explicit specialization for that template, the explicit
26594 instantiation has no effect. */
26595 return;
26597 else if (DECL_EXPLICIT_INSTANTIATION (result))
26599 /* [temp.spec]
26601 No program shall explicitly instantiate any template more
26602 than once.
26604 We check DECL_NOT_REALLY_EXTERN so as not to complain when
26605 the first instantiation was `extern' and the second is not,
26606 and EXTERN_P for the opposite case. */
26607 if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
26608 permerror (input_location, "duplicate explicit instantiation of %q#D", result);
26609 /* If an "extern" explicit instantiation follows an ordinary
26610 explicit instantiation, the template is instantiated. */
26611 if (extern_p)
26612 return;
26614 else if (!DECL_IMPLICIT_INSTANTIATION (result))
26616 error ("no matching template for %qD found", result);
26617 return;
26619 else if (!DECL_TEMPLATE_INFO (result))
26621 permerror (input_location, "explicit instantiation of non-template %q#D", result);
26622 return;
26625 if (storage == NULL_TREE)
26627 else if (storage == ridpointers[(int) RID_EXTERN])
26629 if (cxx_dialect == cxx98 && pedantic)
26630 pedwarn (input_location, OPT_Wc__11_extensions,
26631 "ISO C++ 1998 forbids the use of %<extern%> on explicit "
26632 "instantiations");
26633 extern_p = 1;
26635 else
26636 error ("storage class %qD applied to template instantiation", storage);
26638 check_explicit_instantiation_namespace (result);
26639 mark_decl_instantiated (result, extern_p);
26640 if (! extern_p)
26641 instantiate_decl (result, /*defer_ok=*/true,
26642 /*expl_inst_class_mem_p=*/false);
26645 static void
26646 mark_class_instantiated (tree t, int extern_p)
26648 SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
26649 SET_CLASSTYPE_INTERFACE_KNOWN (t);
26650 CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
26651 TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
26652 if (! extern_p)
26654 CLASSTYPE_DEBUG_REQUESTED (t) = 1;
26655 rest_of_type_compilation (t, 1);
26659 /* Perform an explicit instantiation of template class T. STORAGE, if
26660 non-null, is the RID for extern, inline or static. COMPLAIN is
26661 nonzero if this is called from the parser, zero if called recursively,
26662 since the standard is unclear (as detailed below). */
26664 void
26665 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
26667 if (!(CLASS_TYPE_P (t) && CLASSTYPE_TEMPLATE_INFO (t)))
26669 if (tree ti = TYPE_TEMPLATE_INFO (t))
26670 error ("explicit instantiation of non-class template %qD",
26671 TI_TEMPLATE (ti));
26672 else
26673 error ("explicit instantiation of non-template type %qT", t);
26674 return;
26677 complete_type (t);
26679 if (!COMPLETE_TYPE_P (t))
26681 if (complain & tf_error)
26682 error ("explicit instantiation of %q#T before definition of template",
26684 return;
26687 /* At most one of these will be true. */
26688 bool extern_p = false;
26689 bool nomem_p = false;
26690 bool static_p = false;
26692 if (storage != NULL_TREE)
26694 if (storage == ridpointers[(int) RID_EXTERN])
26696 if (cxx_dialect == cxx98 && pedantic)
26697 pedwarn (input_location, OPT_Wc__11_extensions,
26698 "ISO C++ 1998 forbids the use of %<extern%> on "
26699 "explicit instantiations");
26701 else
26702 pedwarn (input_location, OPT_Wpedantic,
26703 "ISO C++ forbids the use of %qE"
26704 " on explicit instantiations", storage);
26706 if (storage == ridpointers[(int) RID_INLINE])
26707 nomem_p = true;
26708 else if (storage == ridpointers[(int) RID_EXTERN])
26709 extern_p = true;
26710 else if (storage == ridpointers[(int) RID_STATIC])
26711 static_p = true;
26712 else
26713 error ("storage class %qD applied to template instantiation",
26714 storage);
26717 if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
26718 /* DR 259 [temp.spec].
26720 Both an explicit instantiation and a declaration of an explicit
26721 specialization shall not appear in a program unless the
26722 explicit instantiation follows a declaration of the explicit
26723 specialization.
26725 For a given set of template parameters, if an explicit
26726 instantiation of a template appears after a declaration of an
26727 explicit specialization for that template, the explicit
26728 instantiation has no effect. */
26729 return;
26731 if (CLASSTYPE_EXPLICIT_INSTANTIATION (t) && !CLASSTYPE_INTERFACE_ONLY (t))
26733 /* We've already instantiated the template. */
26735 /* [temp.spec]
26737 No program shall explicitly instantiate any template more
26738 than once.
26740 If EXTERN_P then this is ok. */
26741 if (!extern_p && (complain & tf_error))
26742 permerror (input_location,
26743 "duplicate explicit instantiation of %q#T", t);
26745 return;
26748 check_explicit_instantiation_namespace (TYPE_NAME (t));
26749 mark_class_instantiated (t, extern_p);
26751 if (nomem_p)
26752 return;
26754 /* In contrast to implicit instantiation, where only the
26755 declarations, and not the definitions, of members are
26756 instantiated, we have here:
26758 [temp.explicit]
26760 An explicit instantiation that names a class template
26761 specialization is also an explicit instantiation of the same
26762 kind (declaration or definition) of each of its members (not
26763 including members inherited from base classes and members
26764 that are templates) that has not been previously explicitly
26765 specialized in the translation unit containing the explicit
26766 instantiation, provided that the associated constraints, if
26767 any, of that member are satisfied by the template arguments
26768 of the explicit instantiation. */
26769 for (tree fld = TYPE_FIELDS (t); fld; fld = DECL_CHAIN (fld))
26770 if ((VAR_P (fld)
26771 || (TREE_CODE (fld) == FUNCTION_DECL
26772 && !static_p
26773 && user_provided_p (fld)))
26774 && DECL_TEMPLATE_INSTANTIATION (fld)
26775 && constraints_satisfied_p (fld))
26777 mark_decl_instantiated (fld, extern_p);
26778 if (! extern_p)
26779 instantiate_decl (fld, /*defer_ok=*/true,
26780 /*expl_inst_class_mem_p=*/true);
26782 else if (DECL_IMPLICIT_TYPEDEF_P (fld))
26784 tree type = TREE_TYPE (fld);
26786 if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
26787 && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
26788 do_type_instantiation (type, storage, 0);
26792 /* Given a function DECL, which is a specialization of TMPL, modify
26793 DECL to be a re-instantiation of TMPL with the same template
26794 arguments. TMPL should be the template into which tsubst'ing
26795 should occur for DECL, not the most general template.
26797 One reason for doing this is a scenario like this:
26799 template <class T>
26800 void f(const T&, int i);
26802 void g() { f(3, 7); }
26804 template <class T>
26805 void f(const T& t, const int i) { }
26807 Note that when the template is first instantiated, with
26808 instantiate_template, the resulting DECL will have no name for the
26809 first parameter, and the wrong type for the second. So, when we go
26810 to instantiate the DECL, we regenerate it. */
26812 static void
26813 regenerate_decl_from_template (tree decl, tree tmpl, tree args)
26815 /* The arguments used to instantiate DECL, from the most general
26816 template. */
26817 tree code_pattern = DECL_TEMPLATE_RESULT (tmpl);
26819 /* Make sure that we can see identifiers, and compute access correctly. */
26820 push_access_scope (decl);
26822 if (TREE_CODE (decl) == FUNCTION_DECL)
26824 tree specs;
26825 int args_depth;
26826 int parms_depth;
26828 /* Don't bother with this for unique friends that can't be redeclared and
26829 might change type if regenerated (PR69836). */
26830 if (DECL_UNIQUE_FRIEND_P (decl))
26831 goto done;
26833 /* Use the source location of the definition. */
26834 DECL_SOURCE_LOCATION (decl) = DECL_SOURCE_LOCATION (tmpl);
26836 args_depth = TMPL_ARGS_DEPTH (args);
26837 parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
26838 if (args_depth > parms_depth)
26839 args = get_innermost_template_args (args, parms_depth);
26841 /* Instantiate a dynamic exception-specification. noexcept will be
26842 handled below. */
26843 if (tree raises = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (code_pattern)))
26844 if (TREE_VALUE (raises))
26846 specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
26847 args, tf_error, NULL_TREE,
26848 /*defer_ok*/false);
26849 if (specs && specs != error_mark_node)
26850 TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
26851 specs);
26854 /* Merge parameter declarations. */
26855 if (tree pattern_parm
26856 = skip_artificial_parms_for (code_pattern,
26857 DECL_ARGUMENTS (code_pattern)))
26859 tree *p = &DECL_ARGUMENTS (decl);
26860 for (int skip = num_artificial_parms_for (decl); skip; --skip)
26861 p = &DECL_CHAIN (*p);
26862 *p = tsubst_decl (pattern_parm, args, tf_error);
26863 for (tree t = *p; t; t = DECL_CHAIN (t))
26864 DECL_CONTEXT (t) = decl;
26867 if (DECL_CONTRACTS (decl))
26869 /* If we're regenerating a specialization, the contracts will have
26870 been copied from the most general template. Replace those with
26871 the ones from the actual specialization. */
26872 tree tmpl = DECL_TI_TEMPLATE (decl);
26873 if (DECL_TEMPLATE_SPECIALIZATION (tmpl))
26875 remove_contract_attributes (decl);
26876 copy_contract_attributes (decl, code_pattern);
26879 tsubst_contract_attributes (decl, args, tf_warning_or_error, code_pattern);
26882 /* Merge additional specifiers from the CODE_PATTERN. */
26883 if (DECL_DECLARED_INLINE_P (code_pattern)
26884 && !DECL_DECLARED_INLINE_P (decl))
26885 DECL_DECLARED_INLINE_P (decl) = 1;
26887 maybe_instantiate_noexcept (decl, tf_error);
26889 else if (VAR_P (decl))
26891 start_lambda_scope (decl);
26892 DECL_INITIAL (decl) =
26893 tsubst_init (DECL_INITIAL (code_pattern), decl, args,
26894 tf_error, DECL_TI_TEMPLATE (decl));
26895 finish_lambda_scope ();
26896 if (VAR_HAD_UNKNOWN_BOUND (decl))
26897 TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
26898 tf_error, DECL_TI_TEMPLATE (decl));
26900 else
26901 gcc_unreachable ();
26903 done:
26904 pop_access_scope (decl);
26907 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
26908 substituted to get DECL. */
26910 tree
26911 template_for_substitution (tree decl)
26913 tree tmpl = DECL_TI_TEMPLATE (decl);
26915 /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
26916 for the instantiation. This is not always the most general
26917 template. Consider, for example:
26919 template <class T>
26920 struct S { template <class U> void f();
26921 template <> void f<int>(); };
26923 and an instantiation of S<double>::f<int>. We want TD to be the
26924 specialization S<T>::f<int>, not the more general S<T>::f<U>. */
26925 while (/* An instantiation cannot have a definition, so we need a
26926 more general template. */
26927 DECL_TEMPLATE_INSTANTIATION (tmpl)
26928 /* We must also deal with friend templates. Given:
26930 template <class T> struct S {
26931 template <class U> friend void f() {};
26934 S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
26935 so far as the language is concerned, but that's still
26936 where we get the pattern for the instantiation from. On
26937 other hand, if the definition comes outside the class, say:
26939 template <class T> struct S {
26940 template <class U> friend void f();
26942 template <class U> friend void f() {}
26944 we don't need to look any further. That's what the check for
26945 DECL_INITIAL is for. */
26946 || (TREE_CODE (decl) == FUNCTION_DECL
26947 && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
26948 && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
26950 /* The present template, TD, should not be a definition. If it
26951 were a definition, we should be using it! Note that we
26952 cannot restructure the loop to just keep going until we find
26953 a template with a definition, since that might go too far if
26954 a specialization was declared, but not defined. */
26956 /* Fetch the more general template. */
26957 tmpl = DECL_TI_TEMPLATE (tmpl);
26960 return tmpl;
26963 /* Returns true if we need to instantiate this template instance even if we
26964 know we aren't going to emit it. */
26966 bool
26967 always_instantiate_p (tree decl)
26969 /* We always instantiate inline functions so that we can inline them. An
26970 explicit instantiation declaration prohibits implicit instantiation of
26971 non-inline functions. With high levels of optimization, we would
26972 normally inline non-inline functions -- but we're not allowed to do
26973 that for "extern template" functions. Therefore, we check
26974 DECL_DECLARED_INLINE_P, rather than possibly_inlined_p. */
26975 return ((TREE_CODE (decl) == FUNCTION_DECL
26976 && (DECL_DECLARED_INLINE_P (decl)
26977 || type_uses_auto (TREE_TYPE (TREE_TYPE (decl)))))
26978 /* And we need to instantiate static data members so that
26979 their initializers are available in integral constant
26980 expressions. */
26981 || (VAR_P (decl)
26982 && decl_maybe_constant_var_p (decl)));
26985 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
26986 instantiate it now, modifying TREE_TYPE (fn). Returns false on
26987 error, true otherwise. */
26989 bool
26990 maybe_instantiate_noexcept (tree fn, tsubst_flags_t complain)
26992 if (fn == error_mark_node)
26993 return false;
26995 /* Don't instantiate a noexcept-specification from template context. */
26996 if (processing_template_decl
26997 && (!flag_noexcept_type || type_dependent_expression_p (fn)))
26998 return true;
27000 tree fntype = TREE_TYPE (fn);
27001 tree spec = TYPE_RAISES_EXCEPTIONS (fntype);
27003 if ((!spec || UNEVALUATED_NOEXCEPT_SPEC_P (spec))
27004 && DECL_MAYBE_DELETED (fn))
27006 if (fn == current_function_decl)
27007 /* We're in start_preparsed_function, keep going. */
27008 return true;
27010 ++function_depth;
27011 maybe_synthesize_method (fn);
27012 --function_depth;
27013 return !DECL_DELETED_FN (fn);
27016 if (!spec || !TREE_PURPOSE (spec))
27017 return true;
27019 tree noex = TREE_PURPOSE (spec);
27020 if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
27021 && TREE_CODE (noex) != DEFERRED_PARSE)
27022 return true;
27024 tree orig_fn = NULL_TREE;
27025 /* For a member friend template we can get a TEMPLATE_DECL. Let's use
27026 its FUNCTION_DECL for the rest of this function -- push_access_scope
27027 doesn't accept TEMPLATE_DECLs. */
27028 if (DECL_FUNCTION_TEMPLATE_P (fn))
27030 orig_fn = fn;
27031 fn = DECL_TEMPLATE_RESULT (fn);
27034 if (DECL_CLONED_FUNCTION_P (fn))
27036 tree prime = DECL_CLONED_FUNCTION (fn);
27037 if (!maybe_instantiate_noexcept (prime, complain))
27038 return false;
27039 spec = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (prime));
27041 else if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
27043 static hash_set<tree>* fns = new hash_set<tree>;
27044 bool added = false;
27045 if (DEFERRED_NOEXCEPT_PATTERN (noex) == NULL_TREE)
27047 spec = get_defaulted_eh_spec (fn, complain);
27048 if (spec == error_mark_node)
27049 /* This might have failed because of an unparsed DMI, so
27050 let's try again later. */
27051 return false;
27053 else if (!(added = !fns->add (fn)))
27055 /* If hash_set::add returns true, the element was already there. */
27056 location_t loc = cp_expr_loc_or_loc (DEFERRED_NOEXCEPT_PATTERN (noex),
27057 DECL_SOURCE_LOCATION (fn));
27058 error_at (loc,
27059 "exception specification of %qD depends on itself",
27060 fn);
27061 spec = noexcept_false_spec;
27063 else if (push_tinst_level (fn))
27065 const bool push_to_top = maybe_push_to_top_level (fn);
27066 push_access_scope (fn);
27067 push_deferring_access_checks (dk_no_deferred);
27068 input_location = DECL_SOURCE_LOCATION (fn);
27070 if (DECL_IOBJ_MEMBER_FUNCTION_P (fn)
27071 && !DECL_LOCAL_DECL_P (fn))
27073 /* If needed, set current_class_ptr for the benefit of
27074 tsubst_copy/PARM_DECL. */
27075 tree this_parm = DECL_ARGUMENTS (fn);
27076 current_class_ptr = NULL_TREE;
27077 current_class_ref = cp_build_fold_indirect_ref (this_parm);
27078 current_class_ptr = this_parm;
27081 /* If this function is represented by a TEMPLATE_DECL, then
27082 the deferred noexcept-specification might still contain
27083 dependent types, even after substitution. And we need the
27084 dependency check functions to work in build_noexcept_spec. */
27085 if (orig_fn)
27086 ++processing_template_decl;
27088 /* Do deferred instantiation of the noexcept-specifier. */
27089 noex = tsubst_expr (DEFERRED_NOEXCEPT_PATTERN (noex),
27090 DEFERRED_NOEXCEPT_ARGS (noex),
27091 tf_warning_or_error, fn);
27092 /* Build up the noexcept-specification. */
27093 spec = build_noexcept_spec (noex, tf_warning_or_error);
27095 if (orig_fn)
27096 --processing_template_decl;
27098 pop_deferring_access_checks ();
27099 pop_access_scope (fn);
27100 pop_tinst_level ();
27101 maybe_pop_from_top_level (push_to_top);
27103 else
27104 spec = noexcept_false_spec;
27106 if (added)
27107 fns->remove (fn);
27110 if (spec == error_mark_node)
27112 /* This failed with a hard error, so let's go with false. */
27113 gcc_assert (seen_error ());
27114 spec = noexcept_false_spec;
27117 TREE_TYPE (fn) = build_exception_variant (fntype, spec);
27118 if (orig_fn)
27119 TREE_TYPE (orig_fn) = TREE_TYPE (fn);
27121 return true;
27124 /* We're starting to process the function INST, an instantiation of PATTERN;
27125 add their parameters to local_specializations. */
27127 void
27128 register_parameter_specializations (tree pattern, tree inst)
27130 tree tmpl_parm = DECL_ARGUMENTS (pattern);
27131 tree spec_parm = DECL_ARGUMENTS (inst);
27132 if (DECL_IOBJ_MEMBER_FUNCTION_P (inst))
27134 register_local_specialization (spec_parm, tmpl_parm);
27135 spec_parm = skip_artificial_parms_for (inst, spec_parm);
27136 tmpl_parm = skip_artificial_parms_for (pattern, tmpl_parm);
27138 for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
27140 if (!DECL_PACK_P (tmpl_parm))
27142 register_local_specialization (spec_parm, tmpl_parm);
27143 spec_parm = DECL_CHAIN (spec_parm);
27145 else
27147 /* Register the (value) argument pack as a specialization of
27148 TMPL_PARM, then move on. */
27149 tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
27150 register_local_specialization (argpack, tmpl_parm);
27153 gcc_assert (!spec_parm);
27156 /* Instantiate the body of D using PATTERN with ARGS. We have
27157 already determined PATTERN is the correct template to use.
27158 NESTED_P is true if this is a nested function, in which case
27159 PATTERN will be a FUNCTION_DECL not a TEMPLATE_DECL. */
27161 static void
27162 instantiate_body (tree pattern, tree args, tree d, bool nested_p)
27164 tree td = NULL_TREE;
27165 tree code_pattern = pattern;
27167 if (!nested_p)
27169 td = pattern;
27170 code_pattern = DECL_TEMPLATE_RESULT (td);
27172 else
27173 /* Only OMP reductions are nested. */
27174 gcc_checking_assert (DECL_OMP_DECLARE_REDUCTION_P (code_pattern));
27176 vec<tree> omp_privatization_save;
27177 if (current_function_decl)
27178 save_omp_privatization_clauses (omp_privatization_save);
27180 bool push_to_top = maybe_push_to_top_level (d);
27182 mark_template_arguments_used (pattern, args);
27184 if (VAR_P (d))
27186 /* The variable might be a lambda's extra scope, and that
27187 lambda's visibility depends on D's. */
27188 maybe_commonize_var (d);
27189 determine_visibility (d);
27192 /* Mark D as instantiated so that recursive calls to
27193 instantiate_decl do not try to instantiate it again. */
27194 DECL_TEMPLATE_INSTANTIATED (d) = 1;
27196 if (td)
27197 /* Regenerate the declaration in case the template has been modified
27198 by a subsequent redeclaration. */
27199 regenerate_decl_from_template (d, td, args);
27201 /* We already set the file and line above. Reset them now in case
27202 they changed as a result of calling regenerate_decl_from_template. */
27203 input_location = DECL_SOURCE_LOCATION (d);
27205 if (VAR_P (d))
27207 /* Clear out DECL_RTL; whatever was there before may not be right
27208 since we've reset the type of the declaration. */
27209 SET_DECL_RTL (d, NULL);
27210 DECL_IN_AGGR_P (d) = 0;
27212 /* The initializer is placed in DECL_INITIAL by
27213 regenerate_decl_from_template so we don't need to
27214 push/pop_access_scope again here. Pull it out so that
27215 cp_finish_decl can process it. */
27216 bool const_init = false;
27217 tree init = DECL_INITIAL (d);
27218 DECL_INITIAL (d) = NULL_TREE;
27219 DECL_INITIALIZED_P (d) = 0;
27221 /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
27222 initializer. That function will defer actual emission until
27223 we have a chance to determine linkage. */
27224 DECL_EXTERNAL (d) = 0;
27226 /* Enter the scope of D so that access-checking works correctly. */
27227 bool enter_context = DECL_CLASS_SCOPE_P (d);
27228 if (enter_context)
27229 push_nested_class (DECL_CONTEXT (d));
27231 const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
27232 cp_finish_decl (d, init, const_init, NULL_TREE, 0);
27234 if (enter_context)
27235 pop_nested_class ();
27237 else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
27238 synthesize_method (d);
27239 else if (TREE_CODE (d) == FUNCTION_DECL)
27241 /* Set up the list of local specializations. */
27242 local_specialization_stack lss (push_to_top ? lss_blank : lss_copy);
27243 tree block = NULL_TREE;
27245 /* Set up context. */
27246 if (nested_p)
27247 block = push_stmt_list ();
27248 else
27250 start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
27252 perform_instantiation_time_access_checks (code_pattern, args);
27255 /* Create substitution entries for the parameters. */
27256 register_parameter_specializations (code_pattern, d);
27258 /* Substitute into the body of the function. */
27259 if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
27260 tsubst_omp_udr (DECL_SAVED_TREE (code_pattern), args,
27261 tf_warning_or_error, d);
27262 else
27264 tsubst_stmt (DECL_SAVED_TREE (code_pattern), args,
27265 tf_warning_or_error, DECL_TI_TEMPLATE (d));
27267 /* Set the current input_location to the end of the function
27268 so that finish_function knows where we are. */
27269 input_location
27270 = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
27272 /* Remember if we saw an infinite loop in the template. */
27273 current_function_infinite_loop
27274 = DECL_STRUCT_FUNCTION (code_pattern)->language->infinite_loop;
27277 /* Finish the function. */
27278 if (nested_p)
27279 DECL_SAVED_TREE (d) = pop_stmt_list (block);
27280 else
27282 d = finish_function (/*inline_p=*/false);
27283 expand_or_defer_fn (d);
27286 if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
27287 cp_check_omp_declare_reduction (d);
27290 /* We're not deferring instantiation any more. */
27291 if (!nested_p)
27292 TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
27294 maybe_pop_from_top_level (push_to_top);
27296 if (current_function_decl)
27297 restore_omp_privatization_clauses (omp_privatization_save);
27300 /* Produce the definition of D, a _DECL generated from a template. If
27301 DEFER_OK is true, then we don't have to actually do the
27302 instantiation now; we just have to do it sometime. Normally it is
27303 an error if this is an explicit instantiation but D is undefined.
27304 EXPL_INST_CLASS_MEM_P is true iff D is a member of an explicitly
27305 instantiated class template. */
27307 tree
27308 instantiate_decl (tree d, bool defer_ok, bool expl_inst_class_mem_p)
27310 tree tmpl = DECL_TI_TEMPLATE (d);
27311 tree gen_args;
27312 tree args;
27313 tree td;
27314 tree code_pattern;
27315 tree spec;
27316 tree gen_tmpl;
27317 bool pattern_defined;
27318 location_t saved_loc = input_location;
27319 bool external_p;
27320 bool deleted_p;
27322 /* This function should only be used to instantiate templates for
27323 functions and static member variables. */
27324 gcc_assert (VAR_OR_FUNCTION_DECL_P (d));
27326 gcc_checking_assert (!DECL_FUNCTION_SCOPE_P (d));
27328 if (modules_p ())
27329 /* We may have a pending instantiation of D itself. */
27330 lazy_load_pendings (d);
27332 /* Variables are never deferred; if instantiation is required, they
27333 are instantiated right away. That allows for better code in the
27334 case that an expression refers to the value of the variable --
27335 if the variable has a constant value the referring expression can
27336 take advantage of that fact. */
27337 if (VAR_P (d))
27338 defer_ok = false;
27340 /* Don't instantiate cloned functions. Instead, instantiate the
27341 functions they cloned. */
27342 if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
27343 d = DECL_CLONED_FUNCTION (d);
27345 if (DECL_TEMPLATE_INSTANTIATED (d)
27346 || TREE_TYPE (d) == error_mark_node
27347 || (TREE_CODE (d) == FUNCTION_DECL
27348 && DECL_DEFAULTED_FN (d) && DECL_INITIAL (d))
27349 || DECL_TEMPLATE_SPECIALIZATION (d))
27350 /* D has already been instantiated or explicitly specialized, so
27351 there's nothing for us to do here.
27353 It might seem reasonable to check whether or not D is an explicit
27354 instantiation, and, if so, stop here. But when an explicit
27355 instantiation is deferred until the end of the compilation,
27356 DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
27357 the instantiation. */
27358 return d;
27360 /* Check to see whether we know that this template will be
27361 instantiated in some other file, as with "extern template"
27362 extension. */
27363 external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
27365 /* In general, we do not instantiate such templates. */
27366 if (external_p && !always_instantiate_p (d))
27367 return d;
27369 gen_tmpl = most_general_template (tmpl);
27370 gen_args = DECL_TI_ARGS (d);
27372 /* We should already have the extra args. */
27373 gcc_checking_assert (tmpl == gen_tmpl
27374 || (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
27375 == TMPL_ARGS_DEPTH (gen_args)));
27376 /* And what's in the hash table should match D. */
27377 gcc_checking_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0))
27378 == d
27379 || spec == NULL_TREE);
27381 /* This needs to happen before any tsubsting. */
27382 if (! push_tinst_level (d))
27383 return d;
27385 auto_timevar tv (TV_TEMPLATE_INST);
27387 /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
27388 for the instantiation. */
27389 td = template_for_substitution (d);
27390 args = gen_args;
27392 if (variable_template_specialization_p (d))
27394 /* Look up an explicit specialization, if any. */
27395 tree partial_ti = most_specialized_partial_spec (d, tf_warning_or_error);
27396 if (partial_ti && partial_ti != error_mark_node)
27398 td = TI_TEMPLATE (partial_ti);
27399 args = TI_ARGS (partial_ti);
27403 maybe_diagnose_erroneous_template (td);
27405 code_pattern = DECL_TEMPLATE_RESULT (td);
27407 /* We should never be trying to instantiate a member of a class
27408 template or partial specialization. */
27409 gcc_assert (d != code_pattern);
27411 if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
27412 || DECL_TEMPLATE_SPECIALIZATION (td))
27413 /* In the case of a friend template whose definition is provided
27414 outside the class, we may have too many arguments. Drop the
27415 ones we don't need. The same is true for specializations. */
27416 args = get_innermost_template_args
27417 (args, TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (td)));
27419 if (TREE_CODE (d) == FUNCTION_DECL)
27421 deleted_p = DECL_DELETED_FN (code_pattern);
27422 pattern_defined = ((DECL_SAVED_TREE (code_pattern) != NULL_TREE
27423 && DECL_INITIAL (code_pattern) != error_mark_node)
27424 || DECL_DEFAULTED_FN (code_pattern)
27425 || deleted_p);
27427 else
27429 deleted_p = false;
27430 if (DECL_CLASS_SCOPE_P (code_pattern))
27431 pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
27432 else
27433 pattern_defined = ! DECL_EXTERNAL (code_pattern);
27436 /* We may be in the middle of deferred access check. Disable it now. */
27437 push_deferring_access_checks (dk_no_deferred);
27439 /* Unless an explicit instantiation directive has already determined
27440 the linkage of D, remember that a definition is available for
27441 this entity. */
27442 if (pattern_defined
27443 && !DECL_INTERFACE_KNOWN (d)
27444 && !DECL_NOT_REALLY_EXTERN (d))
27445 mark_definable (d);
27447 DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
27448 DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
27449 input_location = DECL_SOURCE_LOCATION (d);
27451 /* If D is a member of an explicitly instantiated class template,
27452 and no definition is available, treat it like an implicit
27453 instantiation. */
27454 if (!pattern_defined && expl_inst_class_mem_p
27455 && DECL_EXPLICIT_INSTANTIATION (d))
27457 /* Leave linkage flags alone on instantiations with anonymous
27458 visibility. */
27459 if (TREE_PUBLIC (d))
27461 DECL_NOT_REALLY_EXTERN (d) = 0;
27462 DECL_INTERFACE_KNOWN (d) = 0;
27464 SET_DECL_IMPLICIT_INSTANTIATION (d);
27467 /* Defer all other templates, unless we have been explicitly
27468 forbidden from doing so. */
27469 if (/* If there is no definition, we cannot instantiate the
27470 template. */
27471 ! pattern_defined
27472 /* If it's OK to postpone instantiation, do so. */
27473 || defer_ok
27474 /* If this is a static data member that will be defined
27475 elsewhere, we don't want to instantiate the entire data
27476 member, but we do want to instantiate the initializer so that
27477 we can substitute that elsewhere. */
27478 || (external_p && VAR_P (d))
27479 /* Handle here a deleted function too, avoid generating
27480 its body (c++/61080). */
27481 || deleted_p)
27483 /* The definition of the static data member is now required so
27484 we must substitute the initializer. */
27485 if (VAR_P (d)
27486 && !DECL_INITIAL (d)
27487 && DECL_INITIAL (code_pattern))
27489 tree ns;
27490 tree init;
27491 bool const_init = false;
27492 bool enter_context = DECL_CLASS_SCOPE_P (d);
27494 ns = decl_namespace_context (d);
27495 push_nested_namespace (ns);
27496 if (enter_context)
27497 push_nested_class (DECL_CONTEXT (d));
27498 init = tsubst_expr (DECL_INITIAL (code_pattern),
27499 args,
27500 tf_warning_or_error, NULL_TREE);
27501 /* If instantiating the initializer involved instantiating this
27502 again, don't call cp_finish_decl twice. */
27503 if (!DECL_INITIAL (d))
27505 /* Make sure the initializer is still constant, in case of
27506 circular dependency (template/instantiate6.C). */
27507 const_init
27508 = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
27509 cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
27510 /*asmspec_tree=*/NULL_TREE, 0);
27512 if (enter_context)
27513 pop_nested_class ();
27514 pop_nested_namespace (ns);
27517 /* We restore the source position here because it's used by
27518 add_pending_template. */
27519 input_location = saved_loc;
27521 if (at_eof && !pattern_defined
27522 && DECL_EXPLICIT_INSTANTIATION (d)
27523 && DECL_NOT_REALLY_EXTERN (d))
27524 /* [temp.explicit]
27526 The definition of a non-exported function template, a
27527 non-exported member function template, or a non-exported
27528 member function or static data member of a class template
27529 shall be present in every translation unit in which it is
27530 explicitly instantiated. */
27531 permerror (input_location, "explicit instantiation of %qD "
27532 "but no definition available", d);
27534 /* If we're in unevaluated context, we just wanted to get the
27535 constant value; this isn't an odr use, so don't queue
27536 a full instantiation. */
27537 if (!cp_unevaluated_operand
27538 /* ??? Historically, we have instantiated inline functions, even
27539 when marked as "extern template". */
27540 && !(external_p && VAR_P (d)))
27541 add_pending_template (d);
27543 else
27545 set_instantiating_module (d);
27546 if (variable_template_p (gen_tmpl))
27547 note_vague_linkage_variable (d);
27548 instantiate_body (td, args, d, false);
27551 pop_deferring_access_checks ();
27552 pop_tinst_level ();
27553 input_location = saved_loc;
27555 return d;
27558 /* Run through the list of templates that we wish we could
27559 instantiate, and instantiate any we can. RETRIES is the
27560 number of times we retry pending template instantiation. */
27562 void
27563 instantiate_pending_templates (int retries)
27565 int reconsider;
27566 location_t saved_loc = input_location;
27568 /* Instantiating templates may trigger vtable generation. This in turn
27569 may require further template instantiations. We place a limit here
27570 to avoid infinite loop. */
27571 if (pending_templates && retries >= max_tinst_depth)
27573 tree decl = pending_templates->tinst->maybe_get_node ();
27575 fatal_error (input_location,
27576 "template instantiation depth exceeds maximum of %d"
27577 " instantiating %q+D, possibly from virtual table generation"
27578 " (use %<-ftemplate-depth=%> to increase the maximum)",
27579 max_tinst_depth, decl);
27580 if (TREE_CODE (decl) == FUNCTION_DECL)
27581 /* Pretend that we defined it. */
27582 DECL_INITIAL (decl) = error_mark_node;
27583 return;
27588 struct pending_template **t = &pending_templates;
27589 struct pending_template *last = NULL;
27590 reconsider = 0;
27591 while (*t)
27593 tree instantiation = reopen_tinst_level ((*t)->tinst);
27594 bool complete = false;
27596 if (TYPE_P (instantiation))
27598 if (!COMPLETE_TYPE_P (instantiation))
27600 instantiate_class_template (instantiation);
27601 if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
27602 for (tree fld = TYPE_FIELDS (instantiation);
27603 fld; fld = TREE_CHAIN (fld))
27604 if ((VAR_P (fld)
27605 || (TREE_CODE (fld) == FUNCTION_DECL
27606 && !DECL_ARTIFICIAL (fld)))
27607 && DECL_TEMPLATE_INSTANTIATION (fld))
27608 instantiate_decl (fld,
27609 /*defer_ok=*/false,
27610 /*expl_inst_class_mem_p=*/false);
27612 if (COMPLETE_TYPE_P (instantiation))
27613 reconsider = 1;
27616 complete = COMPLETE_TYPE_P (instantiation);
27618 else
27620 if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
27621 && !DECL_TEMPLATE_INSTANTIATED (instantiation))
27623 instantiation
27624 = instantiate_decl (instantiation,
27625 /*defer_ok=*/false,
27626 /*expl_inst_class_mem_p=*/false);
27627 if (DECL_TEMPLATE_INSTANTIATED (instantiation))
27628 reconsider = 1;
27631 complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
27632 || DECL_TEMPLATE_INSTANTIATED (instantiation));
27635 if (complete)
27637 /* If INSTANTIATION has been instantiated, then we don't
27638 need to consider it again in the future. */
27639 struct pending_template *drop = *t;
27640 *t = (*t)->next;
27641 set_refcount_ptr (drop->tinst);
27642 pending_template_freelist ().free (drop);
27644 else
27646 last = *t;
27647 t = &(*t)->next;
27649 tinst_depth = 0;
27650 set_refcount_ptr (current_tinst_level);
27652 last_pending_template = last;
27654 while (reconsider);
27656 input_location = saved_loc;
27659 /* Substitute ARGVEC into T, which is a list of initializers for
27660 either base class or a non-static data member. The TREE_PURPOSEs
27661 are DECLs, and the TREE_VALUEs are the initializer values. Used by
27662 instantiate_decl. */
27664 static tree
27665 tsubst_initializer_list (tree t, tree argvec)
27667 tree inits = NULL_TREE;
27668 tree target_ctor = error_mark_node;
27670 for (; t; t = TREE_CHAIN (t))
27672 tree decl;
27673 tree init;
27674 tree expanded_bases = NULL_TREE;
27675 tree expanded_arguments = NULL_TREE;
27676 int i, len = 1;
27678 if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
27680 tree expr;
27681 tree arg;
27683 /* Expand the base class expansion type into separate base
27684 classes. */
27685 expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
27686 tf_warning_or_error,
27687 NULL_TREE);
27688 if (expanded_bases == error_mark_node)
27689 continue;
27691 /* We'll be building separate TREE_LISTs of arguments for
27692 each base. */
27693 len = TREE_VEC_LENGTH (expanded_bases);
27694 expanded_arguments = make_tree_vec (len);
27695 for (i = 0; i < len; i++)
27696 TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
27698 /* Build a dummy EXPR_PACK_EXPANSION that will be used to
27699 expand each argument in the TREE_VALUE of t. */
27700 expr = make_node (EXPR_PACK_EXPANSION);
27701 PACK_EXPANSION_LOCAL_P (expr) = true;
27702 PACK_EXPANSION_PARAMETER_PACKS (expr) =
27703 PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
27705 if (TREE_VALUE (t) == void_type_node)
27706 /* VOID_TYPE_NODE is used to indicate
27707 value-initialization. */
27709 for (i = 0; i < len; i++)
27710 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
27712 else
27714 /* Substitute parameter packs into each argument in the
27715 TREE_LIST. */
27716 in_base_initializer = 1;
27717 for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
27719 tree expanded_exprs;
27721 /* Expand the argument. */
27722 tree value;
27723 if (TREE_CODE (TREE_VALUE (arg)) == EXPR_PACK_EXPANSION)
27724 value = TREE_VALUE (arg);
27725 else
27727 value = expr;
27728 PACK_EXPANSION_PATTERN (value) = TREE_VALUE (arg);
27730 expanded_exprs
27731 = tsubst_pack_expansion (value, argvec,
27732 tf_warning_or_error,
27733 NULL_TREE);
27734 if (expanded_exprs == error_mark_node)
27735 continue;
27737 /* Prepend each of the expanded expressions to the
27738 corresponding TREE_LIST in EXPANDED_ARGUMENTS. */
27739 for (i = 0; i < len; i++)
27740 if (TREE_CODE (TREE_VALUE (arg)) == EXPR_PACK_EXPANSION)
27741 for (int j = 0; j < TREE_VEC_LENGTH (expanded_exprs); j++)
27742 TREE_VEC_ELT (expanded_arguments, i)
27743 = tree_cons (NULL_TREE,
27744 TREE_VEC_ELT (expanded_exprs, j),
27745 TREE_VEC_ELT (expanded_arguments, i));
27746 else
27747 TREE_VEC_ELT (expanded_arguments, i)
27748 = tree_cons (NULL_TREE,
27749 TREE_VEC_ELT (expanded_exprs, i),
27750 TREE_VEC_ELT (expanded_arguments, i));
27752 in_base_initializer = 0;
27754 /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
27755 since we built them backwards. */
27756 for (i = 0; i < len; i++)
27758 TREE_VEC_ELT (expanded_arguments, i) =
27759 nreverse (TREE_VEC_ELT (expanded_arguments, i));
27764 for (i = 0; i < len; ++i)
27766 if (expanded_bases)
27768 decl = TREE_VEC_ELT (expanded_bases, i);
27769 decl = expand_member_init (decl);
27770 init = TREE_VEC_ELT (expanded_arguments, i);
27772 else
27774 tree tmp;
27775 if (TYPE_P (TREE_PURPOSE (t)))
27776 decl = tsubst (TREE_PURPOSE (t), argvec,
27777 tf_warning_or_error, NULL_TREE);
27778 else
27779 decl = tsubst_expr (TREE_PURPOSE (t), argvec,
27780 tf_warning_or_error, NULL_TREE);
27782 decl = expand_member_init (decl);
27783 if (decl && !DECL_P (decl))
27784 in_base_initializer = 1;
27786 init = TREE_VALUE (t);
27787 tmp = init;
27788 if (init != void_type_node)
27789 init = tsubst_expr (init, argvec,
27790 tf_warning_or_error, NULL_TREE);
27791 if (init == NULL_TREE && tmp != NULL_TREE)
27792 /* If we had an initializer but it instantiated to nothing,
27793 value-initialize the object. This will only occur when
27794 the initializer was a pack expansion where the parameter
27795 packs used in that expansion were of length zero. */
27796 init = void_type_node;
27797 in_base_initializer = 0;
27800 if (target_ctor != error_mark_node
27801 && init != error_mark_node)
27803 error ("mem-initializer for %qD follows constructor delegation",
27804 decl);
27805 return inits;
27807 /* Look for a target constructor. */
27808 if (init != error_mark_node
27809 && decl && CLASS_TYPE_P (decl)
27810 && same_type_p (decl, current_class_type))
27812 maybe_warn_cpp0x (CPP0X_DELEGATING_CTORS);
27813 if (inits)
27815 error ("constructor delegation follows mem-initializer for %qD",
27816 TREE_PURPOSE (inits));
27817 continue;
27819 target_ctor = init;
27822 if (decl)
27824 init = build_tree_list (decl, init);
27825 /* Carry over the dummy TREE_TYPE node containing the source
27826 location. */
27827 TREE_TYPE (init) = TREE_TYPE (t);
27828 TREE_CHAIN (init) = inits;
27829 inits = init;
27833 return inits;
27836 /* Instantiate an enumerated type. TAG is the template type, NEWTAG
27837 is the instantiation (which should have been created with
27838 start_enum) and ARGS are the template arguments to use. */
27840 static void
27841 tsubst_enum (tree tag, tree newtag, tree args)
27843 tree e;
27845 if (SCOPED_ENUM_P (newtag))
27846 begin_scope (sk_scoped_enum, newtag);
27848 for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
27850 tree value;
27851 tree decl = TREE_VALUE (e);
27853 /* Note that in a template enum, the TREE_VALUE is the
27854 CONST_DECL, not the corresponding INTEGER_CST. */
27855 value = tsubst_expr (DECL_INITIAL (decl),
27856 args, tf_warning_or_error, NULL_TREE);
27858 /* Give this enumeration constant the correct access. */
27859 set_current_access_from_decl (decl);
27861 /* Actually build the enumerator itself. Here we're assuming that
27862 enumerators can't have dependent attributes. */
27863 tree newdecl = build_enumerator (DECL_NAME (decl), value, newtag,
27864 DECL_ATTRIBUTES (decl),
27865 DECL_SOURCE_LOCATION (decl));
27866 /* Attribute deprecated without an argument isn't sticky: it'll
27867 melt into a tree flag, so we need to propagate the flag here,
27868 since we just created a new enumerator. */
27869 TREE_DEPRECATED (newdecl) = TREE_DEPRECATED (decl);
27870 TREE_UNAVAILABLE (newdecl) = TREE_UNAVAILABLE (decl);
27873 if (SCOPED_ENUM_P (newtag))
27874 finish_scope ();
27876 finish_enum_value_list (newtag);
27877 finish_enum (newtag);
27879 DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
27880 = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
27881 TREE_DEPRECATED (newtag) = TREE_DEPRECATED (tag);
27882 TREE_UNAVAILABLE (newtag) = TREE_UNAVAILABLE (tag);
27885 /* DECL is a FUNCTION_DECL that is a template specialization. Return
27886 its type -- but without substituting the innermost set of template
27887 arguments. So, innermost set of template parameters will appear in
27888 the type. */
27890 tree
27891 get_mostly_instantiated_function_type (tree decl)
27893 /* For a function, DECL_TI_TEMPLATE is partially instantiated. */
27894 return TREE_TYPE (DECL_TI_TEMPLATE (decl));
27897 /* Return truthvalue if we're processing a template different from
27898 the last one involved in diagnostics. */
27899 bool
27900 problematic_instantiation_changed (void)
27902 return current_tinst_level != last_error_tinst_level;
27905 /* Remember current template involved in diagnostics. */
27906 void
27907 record_last_problematic_instantiation (void)
27909 set_refcount_ptr (last_error_tinst_level, current_tinst_level);
27912 struct tinst_level *
27913 current_instantiation (void)
27915 return current_tinst_level;
27918 /* Return TRUE if current_function_decl is being instantiated, false
27919 otherwise. */
27921 bool
27922 instantiating_current_function_p (void)
27924 return (current_instantiation ()
27925 && (current_instantiation ()->maybe_get_node ()
27926 == current_function_decl));
27929 /* [temp.param] Check that template non-type parm TYPE is of an allowable
27930 type. Return false for ok, true for disallowed. Issue error and
27931 inform messages under control of COMPLAIN. */
27933 static bool
27934 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
27936 if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
27937 return false;
27938 else if (TYPE_PTR_P (type))
27939 return false;
27940 else if (TYPE_REF_P (type)
27941 && !TYPE_REF_IS_RVALUE (type))
27942 return false;
27943 else if (TYPE_PTRMEM_P (type))
27944 return false;
27945 else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
27947 if (CLASS_PLACEHOLDER_TEMPLATE (type) && cxx_dialect < cxx20)
27949 if (complain & tf_error)
27950 error ("non-type template parameters of deduced class type only "
27951 "available with %<-std=c++20%> or %<-std=gnu++20%>");
27952 return true;
27954 return false;
27956 else if (TREE_CODE (type) == NULLPTR_TYPE)
27957 return false;
27958 else if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM
27959 && cxx_dialect < cxx11)
27960 /* Fall through; before C++11 alias templates, a bound ttp
27961 always instantiates into a class type. */;
27962 else if (WILDCARD_TYPE_P (type))
27963 /* Any other wildcard type not already handled above is allowed. */
27964 return false;
27965 else if (TREE_CODE (type) == COMPLEX_TYPE)
27966 /* Fall through. */;
27967 else if (VOID_TYPE_P (type))
27968 /* Fall through. */;
27969 else if (cxx_dialect >= cxx20)
27971 if (dependent_type_p (type))
27972 return false;
27973 if (!complete_type_or_maybe_complain (type, NULL_TREE, complain))
27974 return true;
27975 if (structural_type_p (type))
27976 return false;
27977 if (complain & tf_error)
27979 auto_diagnostic_group d;
27980 error ("%qT is not a valid type for a template non-type "
27981 "parameter because it is not structural", type);
27982 structural_type_p (type, true);
27984 return true;
27986 else if (CLASS_TYPE_P (type))
27988 if (complain & tf_error)
27989 error ("non-type template parameters of class type only available "
27990 "with %<-std=c++20%> or %<-std=gnu++20%>");
27991 return true;
27994 if (complain & tf_error)
27996 if (type == error_mark_node)
27997 inform (input_location, "invalid template non-type parameter");
27998 else
27999 error ("%q#T is not a valid type for a template non-type parameter",
28000 type);
28002 return true;
28005 /* Returns true iff the noexcept-specifier for TYPE is value-dependent. */
28007 static bool
28008 value_dependent_noexcept_spec_p (tree type)
28010 if (tree spec = TYPE_RAISES_EXCEPTIONS (type))
28011 if (tree noex = TREE_PURPOSE (spec))
28012 /* Treat DEFERRED_NOEXCEPT as non-dependent, since it doesn't
28013 affect overload resolution and treating it as dependent breaks
28014 things. Same for an unparsed noexcept expression. */
28015 if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
28016 && TREE_CODE (noex) != DEFERRED_PARSE
28017 && value_dependent_expression_p (noex))
28018 return true;
28020 return false;
28023 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
28024 Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
28026 static bool
28027 dependent_type_p_r (tree type)
28029 tree scope;
28031 /* [temp.dep.type]
28033 A type is dependent if it is:
28035 -- a template parameter. Template template parameters are types
28036 for us (since TYPE_P holds true for them) so we handle
28037 them here. */
28038 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
28039 || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
28040 return true;
28041 /* -- a qualified-id with a nested-name-specifier which contains a
28042 class-name that names a dependent type or whose unqualified-id
28043 names a dependent type. */
28044 if (TREE_CODE (type) == TYPENAME_TYPE)
28045 return true;
28047 /* -- a cv-qualified type where the cv-unqualified type is
28048 dependent.
28049 No code is necessary for this bullet; the code below handles
28050 cv-qualified types, and we don't want to strip aliases with
28051 TYPE_MAIN_VARIANT because of DR 1558. */
28052 /* -- a compound type constructed from any dependent type. */
28053 if (TYPE_PTRMEM_P (type))
28054 return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
28055 || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
28056 (type)));
28057 else if (INDIRECT_TYPE_P (type))
28058 return dependent_type_p (TREE_TYPE (type));
28059 else if (FUNC_OR_METHOD_TYPE_P (type))
28061 tree arg_type;
28063 if (dependent_type_p (TREE_TYPE (type)))
28064 return true;
28065 for (arg_type = TYPE_ARG_TYPES (type);
28066 arg_type;
28067 arg_type = TREE_CHAIN (arg_type))
28068 if (dependent_type_p (TREE_VALUE (arg_type)))
28069 return true;
28070 if (cxx_dialect >= cxx17
28071 && value_dependent_noexcept_spec_p (type))
28072 /* A value-dependent noexcept-specifier makes the type dependent. */
28073 return true;
28074 return false;
28076 /* -- an array type constructed from any dependent type or whose
28077 size is specified by a constant expression that is
28078 value-dependent.
28080 We checked for type- and value-dependence of the bounds in
28081 compute_array_index_type, so TYPE_DEPENDENT_P is already set. */
28082 if (TREE_CODE (type) == ARRAY_TYPE)
28084 if (TYPE_DOMAIN (type)
28085 && dependent_type_p (TYPE_DOMAIN (type)))
28086 return true;
28087 return dependent_type_p (TREE_TYPE (type));
28090 /* -- a template-id in which either the template name is a template
28091 parameter ... */
28092 if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
28093 return true;
28094 /* ... or any of the template arguments is a dependent type or
28095 an expression that is type-dependent or value-dependent. */
28096 else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
28097 && (any_dependent_template_arguments_p
28098 (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
28099 return true;
28101 /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and TRAIT_TYPEs are
28102 dependent; if the argument of the `typeof' expression is not
28103 type-dependent, then it should already been have resolved. */
28104 if (TREE_CODE (type) == TYPEOF_TYPE
28105 || TREE_CODE (type) == DECLTYPE_TYPE
28106 || TREE_CODE (type) == TRAIT_TYPE)
28107 return true;
28109 /* A template argument pack is dependent if any of its packed
28110 arguments are. */
28111 if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
28113 tree args = ARGUMENT_PACK_ARGS (type);
28114 for (tree arg : tree_vec_range (args))
28115 if (dependent_template_arg_p (arg))
28116 return true;
28119 /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
28120 be template parameters. */
28121 if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
28122 return true;
28124 if (TREE_CODE (type) == DEPENDENT_OPERATOR_TYPE)
28125 return true;
28127 if (any_dependent_type_attributes_p (TYPE_ATTRIBUTES (type)))
28128 return true;
28130 /* The standard does not specifically mention types that are local
28131 to template functions or local classes, but they should be
28132 considered dependent too. For example:
28134 template <int I> void f() {
28135 enum E { a = I };
28136 S<sizeof (E)> s;
28139 The size of `E' cannot be known until the value of `I' has been
28140 determined. Therefore, `E' must be considered dependent. */
28141 scope = TYPE_CONTEXT (type);
28142 if (scope && TYPE_P (scope))
28143 return dependent_type_p (scope);
28144 /* Don't use type_dependent_expression_p here, as it can lead
28145 to infinite recursion trying to determine whether a lambda
28146 nested in a lambda is dependent (c++/47687). */
28147 else if (scope && TREE_CODE (scope) == FUNCTION_DECL
28148 && DECL_LANG_SPECIFIC (scope)
28149 && DECL_TEMPLATE_INFO (scope)
28150 && (any_dependent_template_arguments_p
28151 (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
28152 return true;
28154 /* Other types are non-dependent. */
28155 return false;
28158 /* Returns TRUE if TYPE is dependent, in the sense of
28159 [temp.dep.type]. Note that a NULL type is considered dependent. */
28161 bool
28162 dependent_type_p (tree type)
28164 /* If there are no template parameters in scope, then there can't be
28165 any dependent types. */
28166 if (!processing_template_decl)
28168 /* If we are not processing a template, then nobody should be
28169 providing us with a dependent type. */
28170 gcc_assert (type);
28171 gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type)
28172 || seen_error ());
28173 return false;
28176 /* If the type is NULL, we have not computed a type for the entity
28177 in question; in that case, the type is dependent. */
28178 if (!type)
28179 return true;
28181 /* Erroneous types can be considered non-dependent. */
28182 if (type == error_mark_node)
28183 return false;
28185 /* If we have not already computed the appropriate value for TYPE,
28186 do so now. */
28187 if (!TYPE_DEPENDENT_P_VALID (type))
28189 TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
28190 TYPE_DEPENDENT_P_VALID (type) = 1;
28193 return TYPE_DEPENDENT_P (type);
28196 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
28197 lookup. In other words, a dependent type that is not the current
28198 instantiation. */
28200 bool
28201 dependent_scope_p (tree scope)
28203 return (scope && TYPE_P (scope) && dependent_type_p (scope)
28204 && !currently_open_class (scope));
28207 /* True if we might find more declarations in SCOPE during instantiation than
28208 we can when parsing the template. */
28210 bool
28211 dependentish_scope_p (tree scope)
28213 return dependent_scope_p (scope) || any_dependent_bases_p (scope);
28216 /* T is a SCOPE_REF. Return whether it represents a non-static member of
28217 an unknown base of 'this' (and is therefore instantiation-dependent). */
28219 static bool
28220 unknown_base_ref_p (tree t)
28222 if (!current_class_ptr)
28223 return false;
28225 tree mem = TREE_OPERAND (t, 1);
28226 if (shared_member_p (mem))
28227 return false;
28229 tree cur = current_nonlambda_class_type ();
28230 if (!any_dependent_bases_p (cur))
28231 return false;
28233 tree ctx = TREE_OPERAND (t, 0);
28234 if (DERIVED_FROM_P (ctx, cur))
28235 return false;
28237 return true;
28240 /* T is a SCOPE_REF; return whether we need to consider it
28241 instantiation-dependent so that we can check access at instantiation
28242 time even though we know which member it resolves to. */
28244 static bool
28245 instantiation_dependent_scope_ref_p (tree t)
28247 if (DECL_P (TREE_OPERAND (t, 1))
28248 && CLASS_TYPE_P (TREE_OPERAND (t, 0))
28249 && !dependent_scope_p (TREE_OPERAND (t, 0))
28250 && !unknown_base_ref_p (t)
28251 && accessible_in_template_p (TREE_OPERAND (t, 0),
28252 TREE_OPERAND (t, 1)))
28253 return false;
28254 else
28255 return true;
28258 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
28259 [temp.dep.constexpr]. EXPRESSION is already known to be a constant
28260 expression. */
28262 /* Note that this predicate is not appropriate for general expressions;
28263 only constant expressions (that satisfy potential_constant_expression)
28264 can be tested for value dependence. */
28266 bool
28267 value_dependent_expression_p (tree expression)
28269 if (!processing_template_decl || expression == NULL_TREE)
28270 return false;
28272 /* A type-dependent expression is also value-dependent. */
28273 if (type_dependent_expression_p (expression))
28274 return true;
28276 switch (TREE_CODE (expression))
28278 case BASELINK:
28279 /* A dependent member function of the current instantiation. */
28280 return dependent_type_p (BINFO_TYPE (BASELINK_BINFO (expression)));
28282 case FUNCTION_DECL:
28283 /* A dependent member function of the current instantiation. */
28284 if (DECL_CLASS_SCOPE_P (expression)
28285 && dependent_type_p (DECL_CONTEXT (expression)))
28286 return true;
28287 break;
28289 case IDENTIFIER_NODE:
28290 /* A name that has not been looked up -- must be dependent. */
28291 return true;
28293 case TEMPLATE_PARM_INDEX:
28294 /* A non-type template parm. */
28295 return true;
28297 case CONST_DECL:
28298 /* A non-type template parm. */
28299 if (DECL_TEMPLATE_PARM_P (expression))
28300 return true;
28301 return value_dependent_expression_p (DECL_INITIAL (expression));
28303 case VAR_DECL:
28304 /* A constant with literal type and is initialized
28305 with an expression that is value-dependent. */
28306 if (DECL_DEPENDENT_INIT_P (expression))
28307 return true;
28308 if (DECL_HAS_VALUE_EXPR_P (expression))
28310 tree value_expr = DECL_VALUE_EXPR (expression);
28311 if (value_dependent_expression_p (value_expr)
28312 /* __PRETTY_FUNCTION__ inside a template function is dependent
28313 on the name of the function. */
28314 || (DECL_PRETTY_FUNCTION_P (expression)
28315 /* It might be used in a template, but not a template
28316 function, in which case its DECL_VALUE_EXPR will be
28317 "top level". */
28318 && value_expr == error_mark_node))
28319 return true;
28321 else if (TYPE_REF_P (TREE_TYPE (expression)))
28322 /* FIXME cp_finish_decl doesn't fold reference initializers. */
28323 return true;
28324 /* We have a constexpr variable and we're processing a template. When
28325 there's lifetime extension involved (for which finish_compound_literal
28326 used to create a temporary), we'll not be able to evaluate the
28327 variable until instantiating, so pretend it's value-dependent. */
28328 else if (DECL_DECLARED_CONSTEXPR_P (expression)
28329 && !TREE_CONSTANT (expression))
28330 return true;
28331 return false;
28333 case DYNAMIC_CAST_EXPR:
28334 case STATIC_CAST_EXPR:
28335 case CONST_CAST_EXPR:
28336 case REINTERPRET_CAST_EXPR:
28337 case CAST_EXPR:
28338 case IMPLICIT_CONV_EXPR:
28339 /* These expressions are value-dependent if the type to which
28340 the cast occurs is dependent or the expression being casted
28341 is value-dependent. */
28343 tree type = TREE_TYPE (expression);
28345 if (dependent_type_p (type))
28346 return true;
28348 /* A functional cast has a list of operands. */
28349 expression = TREE_OPERAND (expression, 0);
28350 if (!expression)
28352 /* If there are no operands, it must be an expression such
28353 as "int()". This should not happen for aggregate types
28354 because it would form non-constant expressions. */
28355 gcc_assert (cxx_dialect >= cxx11
28356 || INTEGRAL_OR_ENUMERATION_TYPE_P (type));
28358 return false;
28361 if (TREE_CODE (expression) == TREE_LIST)
28362 return any_value_dependent_elements_p (expression);
28364 if (TREE_CODE (type) == REFERENCE_TYPE
28365 && has_value_dependent_address (expression))
28366 return true;
28368 return value_dependent_expression_p (expression);
28371 case SIZEOF_EXPR:
28372 if (SIZEOF_EXPR_TYPE_P (expression))
28373 return dependent_type_p (TREE_TYPE (TREE_OPERAND (expression, 0)));
28374 /* FALLTHRU */
28375 case ALIGNOF_EXPR:
28376 case TYPEID_EXPR:
28377 /* A `sizeof' expression is value-dependent if the operand is
28378 type-dependent or is a pack expansion. */
28379 expression = TREE_OPERAND (expression, 0);
28380 if (PACK_EXPANSION_P (expression))
28381 return true;
28382 else if (TYPE_P (expression))
28383 return dependent_type_p (expression);
28384 return instantiation_dependent_uneval_expression_p (expression);
28386 case AT_ENCODE_EXPR:
28387 /* An 'encode' expression is value-dependent if the operand is
28388 type-dependent. */
28389 expression = TREE_OPERAND (expression, 0);
28390 return dependent_type_p (expression);
28392 case NOEXCEPT_EXPR:
28393 expression = TREE_OPERAND (expression, 0);
28394 return instantiation_dependent_uneval_expression_p (expression);
28396 case SCOPE_REF:
28397 /* All instantiation-dependent expressions should also be considered
28398 value-dependent. */
28399 return instantiation_dependent_scope_ref_p (expression);
28401 case COMPONENT_REF:
28402 return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
28403 || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
28405 case NONTYPE_ARGUMENT_PACK:
28406 /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
28407 is value-dependent. */
28408 for (tree arg : tree_vec_range (ARGUMENT_PACK_ARGS (expression)))
28409 if (value_dependent_expression_p (arg))
28410 return true;
28411 return false;
28413 case TRAIT_EXPR:
28415 if (dependent_type_p (TRAIT_EXPR_TYPE1 (expression)))
28416 return true;
28418 tree type2 = TRAIT_EXPR_TYPE2 (expression);
28419 if (!type2)
28420 return false;
28422 if (TREE_CODE (type2) != TREE_VEC)
28423 return dependent_type_p (type2);
28425 for (tree arg : tree_vec_range (type2))
28426 if (dependent_type_p (arg))
28427 return true;
28429 return false;
28432 case MODOP_EXPR:
28433 return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
28434 || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
28436 case ARRAY_REF:
28437 return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
28438 || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
28440 case ADDR_EXPR:
28442 tree op = TREE_OPERAND (expression, 0);
28443 return (value_dependent_expression_p (op)
28444 || has_value_dependent_address (op));
28447 case REQUIRES_EXPR:
28448 /* Treat all requires-expressions as value-dependent so
28449 we don't try to fold them. */
28450 return true;
28452 case TYPE_REQ:
28453 return dependent_type_p (TREE_OPERAND (expression, 0));
28455 case CALL_EXPR:
28457 if (value_dependent_expression_p (CALL_EXPR_FN (expression)))
28458 return true;
28459 tree fn = get_callee_fndecl (expression);
28460 int i, nargs;
28461 nargs = call_expr_nargs (expression);
28462 for (i = 0; i < nargs; ++i)
28464 tree op = CALL_EXPR_ARG (expression, i);
28465 /* In a call to a constexpr member function, look through the
28466 implicit ADDR_EXPR on the object argument so that it doesn't
28467 cause the call to be considered value-dependent. We also
28468 look through it in potential_constant_expression. */
28469 if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
28470 && DECL_IOBJ_MEMBER_FUNCTION_P (fn)
28471 && TREE_CODE (op) == ADDR_EXPR)
28472 op = TREE_OPERAND (op, 0);
28473 if (value_dependent_expression_p (op))
28474 return true;
28476 return false;
28479 case TEMPLATE_ID_EXPR:
28480 return concept_definition_p (TREE_OPERAND (expression, 0))
28481 && any_dependent_template_arguments_p (TREE_OPERAND (expression, 1));
28483 case CONSTRUCTOR:
28485 unsigned ix;
28486 tree val;
28487 if (dependent_type_p (TREE_TYPE (expression)))
28488 return true;
28489 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
28490 if (value_dependent_expression_p (val))
28491 return true;
28492 return false;
28495 case STMT_EXPR:
28496 /* Treat a GNU statement expression as dependent to avoid crashing
28497 under instantiate_non_dependent_expr; it can't be constant. */
28498 return true;
28500 case NEW_EXPR:
28501 case VEC_NEW_EXPR:
28502 /* The second operand is a type, which type_dependent_expression_p
28503 (and therefore value_dependent_expression_p) doesn't want to see. */
28504 return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
28505 || value_dependent_expression_p (TREE_OPERAND (expression, 2))
28506 || value_dependent_expression_p (TREE_OPERAND (expression, 3)));
28508 default:
28509 /* A constant expression is value-dependent if any subexpression is
28510 value-dependent. */
28511 switch (TREE_CODE_CLASS (TREE_CODE (expression)))
28513 case tcc_reference:
28514 case tcc_unary:
28515 case tcc_comparison:
28516 case tcc_binary:
28517 case tcc_expression:
28518 case tcc_vl_exp:
28520 int i, len = cp_tree_operand_length (expression);
28522 for (i = 0; i < len; i++)
28524 tree t = TREE_OPERAND (expression, i);
28526 /* In some cases, some of the operands may be missing.
28527 (For example, in the case of PREDECREMENT_EXPR, the
28528 amount to increment by may be missing.) That doesn't
28529 make the expression dependent. */
28530 if (t && value_dependent_expression_p (t))
28531 return true;
28534 break;
28535 default:
28536 break;
28538 break;
28541 /* The expression is not value-dependent. */
28542 return false;
28545 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
28546 [temp.dep.expr]. Note that an expression with no type is
28547 considered dependent. Other parts of the compiler arrange for an
28548 expression with type-dependent subexpressions to have no type, so
28549 this function doesn't have to be fully recursive. */
28551 bool
28552 type_dependent_expression_p (tree expression)
28554 if (!processing_template_decl)
28555 return false;
28557 if (expression == NULL_TREE || expression == error_mark_node)
28558 return false;
28560 gcc_checking_assert (!TYPE_P (expression));
28562 STRIP_ANY_LOCATION_WRAPPER (expression);
28564 /* An unresolved name is always dependent. */
28565 if (identifier_p (expression)
28566 || TREE_CODE (expression) == USING_DECL
28567 || TREE_CODE (expression) == WILDCARD_DECL)
28568 return true;
28570 /* A lambda-expression in template context is dependent. dependent_type_p is
28571 true for a lambda in the scope of a class or function template, but that
28572 doesn't cover all template contexts, like a default template argument. */
28573 if (TREE_CODE (expression) == LAMBDA_EXPR)
28574 return true;
28576 /* A fold expression is type-dependent. */
28577 if (TREE_CODE (expression) == UNARY_LEFT_FOLD_EXPR
28578 || TREE_CODE (expression) == UNARY_RIGHT_FOLD_EXPR
28579 || TREE_CODE (expression) == BINARY_LEFT_FOLD_EXPR
28580 || TREE_CODE (expression) == BINARY_RIGHT_FOLD_EXPR)
28581 return true;
28583 /* Some expression forms are never type-dependent. */
28584 if (TREE_CODE (expression) == SIZEOF_EXPR
28585 || TREE_CODE (expression) == ALIGNOF_EXPR
28586 || TREE_CODE (expression) == AT_ENCODE_EXPR
28587 || TREE_CODE (expression) == NOEXCEPT_EXPR
28588 || TREE_CODE (expression) == TRAIT_EXPR
28589 || TREE_CODE (expression) == TYPEID_EXPR
28590 || TREE_CODE (expression) == DELETE_EXPR
28591 || TREE_CODE (expression) == VEC_DELETE_EXPR
28592 || TREE_CODE (expression) == THROW_EXPR
28593 || TREE_CODE (expression) == REQUIRES_EXPR)
28594 return false;
28596 /* The types of these expressions depends only on the type to which
28597 the cast occurs. */
28598 if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
28599 || TREE_CODE (expression) == STATIC_CAST_EXPR
28600 || TREE_CODE (expression) == CONST_CAST_EXPR
28601 || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
28602 || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
28603 || TREE_CODE (expression) == CAST_EXPR)
28604 return dependent_type_p (TREE_TYPE (expression));
28606 /* The types of these expressions depends only on the type created
28607 by the expression. */
28608 if (TREE_CODE (expression) == NEW_EXPR
28609 || TREE_CODE (expression) == VEC_NEW_EXPR)
28611 /* For NEW_EXPR tree nodes created inside a template, either
28612 the object type itself or a TREE_LIST may appear as the
28613 operand 1. */
28614 tree type = TREE_OPERAND (expression, 1);
28615 if (TREE_CODE (type) == TREE_LIST)
28616 /* This is an array type. We need to check array dimensions
28617 as well. */
28618 return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
28619 || value_dependent_expression_p
28620 (TREE_OPERAND (TREE_VALUE (type), 1));
28621 /* Array type whose dimension has to be deduced. */
28622 else if (TREE_CODE (type) == ARRAY_TYPE
28623 && TREE_OPERAND (expression, 2) == NULL_TREE)
28624 return true;
28625 else
28626 return dependent_type_p (type);
28629 if (TREE_CODE (expression) == SCOPE_REF)
28631 tree scope = TREE_OPERAND (expression, 0);
28632 tree name = TREE_OPERAND (expression, 1);
28634 /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
28635 contains an identifier associated by name lookup with one or more
28636 declarations declared with a dependent type, or...a
28637 nested-name-specifier or qualified-id that names a member of an
28638 unknown specialization. */
28639 return (type_dependent_expression_p (name)
28640 || dependent_scope_p (scope));
28643 if (TREE_CODE (expression) == TEMPLATE_DECL
28644 && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
28645 return uses_outer_template_parms (expression);
28647 if (TREE_CODE (expression) == STMT_EXPR)
28648 expression = stmt_expr_value_expr (expression);
28650 if (BRACE_ENCLOSED_INITIALIZER_P (expression))
28652 for (auto &elt : CONSTRUCTOR_ELTS (expression))
28653 if (type_dependent_expression_p (elt.value))
28654 return true;
28655 return false;
28658 /* A static data member of the current instantiation with incomplete
28659 array type is type-dependent, as the definition and specializations
28660 can have different bounds. */
28661 if (VAR_P (expression)
28662 && DECL_CLASS_SCOPE_P (expression)
28663 && dependent_type_p (DECL_CONTEXT (expression))
28664 && VAR_HAD_UNKNOWN_BOUND (expression))
28665 return true;
28667 /* An array of unknown bound depending on a variadic parameter, eg:
28669 template<typename... Args>
28670 void foo (Args... args)
28672 int arr[] = { args... };
28675 template<int... vals>
28676 void bar ()
28678 int arr[] = { vals... };
28681 If the array has no length and has an initializer, it must be that
28682 we couldn't determine its length in cp_complete_array_type because
28683 it is dependent. */
28684 if (((VAR_P (expression) && DECL_INITIAL (expression))
28685 || COMPOUND_LITERAL_P (expression))
28686 && TREE_TYPE (expression) != NULL_TREE
28687 && TREE_CODE (TREE_TYPE (expression)) == ARRAY_TYPE
28688 && !TYPE_DOMAIN (TREE_TYPE (expression)))
28689 return true;
28691 /* Pull a FUNCTION_DECL out of a BASELINK if we can. */
28692 if (BASELINK_P (expression))
28694 if (BASELINK_OPTYPE (expression)
28695 && dependent_type_p (BASELINK_OPTYPE (expression)))
28696 return true;
28697 expression = BASELINK_FUNCTIONS (expression);
28700 /* A function or variable template-id is type-dependent if it has any
28701 dependent template arguments. */
28702 if (VAR_OR_FUNCTION_DECL_P (expression)
28703 && DECL_LANG_SPECIFIC (expression)
28704 && DECL_TEMPLATE_INFO (expression))
28706 /* Consider the innermost template arguments, since those are the ones
28707 that come from the template-id; the template arguments for the
28708 enclosing class do not make it type-dependent unless they are used in
28709 the type of the decl. */
28710 if (instantiates_primary_template_p (expression)
28711 && (any_dependent_template_arguments_p
28712 (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
28713 return true;
28716 /* Otherwise, if the function decl isn't from a dependent scope, it can't be
28717 type-dependent. Checking this is important for functions with auto return
28718 type, which looks like a dependent type. */
28719 if (TREE_CODE (expression) == FUNCTION_DECL
28720 && !(DECL_CLASS_SCOPE_P (expression)
28721 && dependent_type_p (DECL_CONTEXT (expression)))
28722 && !(DECL_LANG_SPECIFIC (expression)
28723 && DECL_UNIQUE_FRIEND_P (expression)
28724 && (!DECL_FRIEND_CONTEXT (expression)
28725 || dependent_type_p (DECL_FRIEND_CONTEXT (expression))))
28726 && !DECL_LOCAL_DECL_P (expression))
28728 gcc_assert (!dependent_type_p (TREE_TYPE (expression))
28729 || undeduced_auto_decl (expression));
28730 return false;
28733 /* Otherwise, its constraints could still depend on outer template parameters
28734 from its (dependent) scope. */
28735 if (TREE_CODE (expression) == FUNCTION_DECL
28736 /* As an optimization, check this cheaper sufficient condition first.
28737 (At this point we've established that we're looking at a member of
28738 a dependent class, so it makes sense to start treating say undeduced
28739 auto as dependent.) */
28740 && !dependent_type_p (TREE_TYPE (expression))
28741 && uses_outer_template_parms_in_constraints (expression))
28742 return true;
28744 /* Always dependent, on the number of arguments if nothing else. */
28745 if (TREE_CODE (expression) == EXPR_PACK_EXPANSION)
28746 return true;
28748 if (TREE_TYPE (expression) == unknown_type_node)
28750 if (TREE_CODE (expression) == ADDR_EXPR)
28751 return type_dependent_expression_p (TREE_OPERAND (expression, 0));
28752 if (TREE_CODE (expression) == COMPONENT_REF
28753 || TREE_CODE (expression) == OFFSET_REF)
28755 if (type_dependent_object_expression_p (TREE_OPERAND (expression, 0)))
28756 return true;
28757 expression = TREE_OPERAND (expression, 1);
28758 if (identifier_p (expression))
28759 return false;
28761 /* SCOPE_REF with non-null TREE_TYPE is always non-dependent. */
28762 if (TREE_CODE (expression) == SCOPE_REF)
28763 return false;
28765 if (BASELINK_P (expression))
28767 if (BASELINK_OPTYPE (expression)
28768 && dependent_type_p (BASELINK_OPTYPE (expression)))
28769 return true;
28770 expression = BASELINK_FUNCTIONS (expression);
28773 if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
28775 if (any_dependent_template_arguments_p
28776 (TREE_OPERAND (expression, 1)))
28777 return true;
28778 expression = TREE_OPERAND (expression, 0);
28779 if (identifier_p (expression))
28780 return true;
28783 gcc_assert (OVL_P (expression));
28785 for (lkp_iterator iter (expression); iter; ++iter)
28786 if (type_dependent_expression_p (*iter))
28787 return true;
28789 return false;
28792 /* The type of a non-type template parm declared with a placeholder type
28793 depends on the corresponding template argument, even though
28794 placeholders are not normally considered dependent. */
28795 if (TREE_CODE (expression) == TEMPLATE_PARM_INDEX
28796 && is_auto (TREE_TYPE (expression)))
28797 return true;
28799 gcc_assert (TREE_CODE (expression) != TYPE_DECL);
28801 /* Dependent type attributes might not have made it from the decl to
28802 the type yet. */
28803 if (DECL_P (expression)
28804 && any_dependent_type_attributes_p (DECL_ATTRIBUTES (expression)))
28805 return true;
28807 return (dependent_type_p (TREE_TYPE (expression)));
28810 /* [temp.dep.expr]/5: A class member access expression (5.2.5) is
28811 type-dependent if the expression refers to a member of the current
28812 instantiation and the type of the referenced member is dependent, or the
28813 class member access expression refers to a member of an unknown
28814 specialization.
28816 This function returns true if the OBJECT in such a class member access
28817 expression is of an unknown specialization. */
28819 bool
28820 type_dependent_object_expression_p (tree object)
28822 /* An IDENTIFIER_NODE can sometimes have a TREE_TYPE, but it's still
28823 dependent. */
28824 if (TREE_CODE (object) == IDENTIFIER_NODE)
28825 return true;
28826 tree scope = TREE_TYPE (object);
28827 return (!scope || dependent_scope_p (scope));
28830 /* walk_tree callback function for instantiation_dependent_expression_p,
28831 below. Returns non-zero if a dependent subexpression is found. */
28833 static tree
28834 instantiation_dependent_r (tree *tp, int *walk_subtrees,
28835 void * /*data*/)
28837 if (TYPE_P (*tp))
28839 /* We don't have to worry about decltype currently because decltype
28840 of an instantiation-dependent expr is a dependent type. This
28841 might change depending on the resolution of DR 1172. */
28842 *walk_subtrees = false;
28843 return NULL_TREE;
28845 enum tree_code code = TREE_CODE (*tp);
28846 switch (code)
28848 /* Don't treat an argument list as dependent just because it has no
28849 TREE_TYPE. */
28850 case TREE_LIST:
28851 case TREE_VEC:
28852 case NONTYPE_ARGUMENT_PACK:
28853 return NULL_TREE;
28855 case TEMPLATE_PARM_INDEX:
28856 if (dependent_type_p (TREE_TYPE (*tp)))
28857 return *tp;
28858 if (TEMPLATE_PARM_PARAMETER_PACK (*tp))
28859 return *tp;
28860 /* We'll check value-dependence separately. */
28861 return NULL_TREE;
28863 /* Handle expressions with type operands. */
28864 case SIZEOF_EXPR:
28865 case ALIGNOF_EXPR:
28866 case TYPEID_EXPR:
28867 case AT_ENCODE_EXPR:
28869 tree op = TREE_OPERAND (*tp, 0);
28870 if (code == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (*tp))
28871 op = TREE_TYPE (op);
28872 if (TYPE_P (op))
28874 if (dependent_type_p (op))
28875 return *tp;
28876 else
28878 *walk_subtrees = false;
28879 return NULL_TREE;
28882 break;
28885 case COMPONENT_REF:
28886 if (identifier_p (TREE_OPERAND (*tp, 1)))
28887 /* In a template, finish_class_member_access_expr creates a
28888 COMPONENT_REF with an IDENTIFIER_NODE for op1 even if it isn't
28889 type-dependent, so that we can check access control at
28890 instantiation time (PR 42277). See also Core issue 1273. */
28891 return *tp;
28892 break;
28894 case SCOPE_REF:
28895 if (instantiation_dependent_scope_ref_p (*tp))
28896 return *tp;
28897 else
28898 break;
28900 /* Treat statement-expressions as dependent. */
28901 case BIND_EXPR:
28902 return *tp;
28904 /* Treat requires-expressions as dependent. */
28905 case REQUIRES_EXPR:
28906 return *tp;
28908 case CONSTRUCTOR:
28909 if (CONSTRUCTOR_IS_DEPENDENT (*tp))
28910 return *tp;
28911 break;
28913 case TEMPLATE_DECL:
28914 case FUNCTION_DECL:
28915 /* Before C++17, a noexcept-specifier isn't part of the function type
28916 so it doesn't affect type dependence, but we still want to consider it
28917 for instantiation dependence. */
28918 if (cxx_dialect < cxx17
28919 && DECL_DECLARES_FUNCTION_P (*tp)
28920 && value_dependent_noexcept_spec_p (TREE_TYPE (*tp)))
28921 return *tp;
28922 break;
28924 default:
28925 break;
28928 if (type_dependent_expression_p (*tp))
28929 return *tp;
28930 else
28931 return NULL_TREE;
28934 /* Returns TRUE if the EXPRESSION is instantiation-dependent, in the
28935 sense defined by the ABI:
28937 "An expression is instantiation-dependent if it is type-dependent
28938 or value-dependent, or it has a subexpression that is type-dependent
28939 or value-dependent."
28941 Except don't actually check value-dependence for unevaluated expressions,
28942 because in sizeof(i) we don't care about the value of i. Checking
28943 type-dependence will in turn check value-dependence of array bounds/template
28944 arguments as needed. */
28946 bool
28947 instantiation_dependent_uneval_expression_p (tree expression)
28949 tree result;
28951 if (!processing_template_decl)
28952 return false;
28954 if (expression == error_mark_node)
28955 return false;
28957 result = cp_walk_tree_without_duplicates (&expression,
28958 instantiation_dependent_r, NULL);
28959 return result != NULL_TREE;
28962 /* As above, but also check value-dependence of the expression as a whole. */
28964 bool
28965 instantiation_dependent_expression_p (tree expression)
28967 return (instantiation_dependent_uneval_expression_p (expression)
28968 || (processing_template_decl
28969 && potential_constant_expression (expression)
28970 && value_dependent_expression_p (expression)));
28973 /* Like type_dependent_expression_p, but it also works while not processing
28974 a template definition, i.e. during substitution or mangling. */
28976 bool
28977 type_dependent_expression_p_push (tree expr)
28979 bool b;
28980 ++processing_template_decl;
28981 b = type_dependent_expression_p (expr);
28982 --processing_template_decl;
28983 return b;
28986 /* Returns TRUE if ARGS contains a type-dependent expression. */
28988 bool
28989 any_type_dependent_arguments_p (const vec<tree, va_gc> *args)
28991 if (!processing_template_decl || !args)
28992 return false;
28994 for (tree arg : *args)
28995 if (type_dependent_expression_p (arg))
28996 return true;
28998 return false;
29001 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
29002 expressions) contains any type-dependent expressions. */
29004 bool
29005 any_type_dependent_elements_p (const_tree list)
29007 for (; list; list = TREE_CHAIN (list))
29008 if (type_dependent_expression_p (TREE_VALUE (list)))
29009 return true;
29011 return false;
29014 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
29015 expressions) contains any value-dependent expressions. */
29017 bool
29018 any_value_dependent_elements_p (const_tree list)
29020 for (; list; list = TREE_CHAIN (list))
29021 if (value_dependent_expression_p (TREE_VALUE (list)))
29022 return true;
29024 return false;
29027 /* Returns TRUE if the ARG (a template argument) is dependent. */
29029 bool
29030 dependent_template_arg_p (tree arg)
29032 if (!processing_template_decl)
29033 return false;
29035 /* Assume a template argument that was wrongly written by the user
29036 is dependent. This is consistent with what
29037 any_dependent_template_arguments_p [that calls this function]
29038 does. */
29039 if (!arg || arg == error_mark_node)
29040 return true;
29042 if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
29043 arg = argument_pack_select_arg (arg);
29045 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
29046 return true;
29047 if (TREE_CODE (arg) == TEMPLATE_DECL)
29049 if (DECL_TEMPLATE_PARM_P (arg))
29050 return true;
29051 /* A member template of a dependent class is not necessarily
29052 type-dependent, but it is a dependent template argument because it
29053 will be a member of an unknown specialization to that template. */
29054 tree scope = CP_DECL_CONTEXT (arg);
29055 return TYPE_P (scope) && dependent_type_p (scope);
29057 else if (ARGUMENT_PACK_P (arg))
29059 tree args = ARGUMENT_PACK_ARGS (arg);
29060 for (tree arg : tree_vec_range (args))
29061 if (dependent_template_arg_p (arg))
29062 return true;
29063 return false;
29065 else if (TYPE_P (arg))
29066 return dependent_type_p (arg);
29067 else
29068 return value_dependent_expression_p (arg);
29071 /* Identify any expressions that use function parms. */
29073 static tree
29074 find_parm_usage_r (tree *tp, int *walk_subtrees, void*)
29076 tree t = *tp;
29077 if (TREE_CODE (t) == PARM_DECL)
29079 *walk_subtrees = 0;
29080 return t;
29082 return NULL_TREE;
29085 /* Returns true if a type specialization formed using the template
29086 arguments ARGS needs to use structural equality. */
29088 bool
29089 any_template_arguments_need_structural_equality_p (tree args)
29091 int i;
29092 int j;
29094 if (!args)
29095 return false;
29096 if (args == error_mark_node)
29097 return true;
29099 for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
29101 tree level = TMPL_ARGS_LEVEL (args, i + 1);
29102 for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
29104 tree arg = TREE_VEC_ELT (level, j);
29105 tree packed_args = NULL_TREE;
29106 int k, len = 1;
29108 if (ARGUMENT_PACK_P (arg))
29110 /* Look inside the argument pack. */
29111 packed_args = ARGUMENT_PACK_ARGS (arg);
29112 len = TREE_VEC_LENGTH (packed_args);
29115 for (k = 0; k < len; ++k)
29117 if (packed_args)
29118 arg = TREE_VEC_ELT (packed_args, k);
29120 if (error_operand_p (arg))
29121 return true;
29122 else if (TREE_CODE (arg) == TEMPLATE_DECL)
29123 continue;
29124 else if (arg == any_targ_node)
29125 /* An any_targ_node argument (added by add_defaults_to_ttp)
29126 makes the corresponding specialization not canonicalizable,
29127 since template_args_equal always return true for it. We
29128 may see this when called from bind_template_template_parm. */
29129 return true;
29130 /* Checking current_function_decl because this structural
29131 comparison is only necessary for redeclaration. */
29132 else if (!current_function_decl
29133 && dependent_template_arg_p (arg)
29134 && (cp_walk_tree_without_duplicates
29135 (&arg, find_parm_usage_r, NULL)))
29136 /* The identity of a class template specialization that uses
29137 a function parameter depends on the identity of the function.
29138 And if this specialization appeared in the trailing return
29139 type thereof, we don't know the identity of the function
29140 (e.g. if it's a redeclaration or a new function) until we
29141 form its signature and go through duplicate_decls. Thus
29142 it's unsafe to decide on a canonical type now (which depends
29143 on the DECL_CONTEXT of the function parameter, which can get
29144 mutated after the fact by duplicate_decls), so just require
29145 structural equality in this case (PR52830). */
29146 return true;
29147 else if (TYPE_P (arg)
29148 && TYPE_STRUCTURAL_EQUALITY_P (arg)
29149 && (dependent_alias_template_spec_p (arg, nt_opaque)
29150 || dependent_opaque_alias_p (arg)))
29151 /* Require structural equality for specializations written
29152 in terms of a dependent alias template specialization. */
29153 return true;
29154 else if (CLASS_TYPE_P (arg)
29155 && TYPE_TEMPLATE_INFO (arg)
29156 && TYPE_STRUCTURAL_EQUALITY_P (arg))
29157 /* Require structural equality for specializations written
29158 in terms of a class template specialization that itself
29159 needs structural equality. */
29160 return true;
29165 return false;
29168 /* Returns true if ARGS (a collection of template arguments) contains
29169 any dependent arguments. */
29171 bool
29172 any_dependent_template_arguments_p (const_tree args)
29174 if (args == error_mark_node)
29175 return true;
29176 if (!processing_template_decl || !args)
29177 return false;
29179 for (int i = 0, depth = TMPL_ARGS_DEPTH (args); i < depth; ++i)
29181 const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
29182 for (tree arg : tree_vec_range (CONST_CAST_TREE (level)))
29183 if (dependent_template_arg_p (arg))
29184 return true;
29187 return false;
29190 /* Returns true if ARGS contains any errors. */
29192 bool
29193 any_erroneous_template_args_p (const_tree args)
29195 int i;
29196 int j;
29198 if (args == error_mark_node)
29199 return true;
29201 if (args && TREE_CODE (args) != TREE_VEC)
29203 if (tree ti = get_template_info (args))
29204 args = TI_ARGS (ti);
29205 else
29206 args = NULL_TREE;
29209 if (!args)
29210 return false;
29212 for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
29214 const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
29215 for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
29216 if (error_operand_p (TREE_VEC_ELT (level, j)))
29217 return true;
29220 return false;
29223 /* Returns TRUE if the template TMPL is type-dependent. */
29225 bool
29226 dependent_template_p (tree tmpl)
29228 if (TREE_CODE (tmpl) == OVERLOAD)
29230 for (lkp_iterator iter (tmpl); iter; ++iter)
29231 if (dependent_template_p (*iter))
29232 return true;
29233 return false;
29236 /* Template template parameters are dependent. */
29237 if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
29238 || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
29239 return true;
29240 /* So are names that have not been looked up. */
29241 if (TREE_CODE (tmpl) == SCOPE_REF || identifier_p (tmpl))
29242 return true;
29243 return false;
29246 /* Returns TRUE if the specialization TMPL<ARGS> is dependent. */
29248 bool
29249 dependent_template_id_p (tree tmpl, tree args)
29251 return (dependent_template_p (tmpl)
29252 || any_dependent_template_arguments_p (args));
29255 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
29256 are dependent. BODY is the body to use for loop transforming
29257 constructs. */
29259 bool
29260 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv, tree body)
29262 int i, k;
29264 if (!processing_template_decl)
29265 return false;
29267 for (i = 0, k = 0; i < TREE_VEC_LENGTH (declv); i++)
29269 tree decl = TREE_VEC_ELT (declv, i);
29270 tree init = TREE_VEC_ELT (initv, i);
29271 tree cond = TREE_VEC_ELT (condv, i);
29272 tree incr = TREE_VEC_ELT (incrv, i);
29274 if (decl == NULL_TREE)
29276 tree stmt = body;
29277 int j = c_omp_find_generated_loop (stmt, k++, cp_walk_subtrees);
29278 init = TREE_VEC_ELT (OMP_FOR_INIT (stmt), j);
29279 decl = TREE_OPERAND (init, 0);
29280 cond = TREE_VEC_ELT (OMP_FOR_INIT (stmt), j);
29281 incr = TREE_VEC_ELT (OMP_FOR_INIT (stmt), j);
29284 if (type_dependent_expression_p (decl)
29285 || TREE_CODE (decl) == SCOPE_REF)
29286 return true;
29288 if (init && type_dependent_expression_p (init))
29289 return true;
29291 if (cond == global_namespace)
29292 return true;
29294 if (type_dependent_expression_p (cond))
29295 return true;
29297 if (COMPARISON_CLASS_P (cond)
29298 && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
29299 || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
29300 return true;
29302 if (TREE_CODE (incr) == MODOP_EXPR)
29304 if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
29305 || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
29306 return true;
29308 else if (type_dependent_expression_p (incr))
29309 return true;
29310 else if (TREE_CODE (incr) == MODIFY_EXPR)
29312 if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
29313 return true;
29314 else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
29316 tree t = TREE_OPERAND (incr, 1);
29317 if (type_dependent_expression_p (TREE_OPERAND (t, 0))
29318 || type_dependent_expression_p (TREE_OPERAND (t, 1)))
29319 return true;
29321 /* If this loop has a class iterator with != comparison
29322 with increment other than i++/++i/i--/--i, make sure the
29323 increment is constant. */
29324 if (CLASS_TYPE_P (TREE_TYPE (decl))
29325 && TREE_CODE (cond) == NE_EXPR)
29327 if (TREE_OPERAND (t, 0) == decl)
29328 t = TREE_OPERAND (t, 1);
29329 else
29330 t = TREE_OPERAND (t, 0);
29331 if (TREE_CODE (t) != INTEGER_CST)
29332 return true;
29338 return false;
29341 /* TYPE is a TYPENAME_TYPE. Returns the ordinary TYPE to which the
29342 TYPENAME_TYPE corresponds. Returns the original TYPENAME_TYPE if
29343 no such TYPE can be found. Note that this function peers inside
29344 uninstantiated templates and therefore should be used only in
29345 extremely limited situations. ONLY_CURRENT_P restricts this
29346 peering to the currently open classes hierarchy (which is required
29347 when comparing types). */
29349 tree
29350 resolve_typename_type (tree type, bool only_current_p)
29352 tree scope;
29353 tree name;
29354 tree decl;
29355 int quals;
29356 tree pushed_scope;
29357 tree result;
29359 gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
29361 scope = TYPE_CONTEXT (type);
29362 /* We shouldn't have built a TYPENAME_TYPE with a non-dependent scope. */
29363 gcc_checking_assert (uses_template_parms (scope));
29365 /* Usually the non-qualified identifier of a TYPENAME_TYPE is
29366 TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of a
29367 TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL
29368 representing the typedef. In that case TYPE_IDENTIFIER (type) is
29369 not the non-qualified identifier of the TYPENAME_TYPE anymore.
29370 So by getting the TYPE_IDENTIFIER of the _main declaration_ of
29371 the TYPENAME_TYPE instead, we avoid messing up with a possible
29372 typedef variant case. */
29373 name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
29375 /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
29376 it first before we can figure out what NAME refers to. */
29377 if (TREE_CODE (scope) == TYPENAME_TYPE)
29379 if (TYPENAME_IS_RESOLVING_P (scope))
29380 /* Given a class template A with a dependent base with nested type C,
29381 typedef typename A::C::C C will land us here, as trying to resolve
29382 the initial A::C leads to the local C typedef, which leads back to
29383 A::C::C. So we break the recursion now. */
29384 return type;
29385 else
29386 scope = resolve_typename_type (scope, only_current_p);
29388 /* If we don't know what SCOPE refers to, then we cannot resolve the
29389 TYPENAME_TYPE. */
29390 if (!CLASS_TYPE_P (scope))
29391 return type;
29392 /* If this is a typedef, we don't want to look inside (c++/11987). */
29393 if (typedef_variant_p (type))
29394 return type;
29395 /* If SCOPE isn't the template itself, it will not have a valid
29396 TYPE_FIELDS list. */
29397 if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
29398 /* scope is either the template itself or a compatible instantiation
29399 like X<T>, so look up the name in the original template. */
29400 scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
29401 /* If scope has no fields, it can't be a current instantiation. Check this
29402 before currently_open_class to avoid infinite recursion (71515). */
29403 if (!TYPE_FIELDS (scope))
29404 return type;
29405 /* If the SCOPE is not the current instantiation, there's no reason
29406 to look inside it. */
29407 if (only_current_p && !currently_open_class (scope))
29408 return type;
29409 /* Enter the SCOPE so that name lookup will be resolved as if we
29410 were in the class definition. In particular, SCOPE will no
29411 longer be considered a dependent type. */
29412 pushed_scope = push_scope (scope);
29413 /* Look up the declaration. */
29414 decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true,
29415 tf_warning_or_error);
29417 result = NULL_TREE;
29419 /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
29420 find a TEMPLATE_DECL. Otherwise, we want to find a TYPE_DECL. */
29421 tree fullname = TYPENAME_TYPE_FULLNAME (type);
29422 if (!decl)
29423 /*nop*/;
29424 else if (identifier_p (fullname)
29425 && TREE_CODE (decl) == TYPE_DECL)
29427 result = TREE_TYPE (decl);
29428 if (result == error_mark_node)
29429 result = NULL_TREE;
29431 else if (TREE_CODE (fullname) == TEMPLATE_ID_EXPR
29432 && DECL_CLASS_TEMPLATE_P (decl))
29434 /* Obtain the template and the arguments. */
29435 tree tmpl = TREE_OPERAND (fullname, 0);
29436 if (TREE_CODE (tmpl) == IDENTIFIER_NODE)
29438 /* We get here with a plain identifier because a previous tentative
29439 parse of the nested-name-specifier as part of a ptr-operator saw
29440 ::template X<A>. The use of ::template is necessary in a
29441 ptr-operator, but wrong in a declarator-id.
29443 [temp.names]: In a qualified-id of a declarator-id, the keyword
29444 template shall not appear at the top level. */
29445 pedwarn (cp_expr_loc_or_input_loc (fullname), OPT_Wpedantic,
29446 "keyword %<template%> not allowed in declarator-id");
29447 tmpl = decl;
29449 tree args = TREE_OPERAND (fullname, 1);
29450 /* Instantiate the template. */
29451 result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
29452 tf_error | tf_user);
29453 result = adjust_type_for_entering_scope (result);
29454 if (result == error_mark_node)
29455 result = NULL_TREE;
29458 /* Leave the SCOPE. */
29459 if (pushed_scope)
29460 pop_scope (pushed_scope);
29462 /* If we failed to resolve it, return the original typename. */
29463 if (!result)
29464 return type;
29466 /* If lookup found a typename type, resolve that too. */
29467 if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
29469 /* Ill-formed programs can cause infinite recursion here, so we
29470 must catch that. */
29471 TYPENAME_IS_RESOLVING_P (result) = 1;
29472 result = resolve_typename_type (result, only_current_p);
29473 TYPENAME_IS_RESOLVING_P (result) = 0;
29476 /* Qualify the resulting type. */
29477 quals = cp_type_quals (type);
29478 if (quals)
29479 result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
29481 return result;
29484 /* Returns a type which represents 'auto' or 'decltype(auto)'. We use a
29485 TEMPLATE_TYPE_PARM with a level one deeper than the actual template parms,
29486 by default. If set_canonical is true, we set TYPE_CANONICAL on it. */
29488 static tree
29489 make_auto_1 (tree name, bool set_canonical, int level = -1)
29491 if (level == -1)
29492 level = current_template_depth + 1;
29493 tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
29494 TYPE_NAME (au) = build_decl (input_location, TYPE_DECL, name, au);
29495 TYPE_STUB_DECL (au) = TYPE_NAME (au);
29496 TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
29497 (0, level, level, TYPE_NAME (au), NULL_TREE);
29498 if (set_canonical)
29499 TYPE_CANONICAL (au) = canonical_type_parameter (au);
29500 DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
29501 SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
29502 if (name == decltype_auto_identifier)
29503 AUTO_IS_DECLTYPE (au) = true;
29505 return au;
29508 tree
29509 make_decltype_auto (void)
29511 return make_auto_1 (decltype_auto_identifier, true);
29514 tree
29515 make_auto (void)
29517 return make_auto_1 (auto_identifier, true);
29520 /* Return a C++17 deduction placeholder for class template TMPL.
29521 There are represented as an 'auto' with the special level 0 and
29522 CLASS_PLACEHOLDER_TEMPLATE set. */
29524 tree
29525 make_template_placeholder (tree tmpl)
29527 tree t = make_auto_1 (auto_identifier, false, /*level=*/0);
29528 CLASS_PLACEHOLDER_TEMPLATE (t) = tmpl;
29529 /* Our canonical type depends on the placeholder. */
29530 TYPE_CANONICAL (t) = canonical_type_parameter (t);
29531 return t;
29534 /* True iff T is a C++17 class template deduction placeholder. */
29536 bool
29537 template_placeholder_p (tree t)
29539 return is_auto (t) && CLASS_PLACEHOLDER_TEMPLATE (t);
29542 /* Return an auto for an explicit cast expression auto(x).
29543 Like CTAD placeholders, these have level 0 so that they're
29544 not accidentally replaced via tsubst and are always directly
29545 resolved via do_auto_deduction. */
29547 tree
29548 make_cast_auto ()
29550 return make_auto_1 (auto_identifier, true, /*level=*/0);
29553 /* Make a "constrained auto" type-specifier. This is an auto or
29554 decltype(auto) type with constraints that must be associated after
29555 deduction. The constraint is formed from the given concept CON
29556 and its optional sequence of template arguments ARGS.
29558 TYPE must be the result of make_auto_type or make_decltype_auto_type. */
29560 static tree
29561 make_constrained_placeholder_type (tree type, tree con, tree args)
29563 /* Build the constraint. */
29564 tree tmpl = DECL_TI_TEMPLATE (con);
29565 tree expr = tmpl;
29566 if (TREE_CODE (con) == FUNCTION_DECL)
29567 expr = ovl_make (tmpl);
29568 ++processing_template_decl;
29569 expr = build_concept_check (expr, type, args, tf_warning_or_error);
29570 --processing_template_decl;
29572 PLACEHOLDER_TYPE_CONSTRAINTS_INFO (type)
29573 = build_tree_list (current_template_parms, expr);
29575 /* Our canonical type depends on the constraint. */
29576 TYPE_CANONICAL (type) = canonical_type_parameter (type);
29578 /* Attach the constraint to the type declaration. */
29579 return TYPE_NAME (type);
29582 /* Make a "constrained auto" type-specifier. */
29584 tree
29585 make_constrained_auto (tree con, tree args)
29587 tree type = make_auto_1 (auto_identifier, false);
29588 return make_constrained_placeholder_type (type, con, args);
29591 /* Make a "constrained decltype(auto)" type-specifier. */
29593 tree
29594 make_constrained_decltype_auto (tree con, tree args)
29596 tree type = make_auto_1 (decltype_auto_identifier, false);
29597 return make_constrained_placeholder_type (type, con, args);
29600 /* Returns true if the placeholder type constraint T has any dependent
29601 (explicit) template arguments. */
29603 static bool
29604 placeholder_type_constraint_dependent_p (tree t)
29606 gcc_assert (concept_check_p (t));
29607 tree args = TREE_OPERAND (t, 1);
29608 tree first = TREE_VEC_ELT (args, 0);
29609 if (ARGUMENT_PACK_P (first))
29611 args = expand_template_argument_pack (args);
29612 first = TREE_VEC_ELT (args, 0);
29614 gcc_checking_assert (TREE_CODE (first) == WILDCARD_DECL
29615 || is_auto (first));
29616 for (int i = 1; i < TREE_VEC_LENGTH (args); ++i)
29617 if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
29618 return true;
29619 return false;
29622 /* Build and return a concept definition. Like other templates, the
29623 CONCEPT_DECL node is wrapped by a TEMPLATE_DECL. This returns the
29624 the TEMPLATE_DECL. */
29626 tree
29627 finish_concept_definition (cp_expr id, tree init, tree attrs)
29629 gcc_assert (identifier_p (id));
29630 gcc_assert (processing_template_decl);
29632 location_t loc = id.get_location();
29634 /* A concept-definition shall not have associated constraints. */
29635 if (TEMPLATE_PARMS_CONSTRAINTS (current_template_parms))
29637 error_at (loc, "a concept cannot be constrained");
29638 TEMPLATE_PARMS_CONSTRAINTS (current_template_parms) = NULL_TREE;
29641 /* A concept-definition shall appear in namespace scope. Templates
29642 aren't allowed in block scope, so we only need to check for class
29643 scope. */
29644 if (TYPE_P (current_scope()) || !DECL_NAMESPACE_SCOPE_P (current_scope ()))
29646 error_at (loc, "concept %qE not in namespace scope", *id);
29647 return error_mark_node;
29650 if (current_template_depth > 1)
29652 error_at (loc, "concept %qE has multiple template parameter lists", *id);
29653 return error_mark_node;
29656 /* Initially build the concept declaration; its type is bool. */
29657 tree decl = build_lang_decl_loc (loc, CONCEPT_DECL, *id, boolean_type_node);
29658 DECL_CONTEXT (decl) = current_scope ();
29659 DECL_INITIAL (decl) = init;
29661 if (attrs)
29662 cplus_decl_attributes (&decl, attrs, 0);
29664 set_originating_module (decl, false);
29666 /* Push the enclosing template. */
29667 return push_template_decl (decl);
29670 /* Given type ARG, return std::initializer_list<ARG>. */
29672 static tree
29673 listify (tree arg)
29675 tree std_init_list = lookup_qualified_name (std_node, init_list_identifier);
29677 if (std_init_list == error_mark_node
29678 || !DECL_CLASS_TEMPLATE_P (std_init_list))
29680 gcc_rich_location richloc (input_location);
29681 maybe_add_include_fixit (&richloc, "<initializer_list>", false);
29682 error_at (&richloc,
29683 "deducing from brace-enclosed initializer list"
29684 " requires %<#include <initializer_list>%>");
29686 return error_mark_node;
29688 tree argvec = make_tree_vec (1);
29689 TREE_VEC_ELT (argvec, 0) = arg;
29691 return lookup_template_class (std_init_list, argvec, NULL_TREE,
29692 NULL_TREE, tf_warning_or_error);
29695 /* Replace auto in TYPE with std::initializer_list<auto>. */
29697 static tree
29698 listify_autos (tree type, tree auto_node)
29700 tree init_auto = listify (strip_top_quals (auto_node));
29701 tree argvec = make_tree_vec (1);
29702 TREE_VEC_ELT (argvec, 0) = init_auto;
29703 if (processing_template_decl)
29704 argvec = add_to_template_args (current_template_args (), argvec);
29705 return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
29708 /* Hash traits for hashing possibly constrained 'auto'
29709 TEMPLATE_TYPE_PARMs for use by do_auto_deduction. */
29711 struct auto_hash : default_hash_traits<tree>
29713 static inline hashval_t hash (tree);
29714 static inline bool equal (tree, tree);
29717 /* Hash the 'auto' T. */
29719 inline hashval_t
29720 auto_hash::hash (tree t)
29722 if (tree c = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (t)))
29723 /* Matching constrained-type-specifiers denote the same template
29724 parameter, so hash the constraint. */
29725 return iterative_hash_placeholder_constraint (c, 0);
29726 else
29727 /* But unconstrained autos are all separate, so just hash the pointer. */
29728 return iterative_hash_object (t, 0);
29731 /* Compare two 'auto's. */
29733 inline bool
29734 auto_hash::equal (tree t1, tree t2)
29736 if (t1 == t2)
29737 return true;
29739 tree c1 = PLACEHOLDER_TYPE_CONSTRAINTS (t1);
29740 tree c2 = PLACEHOLDER_TYPE_CONSTRAINTS (t2);
29742 /* Two unconstrained autos are distinct. */
29743 if (!c1 || !c2)
29744 return false;
29746 return equivalent_placeholder_constraints (c1, c2);
29749 /* The stem for deduction guide names. */
29750 const char *const dguide_base = "__dguide_";
29752 /* Return the name for a deduction guide for class template TMPL. */
29754 tree
29755 dguide_name (tree tmpl)
29757 tree type = (TYPE_P (tmpl) ? tmpl : TREE_TYPE (tmpl));
29758 tree tname = TYPE_IDENTIFIER (type);
29759 char *buf = (char *) alloca (1 + strlen (dguide_base)
29760 + IDENTIFIER_LENGTH (tname));
29761 memcpy (buf, dguide_base, strlen (dguide_base));
29762 memcpy (buf + strlen (dguide_base), IDENTIFIER_POINTER (tname),
29763 IDENTIFIER_LENGTH (tname) + 1);
29764 tree dname = get_identifier (buf);
29765 TREE_TYPE (dname) = type;
29766 return dname;
29769 /* True if NAME is the name of a deduction guide. */
29771 bool
29772 dguide_name_p (tree name)
29774 return (TREE_CODE (name) == IDENTIFIER_NODE
29775 && TREE_TYPE (name)
29776 && startswith (IDENTIFIER_POINTER (name), dguide_base));
29779 /* True if FN is a deduction guide. */
29781 bool
29782 deduction_guide_p (const_tree fn)
29784 if (DECL_P (fn))
29785 if (tree name = DECL_NAME (fn))
29786 return dguide_name_p (name);
29787 return false;
29790 /* True if FN is the copy deduction guide, i.e. A(A)->A. */
29792 bool
29793 copy_guide_p (const_tree fn)
29795 gcc_assert (deduction_guide_p (fn));
29796 if (!DECL_ARTIFICIAL (fn))
29797 return false;
29798 tree parms = FUNCTION_FIRST_USER_PARMTYPE (DECL_TI_TEMPLATE (fn));
29799 return (TREE_CHAIN (parms) == void_list_node
29800 && same_type_p (TREE_VALUE (parms), TREE_TYPE (DECL_NAME (fn))));
29803 /* True if FN is a guide generated from a constructor template. */
29805 bool
29806 template_guide_p (const_tree fn)
29808 gcc_assert (deduction_guide_p (fn));
29809 if (!DECL_ARTIFICIAL (fn))
29810 return false;
29811 tree tmpl = DECL_TI_TEMPLATE (fn);
29812 if (tree org = DECL_ABSTRACT_ORIGIN (tmpl))
29813 return PRIMARY_TEMPLATE_P (org);
29814 return false;
29817 /* True if FN is an aggregate initialization guide or the copy deduction
29818 guide. */
29820 bool
29821 builtin_guide_p (const_tree fn)
29823 if (!deduction_guide_p (fn))
29824 return false;
29825 if (!DECL_ARTIFICIAL (fn))
29826 /* Explicitly declared. */
29827 return false;
29828 if (DECL_ABSTRACT_ORIGIN (fn))
29829 /* Derived from a constructor. */
29830 return false;
29831 return true;
29834 /* True if FN is a C++23 inherited guide. */
29836 bool
29837 inherited_guide_p (const_tree fn)
29839 gcc_assert (deduction_guide_p (fn));
29840 return LANG_DECL_FN_CHECK (fn)->context != NULL_TREE;
29843 /* Set the base class BASE from which the transformed guide FN
29844 was inherited as part of C++23 inherited CTAD. */
29846 static void
29847 set_inherited_guide_context (const_tree fn, tree base)
29849 gcc_assert (deduction_guide_p (fn));
29850 LANG_DECL_FN_CHECK (fn)->context = base;
29853 /* OLDDECL is a _DECL for a template parameter. Return a similar parameter at
29854 LEVEL:INDEX, using tsubst_args and complain for substitution into non-type
29855 template parameter types. Note that the handling of template template
29856 parameters relies on current_template_parms being set appropriately for the
29857 new template. */
29859 static tree
29860 rewrite_template_parm (tree olddecl, unsigned index, unsigned level,
29861 tree tsubst_args, tsubst_flags_t complain)
29863 if (olddecl == error_mark_node)
29864 return error_mark_node;
29866 tree oldidx = get_template_parm_index (olddecl);
29868 tree newtype;
29869 if (TREE_CODE (olddecl) == TYPE_DECL
29870 || TREE_CODE (olddecl) == TEMPLATE_DECL)
29872 tree oldtype = TREE_TYPE (olddecl);
29873 newtype = cxx_make_type (TREE_CODE (oldtype));
29874 TYPE_MAIN_VARIANT (newtype) = newtype;
29876 else
29878 newtype = TREE_TYPE (olddecl);
29879 if (type_uses_auto (newtype))
29881 // Substitute once to fix references to other template parameters.
29882 newtype = tsubst (newtype, tsubst_args,
29883 complain|tf_partial, NULL_TREE);
29884 // Now substitute again to reduce the level of the auto.
29885 newtype = tsubst (newtype, current_template_args (),
29886 complain, NULL_TREE);
29888 else
29889 newtype = tsubst (newtype, tsubst_args,
29890 complain, NULL_TREE);
29893 tree newdecl
29894 = build_decl (DECL_SOURCE_LOCATION (olddecl), TREE_CODE (olddecl),
29895 DECL_NAME (olddecl), newtype);
29896 SET_DECL_TEMPLATE_PARM_P (newdecl);
29898 tree newidx;
29899 if (TREE_CODE (olddecl) == TYPE_DECL
29900 || TREE_CODE (olddecl) == TEMPLATE_DECL)
29902 newidx = TEMPLATE_TYPE_PARM_INDEX (newtype)
29903 = build_template_parm_index (index, level, level,
29904 newdecl, newtype);
29905 TEMPLATE_PARM_PARAMETER_PACK (newidx)
29906 = TEMPLATE_PARM_PARAMETER_PACK (oldidx);
29907 TYPE_STUB_DECL (newtype) = TYPE_NAME (newtype) = newdecl;
29909 if (TREE_CODE (olddecl) == TEMPLATE_DECL)
29911 tree newresult
29912 = build_lang_decl_loc (DECL_SOURCE_LOCATION (olddecl), TYPE_DECL,
29913 DECL_NAME (olddecl), newtype);
29914 DECL_ARTIFICIAL (newresult) = true;
29915 DECL_TEMPLATE_RESULT (newdecl) = newresult;
29916 // First create a copy (ttargs) of tsubst_args with an
29917 // additional level for the template template parameter's own
29918 // template parameters (ttparms).
29919 tree ttparms = (INNERMOST_TEMPLATE_PARMS
29920 (DECL_TEMPLATE_PARMS (olddecl)));
29921 const int depth = TMPL_ARGS_DEPTH (tsubst_args);
29922 tree ttargs = make_tree_vec (depth + 1);
29923 for (int i = 0; i < depth; ++i)
29924 TREE_VEC_ELT (ttargs, i) = TMPL_ARGS_LEVEL (tsubst_args, i + 1);
29925 TREE_VEC_ELT (ttargs, depth)
29926 = template_parms_level_to_args (ttparms);
29927 // Substitute ttargs into ttparms to fix references to
29928 // other template parameters.
29929 ttparms = tsubst_template_parms_level (ttparms, ttargs,
29930 complain|tf_partial);
29931 // Now substitute again with args based on tparms, to reduce
29932 // the level of the ttparms.
29933 ttargs = current_template_args ();
29934 ttparms = tsubst_template_parms_level (ttparms, ttargs,
29935 complain);
29936 // Finally, tack the adjusted parms onto tparms.
29937 ttparms = tree_cons (size_int (level + 1), ttparms,
29938 copy_node (current_template_parms));
29939 // As with all template template parms, the parameter list captured
29940 // by this template template parm that corresponds to its own level
29941 // should be empty. This avoids infinite recursion when structurally
29942 // comparing two such rewritten template template parms (PR102479).
29943 gcc_assert (!TREE_VEC_LENGTH
29944 (TREE_VALUE (TREE_CHAIN (DECL_TEMPLATE_PARMS (olddecl)))));
29945 gcc_assert (TMPL_PARMS_DEPTH (TREE_CHAIN (ttparms)) == level);
29946 TREE_VALUE (TREE_CHAIN (ttparms)) = make_tree_vec (0);
29947 // All done.
29948 DECL_TEMPLATE_PARMS (newdecl) = ttparms;
29949 DECL_TEMPLATE_INFO (newresult)
29950 = build_template_info (newdecl, template_parms_to_args (ttparms));
29953 if (TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (olddecl)))
29954 SET_TYPE_STRUCTURAL_EQUALITY (newtype);
29955 else
29956 TYPE_CANONICAL (newtype) = canonical_type_parameter (newtype);
29958 else
29960 tree oldconst = TEMPLATE_PARM_DECL (oldidx);
29961 tree newconst
29962 = build_decl (DECL_SOURCE_LOCATION (oldconst),
29963 TREE_CODE (oldconst),
29964 DECL_NAME (oldconst), newtype);
29965 TREE_CONSTANT (newconst) = TREE_CONSTANT (newdecl)
29966 = TREE_READONLY (newconst) = TREE_READONLY (newdecl) = true;
29967 SET_DECL_TEMPLATE_PARM_P (newconst);
29968 newidx = build_template_parm_index (index, level, level,
29969 newconst, newtype);
29970 TEMPLATE_PARM_PARAMETER_PACK (newidx)
29971 = TEMPLATE_PARM_PARAMETER_PACK (oldidx);
29972 DECL_INITIAL (newdecl) = DECL_INITIAL (newconst) = newidx;
29975 return newdecl;
29978 /* As rewrite_template_parm, but for the whole TREE_LIST representing a
29979 template parameter. */
29981 static tree
29982 rewrite_tparm_list (tree oldelt, unsigned index, unsigned level,
29983 tree targs, unsigned targs_index, tsubst_flags_t complain)
29985 tree olddecl = TREE_VALUE (oldelt);
29986 tree newdecl = rewrite_template_parm (olddecl, index, level,
29987 targs, complain);
29988 if (newdecl == error_mark_node)
29989 return error_mark_node;
29990 tree newdef = tsubst_template_arg (TREE_PURPOSE (oldelt),
29991 targs, complain, NULL_TREE);
29992 tree list = build_tree_list (newdef, newdecl);
29993 TEMPLATE_PARM_CONSTRAINTS (list)
29994 = tsubst_constraint_info (TEMPLATE_PARM_CONSTRAINTS (oldelt),
29995 targs, complain, NULL_TREE);
29996 int depth = TMPL_ARGS_DEPTH (targs);
29997 TMPL_ARG (targs, depth, targs_index) = template_parm_to_arg (list);
29998 return list;
30001 /* Returns a C++17 class deduction guide template based on the constructor
30002 CTOR. As a special case, CTOR can be a RECORD_TYPE for an implicit default
30003 guide, REFERENCE_TYPE for an implicit copy/move guide, or TREE_LIST for an
30004 aggregate initialization guide. OUTER_ARGS are the template arguments
30005 for the enclosing scope of the class. */
30007 static tree
30008 build_deduction_guide (tree type, tree ctor, tree outer_args, tsubst_flags_t complain)
30010 tree tparms, targs, fparms, fargs, ci;
30011 bool memtmpl = false;
30012 bool explicit_p;
30013 location_t loc;
30014 tree fn_tmpl = NULL_TREE;
30016 if (outer_args)
30018 ++processing_template_decl;
30019 type = tsubst (type, outer_args, complain, CLASSTYPE_TI_TEMPLATE (type));
30020 --processing_template_decl;
30023 if (!DECL_DECLARES_FUNCTION_P (ctor))
30025 if (TYPE_P (ctor))
30027 bool copy_p = TYPE_REF_P (ctor);
30028 if (copy_p)
30029 fparms = tree_cons (NULL_TREE, type, void_list_node);
30030 else
30031 fparms = void_list_node;
30033 else if (TREE_CODE (ctor) == TREE_LIST)
30034 fparms = ctor;
30035 else
30036 gcc_unreachable ();
30038 tree ctmpl = CLASSTYPE_TI_TEMPLATE (type);
30039 tparms = DECL_TEMPLATE_PARMS (ctmpl);
30040 targs = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
30041 ci = NULL_TREE;
30042 fargs = NULL_TREE;
30043 loc = DECL_SOURCE_LOCATION (ctmpl);
30044 explicit_p = false;
30046 else
30048 ++processing_template_decl;
30049 bool ok = true;
30051 complain |= tf_dguide;
30053 fn_tmpl
30054 = (TREE_CODE (ctor) == TEMPLATE_DECL ? ctor
30055 : DECL_TI_TEMPLATE (ctor));
30056 if (outer_args)
30057 fn_tmpl = tsubst (fn_tmpl, outer_args, complain, ctor);
30058 ctor = DECL_TEMPLATE_RESULT (fn_tmpl);
30060 tparms = DECL_TEMPLATE_PARMS (fn_tmpl);
30061 /* If type is a member class template, DECL_TI_ARGS (ctor) will have
30062 fully specialized args for the enclosing class. Strip those off, as
30063 the deduction guide won't have those template parameters. */
30064 targs = get_innermost_template_args (DECL_TI_ARGS (ctor),
30065 TMPL_PARMS_DEPTH (tparms));
30066 /* Discard the 'this' parameter. */
30067 fparms = FUNCTION_ARG_CHAIN (ctor);
30068 fargs = TREE_CHAIN (DECL_ARGUMENTS (ctor));
30069 ci = get_constraints (ctor);
30070 loc = DECL_SOURCE_LOCATION (ctor);
30071 explicit_p = DECL_NONCONVERTING_P (ctor);
30073 if (PRIMARY_TEMPLATE_P (fn_tmpl))
30075 memtmpl = true;
30077 /* For a member template constructor, we need to flatten the two
30078 template parameter lists into one, and then adjust the function
30079 signature accordingly. This gets...complicated. */
30080 tree save_parms = current_template_parms;
30082 /* For a member template we should have two levels of parms/args, one
30083 for the class and one for the constructor. We stripped
30084 specialized args for further enclosing classes above. */
30085 const int depth = 2;
30086 gcc_assert (TMPL_ARGS_DEPTH (targs) == depth);
30088 /* Template args for translating references to the two-level template
30089 parameters into references to the one-level template parameters we
30090 are creating. */
30091 tree tsubst_args = copy_node (targs);
30092 TMPL_ARGS_LEVEL (tsubst_args, depth)
30093 = copy_node (TMPL_ARGS_LEVEL (tsubst_args, depth));
30095 /* Template parms for the constructor template. */
30096 tree ftparms = TREE_VALUE (tparms);
30097 unsigned flen = TREE_VEC_LENGTH (ftparms);
30098 /* Template parms for the class template. */
30099 tparms = TREE_CHAIN (tparms);
30100 tree ctparms = TREE_VALUE (tparms);
30101 unsigned clen = TREE_VEC_LENGTH (ctparms);
30102 /* Template parms for the deduction guide start as a copy of the
30103 template parms for the class. We set current_template_parms for
30104 lookup_template_class_1. */
30105 current_template_parms = tparms = copy_node (tparms);
30106 tree new_vec = TREE_VALUE (tparms) = make_tree_vec (flen + clen);
30107 for (unsigned i = 0; i < clen; ++i)
30108 TREE_VEC_ELT (new_vec, i) = TREE_VEC_ELT (ctparms, i);
30110 /* Now we need to rewrite the constructor parms to append them to the
30111 class parms. */
30112 for (unsigned i = 0; i < flen; ++i)
30114 unsigned index = i + clen;
30115 unsigned level = 1;
30116 tree oldelt = TREE_VEC_ELT (ftparms, i);
30117 tree newelt
30118 = rewrite_tparm_list (oldelt, index, level,
30119 tsubst_args, i, complain);
30120 if (newelt == error_mark_node)
30121 ok = false;
30122 TREE_VEC_ELT (new_vec, index) = newelt;
30125 /* Now we have a final set of template parms to substitute into the
30126 function signature. */
30127 targs = template_parms_to_args (tparms);
30128 fparms = tsubst_arg_types (fparms, tsubst_args, NULL_TREE,
30129 complain, ctor);
30130 if (fparms == error_mark_node)
30131 ok = false;
30132 if (ci)
30134 if (outer_args)
30135 /* FIXME: We'd like to avoid substituting outer template
30136 arguments into the constraint ahead of time, but the
30137 construction of tsubst_args assumes that outer arguments
30138 are already substituted in. */
30139 ci = tsubst_constraint_info (ci, outer_args, complain, ctor);
30140 ci = tsubst_constraint_info (ci, tsubst_args, complain, ctor);
30143 /* Parms are to have DECL_CHAIN tsubsted, which would be skipped if
30144 cp_unevaluated_operand. */
30145 cp_evaluated ev;
30146 fargs = tsubst (fargs, tsubst_args, complain, ctor);
30147 current_template_parms = save_parms;
30149 else
30151 /* Substitute in the same arguments to rewrite class members into
30152 references to members of an unknown specialization. */
30153 cp_evaluated ev;
30154 fparms = tsubst_arg_types (fparms, targs, NULL_TREE, complain, ctor);
30155 if (fparms == error_mark_node)
30156 ok = false;
30157 fargs = tsubst (fargs, targs, complain, ctor);
30158 if (ci)
30160 if (outer_args)
30161 /* FIXME: As above. */
30162 ci = tsubst_constraint_info (ci, outer_args, complain, ctor);
30163 ci = tsubst_constraint_info (ci, targs, complain, ctor);
30167 --processing_template_decl;
30168 if (!ok)
30169 return error_mark_node;
30172 if (!memtmpl)
30174 /* Copy the parms so we can set DECL_PRIMARY_TEMPLATE. */
30175 tparms = copy_node (tparms);
30176 INNERMOST_TEMPLATE_PARMS (tparms)
30177 = copy_node (INNERMOST_TEMPLATE_PARMS (tparms));
30180 tree fntype = build_function_type (type, fparms);
30181 tree ded_fn = build_lang_decl_loc (loc,
30182 FUNCTION_DECL,
30183 dguide_name (type), fntype);
30184 DECL_ARGUMENTS (ded_fn) = fargs;
30185 DECL_ARTIFICIAL (ded_fn) = true;
30186 DECL_NONCONVERTING_P (ded_fn) = explicit_p;
30187 tree ded_tmpl = build_template_decl (ded_fn, tparms, /*member*/false);
30188 DECL_ARTIFICIAL (ded_tmpl) = true;
30189 DECL_TEMPLATE_INFO (ded_fn) = build_template_info (ded_tmpl, targs);
30190 DECL_PRIMARY_TEMPLATE (ded_tmpl) = ded_tmpl;
30191 if (DECL_P (ctor))
30192 DECL_ABSTRACT_ORIGIN (ded_tmpl) = fn_tmpl;
30193 if (ci)
30194 set_constraints (ded_tmpl, ci);
30196 return ded_tmpl;
30199 /* Add to LIST the member types for the reshaped initializer CTOR. */
30201 static tree
30202 collect_ctor_idx_types (tree ctor, tree list, tree elt = NULL_TREE)
30204 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (ctor);
30205 tree idx, val; unsigned i;
30206 FOR_EACH_CONSTRUCTOR_ELT (v, i, idx, val)
30208 tree ftype = elt ? elt : TREE_TYPE (idx);
30209 if (BRACE_ENCLOSED_INITIALIZER_P (val)
30210 && CONSTRUCTOR_BRACES_ELIDED_P (val))
30212 tree subelt = NULL_TREE;
30213 if (TREE_CODE (ftype) == ARRAY_TYPE)
30214 subelt = TREE_TYPE (ftype);
30215 list = collect_ctor_idx_types (val, list, subelt);
30216 continue;
30218 tree arg = NULL_TREE;
30219 if (i == v->length() - 1
30220 && PACK_EXPANSION_P (ftype))
30221 /* Give the trailing pack expansion parameter a default argument to
30222 match aggregate initialization behavior, even if we deduce the
30223 length of the pack separately to more than we have initializers. */
30224 arg = build_constructor (init_list_type_node, NULL);
30225 /* if ei is of array type and xi is a braced-init-list or string literal,
30226 Ti is an rvalue reference to the declared type of ei */
30227 STRIP_ANY_LOCATION_WRAPPER (val);
30228 if (TREE_CODE (ftype) == ARRAY_TYPE
30229 && (BRACE_ENCLOSED_INITIALIZER_P (val)
30230 || TREE_CODE (val) == STRING_CST))
30232 if (TREE_CODE (val) == STRING_CST)
30233 ftype = cp_build_qualified_type
30234 (ftype, cp_type_quals (ftype) | TYPE_QUAL_CONST);
30235 ftype = (cp_build_reference_type
30236 (ftype, BRACE_ENCLOSED_INITIALIZER_P (val)));
30238 list = tree_cons (arg, ftype, list);
30241 return list;
30244 /* Return whether ETYPE is, or is derived from, a specialization of TMPL. */
30246 static bool
30247 is_spec_or_derived (tree etype, tree tmpl)
30249 if (!etype || !CLASS_TYPE_P (etype))
30250 return false;
30252 etype = cv_unqualified (etype);
30253 tree type = TREE_TYPE (tmpl);
30254 tree tparms = (INNERMOST_TEMPLATE_PARMS
30255 (DECL_TEMPLATE_PARMS (tmpl)));
30256 tree targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
30257 int err = unify (tparms, targs, type, etype,
30258 UNIFY_ALLOW_DERIVED, /*explain*/false);
30259 ggc_free (targs);
30260 return !err;
30263 /* Return a C++20 aggregate deduction candidate for TYPE initialized from
30264 INIT. */
30266 static tree
30267 maybe_aggr_guide (tree tmpl, tree init, vec<tree,va_gc> *args)
30269 if (cxx_dialect < cxx20)
30270 return NULL_TREE;
30272 if (init == NULL_TREE)
30273 return NULL_TREE;
30275 if (DECL_ALIAS_TEMPLATE_P (tmpl))
30277 tree under = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30278 tree tinfo = get_template_info (under);
30279 if (tree guide = maybe_aggr_guide (TI_TEMPLATE (tinfo), init, args))
30280 return alias_ctad_tweaks (tmpl, guide);
30281 return NULL_TREE;
30284 /* We might be creating a guide for a class member template, e.g.,
30286 template<typename U> struct A {
30287 template<typename T> struct B { T t; };
30290 At this point, A will have been instantiated. Below, we need to
30291 use both A<U>::B<T> (TEMPLATE_TYPE) and A<int>::B<T> (TYPE) types. */
30292 const bool member_template_p
30293 = (DECL_TEMPLATE_INFO (tmpl)
30294 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (tmpl)));
30295 tree type = TREE_TYPE (tmpl);
30296 tree template_type = (member_template_p
30297 ? TREE_TYPE (DECL_TI_TEMPLATE (tmpl))
30298 : type);
30299 if (!CP_AGGREGATE_TYPE_P (template_type))
30300 return NULL_TREE;
30302 /* No aggregate candidate for copy-initialization. */
30303 if (args->length() == 1)
30305 tree val = (*args)[0];
30306 if (is_spec_or_derived (TREE_TYPE (val), tmpl))
30307 return NULL_TREE;
30310 /* If we encounter a problem, we just won't add the candidate. */
30311 tsubst_flags_t complain = tf_none;
30313 tree parms = NULL_TREE;
30314 if (BRACE_ENCLOSED_INITIALIZER_P (init))
30316 init = reshape_init (template_type, init, complain);
30317 if (init == error_mark_node)
30318 return NULL_TREE;
30319 parms = collect_ctor_idx_types (init, parms);
30321 else if (TREE_CODE (init) == TREE_LIST)
30323 int len = list_length (init);
30324 for (tree binfo : BINFO_BASE_BINFOS (TYPE_BINFO (template_type)))
30326 if (!len)
30327 break;
30328 parms = tree_cons (NULL_TREE, BINFO_TYPE (binfo), parms);
30329 --len;
30331 for (tree field = TYPE_FIELDS (template_type);
30332 len;
30333 --len, field = DECL_CHAIN (field))
30335 field = next_aggregate_field (field);
30336 if (!field)
30337 return NULL_TREE;
30338 tree ftype = finish_decltype_type (field, true, complain);
30339 parms = tree_cons (NULL_TREE, ftype, parms);
30342 else
30343 /* Aggregate initialization doesn't apply to an initializer expression. */
30344 return NULL_TREE;
30346 /* If we're creating a deduction guide for a member class template,
30347 we've used the original template pattern type for the reshape_init
30348 above; this is done because we want PARMS to be a template parameter
30349 type, something that can be deduced when used as a function template
30350 parameter. At this point the outer class template has already been
30351 partially instantiated (we deferred the deduction until the enclosing
30352 scope is non-dependent). Therefore we have to partially instantiate
30353 PARMS, so that its template level is properly reduced and we don't get
30354 mismatches when deducing types using the guide with PARMS. */
30355 if (member_template_p)
30357 ++processing_template_decl;
30358 parms = tsubst (parms, outer_template_args (tmpl), complain, init);
30359 --processing_template_decl;
30362 if (parms)
30364 tree last = parms;
30365 parms = nreverse (parms);
30366 TREE_CHAIN (last) = void_list_node;
30367 tree guide = build_deduction_guide (type, parms, NULL_TREE, complain);
30368 return guide;
30371 return NULL_TREE;
30374 /* UGUIDES are the deduction guides for the underlying template of alias
30375 template TMPL; adjust them to be deduction guides for TMPL.
30377 This routine also handles C++23 inherited CTAD, in which case TMPL is a
30378 TREE_LIST representing a synthetic alias template whose TREE_PURPOSE is
30379 the template parameter list of the alias template (equivalently, of the
30380 derived class) and TREE_VALUE the defining-type-id (equivalently, the
30381 base whose guides we're inheriting). UGUIDES are the base's guides. */
30383 static tree
30384 alias_ctad_tweaks (tree tmpl, tree uguides)
30386 /* [over.match.class.deduct]: When resolving a placeholder for a deduced
30387 class type (9.2.8.2) where the template-name names an alias template A,
30388 the defining-type-id of A must be of the form
30390 typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
30392 as specified in 9.2.8.2. The guides of A are the set of functions or
30393 function templates formed as follows. For each function or function
30394 template f in the guides of the template named by the simple-template-id
30395 of the defining-type-id, the template arguments of the return type of f
30396 are deduced from the defining-type-id of A according to the process in
30397 13.10.2.5 with the exception that deduction does not fail if not all
30398 template arguments are deduced. Let g denote the result of substituting
30399 these deductions into f. If substitution succeeds, form a function or
30400 function template f' with the following properties and add it to the set
30401 of guides of A:
30403 * The function type of f' is the function type of g.
30405 * If f is a function template, f' is a function template whose template
30406 parameter list consists of all the template parameters of A (including
30407 their default template arguments) that appear in the above deductions or
30408 (recursively) in their default template arguments, followed by the
30409 template parameters of f that were not deduced (including their default
30410 template arguments), otherwise f' is not a function template.
30412 * The associated constraints (13.5.2) are the conjunction of the
30413 associated constraints of g and a constraint that is satisfied if and only
30414 if the arguments of A are deducible (see below) from the return type.
30416 * If f is a copy deduction candidate (12.4.1.8), then f' is considered to
30417 be so as well.
30419 * If f was generated from a deduction-guide (12.4.1.8), then f' is
30420 considered to be so as well.
30422 * The explicit-specifier of f' is the explicit-specifier of g (if
30423 any). */
30425 enum { alias, inherited } ctad_kind;
30426 tree atype, fullatparms, utype, name;
30427 if (TREE_CODE (tmpl) == TEMPLATE_DECL)
30429 ctad_kind = alias;
30430 atype = TREE_TYPE (tmpl);
30431 fullatparms = DECL_TEMPLATE_PARMS (tmpl);
30432 utype = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30433 name = dguide_name (tmpl);
30435 else
30437 ctad_kind = inherited;
30438 atype = NULL_TREE;
30439 fullatparms = TREE_PURPOSE (tmpl);
30440 utype = TREE_VALUE (tmpl);
30441 name = dguide_name (TPARMS_PRIMARY_TEMPLATE
30442 (INNERMOST_TEMPLATE_PARMS (fullatparms)));
30445 tsubst_flags_t complain = tf_none;
30446 tree aguides = NULL_TREE;
30447 tree atparms = INNERMOST_TEMPLATE_PARMS (fullatparms);
30448 unsigned natparms = TREE_VEC_LENGTH (atparms);
30449 for (ovl_iterator iter (uguides); iter; ++iter)
30451 tree f = *iter;
30452 tree in_decl = f;
30453 location_t loc = DECL_SOURCE_LOCATION (f);
30454 tree ret = TREE_TYPE (TREE_TYPE (f));
30455 tree fprime = f;
30456 if (TREE_CODE (f) == TEMPLATE_DECL)
30458 processing_template_decl_sentinel ptds (/*reset*/false);
30459 ++processing_template_decl;
30461 /* Deduce template arguments for f from the type-id of A. */
30462 tree ftparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (f));
30463 unsigned len = TREE_VEC_LENGTH (ftparms);
30464 tree targs = make_tree_vec (len);
30465 int err = unify (ftparms, targs, ret, utype, UNIFY_ALLOW_NONE, false);
30466 if (err)
30467 /* CWG2664: Discard any deductions, still build the guide. */
30468 for (unsigned i = 0; i < len; ++i)
30469 TREE_VEC_ELT (targs, i) = NULL_TREE;
30471 /* The number of parms for f' is the number of parms of A used in
30472 the deduced arguments plus non-deduced parms of f. */
30473 unsigned ndlen = 0;
30474 unsigned j;
30475 for (unsigned i = 0; i < len; ++i)
30476 if (TREE_VEC_ELT (targs, i) == NULL_TREE)
30477 ++ndlen;
30478 find_template_parameter_info ftpi (fullatparms);
30479 ftpi.find_in_recursive (targs);
30480 unsigned nusedatparms = ftpi.num_found ();
30481 unsigned nfparms = nusedatparms + ndlen;
30482 tree gtparms = make_tree_vec (nfparms);
30484 /* Set current_template_parms as in build_deduction_guide. */
30485 auto ctp = make_temp_override (current_template_parms);
30486 current_template_parms = copy_node (fullatparms);
30487 TREE_VALUE (current_template_parms) = gtparms;
30489 j = 0;
30490 unsigned level = 1;
30492 /* First copy over the used parms of A. */
30493 tree atargs = make_tree_vec (natparms);
30494 for (unsigned i = 0; i < natparms; ++i)
30496 tree elt = TREE_VEC_ELT (atparms, i);
30497 if (ftpi.found (elt))
30499 unsigned index = j++;
30500 tree nelt = rewrite_tparm_list (elt, index, level,
30501 atargs, i, complain);
30502 TREE_VEC_ELT (gtparms, index) = nelt;
30505 gcc_checking_assert (j == nusedatparms);
30507 /* Adjust the deduced template args for f to refer to the A parms
30508 with their new indexes. */
30509 if (nusedatparms && nusedatparms != natparms)
30510 targs = tsubst_template_args (targs, atargs, complain, in_decl);
30512 /* Now rewrite the non-deduced parms of f. */
30513 for (unsigned i = 0; ndlen && i < len; ++i)
30514 if (TREE_VEC_ELT (targs, i) == NULL_TREE)
30516 --ndlen;
30517 unsigned index = j++;
30518 tree oldlist = TREE_VEC_ELT (ftparms, i);
30519 tree list = rewrite_tparm_list (oldlist, index, level,
30520 targs, i, complain);
30521 TREE_VEC_ELT (gtparms, index) = list;
30523 gtparms = build_tree_list (size_one_node, gtparms);
30525 /* Substitute the deduced arguments plus the rewritten template
30526 parameters into f to get g. This covers the type, copyness,
30527 guideness, and explicit-specifier. */
30528 tree g;
30530 /* Parms are to have DECL_CHAIN tsubsted, which would be skipped
30531 if cp_unevaluated_operand. */
30532 cp_evaluated ev;
30533 g = tsubst_decl (DECL_TEMPLATE_RESULT (f), targs, complain,
30534 /*use_spec_table=*/false);
30536 if (g == error_mark_node)
30537 continue;
30538 DECL_NAME (g) = name;
30539 if (nfparms == 0)
30541 /* The targs are all non-dependent, so g isn't a template. */
30542 fprime = g;
30543 ret = TREE_TYPE (TREE_TYPE (fprime));
30544 goto non_template;
30546 DECL_USE_TEMPLATE (g) = 0;
30547 fprime = build_template_decl (g, gtparms, false);
30548 DECL_TEMPLATE_RESULT (fprime) = g;
30549 TREE_TYPE (fprime) = TREE_TYPE (g);
30550 tree gtargs = template_parms_to_args (gtparms);
30551 DECL_TEMPLATE_INFO (g) = build_template_info (fprime, gtargs);
30552 DECL_PRIMARY_TEMPLATE (fprime) = fprime;
30554 /* Substitute the associated constraints. */
30555 tree ci = get_constraints (f);
30556 if (ci)
30558 if (tree outer_targs = outer_template_args (f))
30559 ci = tsubst_constraint_info (ci, outer_targs, complain, in_decl);
30560 ci = tsubst_constraint_info (ci, targs, complain, in_decl);
30562 if (ci == error_mark_node)
30563 continue;
30565 /* Add a constraint that the return type matches the instantiation of
30566 A with the same template arguments. */
30567 ret = TREE_TYPE (TREE_TYPE (fprime));
30568 if (ctad_kind == alias
30569 /* Use template_args_equal instead of same_type_p to get the
30570 comparing_dependent_aliases behavior. */
30571 && !template_args_equal (atype, ret))
30573 tree same = finish_trait_expr (loc, CPTK_IS_DEDUCIBLE, tmpl, ret);
30574 ci = append_constraint (ci, same);
30577 if (ci)
30579 remove_constraints (fprime);
30580 set_constraints (fprime, ci);
30583 else
30585 /* For a non-template deduction guide, if the arguments of A aren't
30586 deducible from the return type, don't add the candidate. */
30587 non_template:
30588 if (ctad_kind == alias
30589 && !type_targs_deducible_from (tmpl, ret))
30590 continue;
30593 /* Rewrite the return type of the inherited guide in terms of the
30594 derived class. This is specified as replacing the return type R
30595 with typename CC<R>::type where the partially specialized CC maps a
30596 base class specialization to a specialization of the derived class
30597 having such a base (inducing substitution failure if no such derived
30598 class exists).
30600 As specified this mapping would be done at instantiation time using
30601 non-dependent template arguments, but we do it ahead of time using
30602 the generic arguments. This seems to be good enough since generic
30603 deduction should succeed only if concrete deduction would. */
30604 if (ctad_kind == inherited)
30606 processing_template_decl_sentinel ptds (/*reset*/false);
30607 if (TREE_CODE (fprime) == TEMPLATE_DECL)
30608 ++processing_template_decl;
30610 tree targs = type_targs_deducible_from (tmpl, ret);
30611 if (!targs)
30612 continue;
30614 if (TREE_CODE (f) != TEMPLATE_DECL)
30615 fprime = copy_decl (fprime);
30616 tree fntype = TREE_TYPE (fprime);
30617 ret = lookup_template_class (TPARMS_PRIMARY_TEMPLATE (atparms), targs,
30618 in_decl, NULL_TREE, complain);
30619 fntype = build_function_type (ret, TYPE_ARG_TYPES (fntype));
30620 TREE_TYPE (fprime) = fntype;
30621 if (TREE_CODE (fprime) == TEMPLATE_DECL)
30622 TREE_TYPE (DECL_TEMPLATE_RESULT (fprime)) = fntype;
30623 set_inherited_guide_context (fprime, utype);
30626 aguides = lookup_add (fprime, aguides);
30629 return aguides;
30632 /* CTOR is a using-decl inheriting the constructors of some base of the class
30633 template TMPL; adjust the base's guides be deduction guides for TMPL. */
30635 static tree
30636 inherited_ctad_tweaks (tree tmpl, tree ctor, tsubst_flags_t complain)
30638 /* [over.match.class.deduct]: In addition, if C is defined and inherits
30639 constructors ([namespace.udecl]) from a direct base class denoted in the
30640 base-specifier-list by a class-or-decltype B, let A be an alias template
30641 whose template parameter list is that of C and whose defining-type-id is
30642 B. If A is a deducible template ([dcl.type.simple]), the set contains the
30643 guides of A with the return type R of each guide replaced with typename
30644 CC::type given a class template
30646 template <typename> class CC;
30648 whose primary template is not defined and with a single partial
30649 specialization whose template parameter list is that of A and whose
30650 template argument list is a specialization of A with the template argument
30651 list of A ([temp.dep.type]) having a member typedef type designating a
30652 template specialization with the template argument list of A but with C as
30653 the template. */
30655 tree scope = USING_DECL_SCOPE (ctor);
30656 if (TREE_CODE (scope) == TYPENAME_TYPE
30657 && (TYPE_IDENTIFIER (TYPE_CONTEXT (scope))
30658 == TYPENAME_TYPE_FULLNAME (scope)))
30659 /* Recognize using B<T>::B::B as an inherited constructor. */
30660 /* FIXME: Also recognize using C::B::B? We might have to call
30661 resolve_typename_type for that. */
30662 scope = TYPE_CONTEXT (scope);
30663 if (!CLASS_TYPE_P (scope)
30664 || !CLASSTYPE_TEMPLATE_INFO (scope)
30665 || !PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (scope)))
30666 return NULL_TREE;
30668 tree t = build_tree_list (DECL_TEMPLATE_PARMS (tmpl), scope);
30669 bool any_dguides_p;
30670 tree uguides = deduction_guides_for (CLASSTYPE_TI_TEMPLATE (scope),
30671 any_dguides_p, complain);
30672 return alias_ctad_tweaks (t, uguides);
30675 /* If template arguments for TMPL can be deduced from TYPE, return
30676 the deduced arguments, otherwise return NULL_TREE.
30677 Used to implement CPTK_IS_DEDUCIBLE for alias CTAD according to
30678 [over.match.class.deduct].
30680 This check is specified in terms of partial specialization, so the behavior
30681 should be parallel to that of get_partial_spec_bindings. */
30683 tree
30684 type_targs_deducible_from (tree tmpl, tree type)
30686 tree tparms, ttype;
30687 if (TREE_CODE (tmpl) == TEMPLATE_DECL)
30689 /* If tmpl is a class template, this is trivial: it's deducible if
30690 TYPE is a specialization of TMPL. */
30691 if (DECL_CLASS_TEMPLATE_P (tmpl))
30693 if (CLASS_TYPE_P (type)
30694 && CLASSTYPE_TEMPLATE_INFO (type)
30695 && CLASSTYPE_TI_TEMPLATE (type) == tmpl)
30696 return INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
30697 else
30698 return NULL_TREE;
30701 /* Otherwise it's an alias template. */
30702 tparms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
30703 ttype = TREE_TYPE (tmpl);
30705 else
30707 /* TMPL is a synthetic alias template represented as a TREE_LIST as
30708 per alias_ctad_tweaks. */
30709 tparms = INNERMOST_TEMPLATE_PARMS (TREE_PURPOSE (tmpl));
30710 ttype = TREE_VALUE (tmpl);
30711 tmpl = TI_TEMPLATE (TYPE_TEMPLATE_INFO_MAYBE_ALIAS (ttype));
30714 int len = TREE_VEC_LENGTH (tparms);
30715 tree targs = make_tree_vec (len);
30716 bool tried_array_deduction = (cxx_dialect < cxx17);
30718 again:
30719 if (unify (tparms, targs, ttype, type,
30720 UNIFY_ALLOW_NONE, false))
30721 return NULL_TREE;
30723 /* We don't fail on an undeduced targ the second time through (like
30724 get_partial_spec_bindings) because we're going to try defaults. */
30725 for (int i = 0; i < len; ++i)
30726 if (! TREE_VEC_ELT (targs, i))
30728 tree tparm = TREE_VEC_ELT (tparms, i);
30729 tparm = TREE_VALUE (tparm);
30731 if (!tried_array_deduction
30732 && TREE_CODE (tparm) == TYPE_DECL)
30734 try_array_deduction (tparms, targs, ttype);
30735 tried_array_deduction = true;
30736 if (TREE_VEC_ELT (targs, i))
30737 goto again;
30739 /* If the type parameter is a parameter pack, then it will be deduced
30740 to an empty parameter pack. This is another case that doesn't model
30741 well as partial specialization. */
30742 if (template_parameter_pack_p (tparm))
30744 tree arg;
30745 if (TREE_CODE (tparm) == PARM_DECL)
30747 arg = make_node (NONTYPE_ARGUMENT_PACK);
30748 TREE_CONSTANT (arg) = 1;
30750 else
30751 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
30752 ARGUMENT_PACK_ARGS (arg) = make_tree_vec (0);
30753 TREE_VEC_ELT (targs, i) = arg;
30757 /* Maybe add in default template args. This seems like a flaw in the
30758 specification in terms of partial specialization, since it says the
30759 partial specialization has the template parameter list of A, but a
30760 partial specialization can't have default targs. */
30761 targs = coerce_template_parms (tparms, targs, tmpl, tf_none);
30762 if (targs == error_mark_node)
30763 return NULL_TREE;
30765 /* I believe we don't need the template_template_parm_bindings_ok_p call
30766 because coerce_template_parms did coerce_template_template_parms. */
30768 if (!constraints_satisfied_p (tmpl, targs))
30769 return NULL_TREE;
30771 return targs;
30774 /* Return artificial deduction guides built from the constructors of class
30775 template TMPL. */
30777 static tree
30778 ctor_deduction_guides_for (tree tmpl, tsubst_flags_t complain)
30780 tree outer_args = outer_template_args (tmpl);
30781 tree type = TREE_TYPE (most_general_template (tmpl));
30783 tree cands = NULL_TREE;
30785 for (ovl_iterator iter (CLASSTYPE_CONSTRUCTORS (type)); iter; ++iter)
30787 /* We handle C++23 inherited CTAD below. */
30788 if (iter.using_p ())
30789 continue;
30791 tree guide = build_deduction_guide (type, *iter, outer_args, complain);
30792 cands = lookup_add (guide, cands);
30795 if (cxx_dialect >= cxx23)
30796 /* FIXME: CLASSTYPE_CONSTRUCTORS doesn't contain inherited constructors if
30797 e.g. the class also has a user-defined constructor. So instead iterate
30798 over TYPE_FIELDS manually to robustly find all relevant using-decls. */
30799 for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
30800 if (TREE_CODE (field) == USING_DECL
30801 && DECL_NAME (field) == ctor_identifier)
30803 tree uguides = inherited_ctad_tweaks (tmpl, field, complain);
30804 if (uguides)
30805 cands = lookup_add (uguides, cands);
30808 /* Add implicit default constructor deduction guide. */
30809 if (!TYPE_HAS_USER_CONSTRUCTOR (type))
30811 tree guide = build_deduction_guide (type, type, outer_args,
30812 complain);
30813 cands = lookup_add (guide, cands);
30816 /* Add copy guide. */
30818 tree gtype = build_reference_type (type);
30819 tree guide = build_deduction_guide (type, gtype, outer_args,
30820 complain);
30821 cands = lookup_add (guide, cands);
30824 return cands;
30827 static GTY((deletable)) hash_map<tree, tree_pair_p> *dguide_cache;
30829 /* Return the non-aggregate deduction guides for deducible template TMPL. The
30830 aggregate candidate is added separately because it depends on the
30831 initializer. Set ANY_DGUIDES_P if we find a non-implicit deduction
30832 guide. */
30834 static tree
30835 deduction_guides_for (tree tmpl, bool &any_dguides_p, tsubst_flags_t complain)
30837 tree guides = NULL_TREE;
30838 if (DECL_ALIAS_TEMPLATE_P (tmpl))
30840 tree under = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30841 tree tinfo = get_template_info (under);
30842 guides = deduction_guides_for (TI_TEMPLATE (tinfo), any_dguides_p,
30843 complain);
30845 else
30847 guides = lookup_qualified_name (CP_DECL_CONTEXT (tmpl),
30848 dguide_name (tmpl),
30849 LOOK_want::ANY_REACHABLE,
30850 /*complain=*/false);
30851 if (guides == error_mark_node)
30852 guides = NULL_TREE;
30853 else
30854 any_dguides_p = true;
30857 /* Cache the deduction guides for a template. We also remember the result of
30858 lookup, and rebuild everything if it changes; should be very rare. */
30859 /* FIXME: Also rebuild if this is a class template that inherits guides from a
30860 base class, and lookup for the latter changed. */
30861 tree_pair_p cache = NULL;
30862 if (tree_pair_p &r
30863 = hash_map_safe_get_or_insert<hm_ggc> (dguide_cache, tmpl))
30865 cache = r;
30866 if (cache->purpose == guides)
30867 return cache->value;
30869 else
30871 r = cache = ggc_cleared_alloc<tree_pair_s> ();
30872 cache->purpose = guides;
30875 tree cands = NULL_TREE;
30876 if (DECL_ALIAS_TEMPLATE_P (tmpl))
30877 cands = alias_ctad_tweaks (tmpl, guides);
30878 else
30880 cands = ctor_deduction_guides_for (tmpl, complain);
30881 for (lkp_iterator it (guides); it; ++it)
30882 cands = lookup_add (*it, cands);
30885 cache->value = cands;
30886 return cands;
30889 /* Return whether TMPL is a (class template argument-) deducible template. */
30891 bool
30892 ctad_template_p (tree tmpl)
30894 /* A deducible template is either a class template or is an alias template
30895 whose defining-type-id is of the form
30897 typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
30899 where the nested-name-specifier (if any) is non-dependent and the
30900 template-name of the simple-template-id names a deducible template. */
30902 if (DECL_CLASS_TEMPLATE_P (tmpl)
30903 && IDENTIFIER_TRAIT_P (DECL_NAME (tmpl)))
30904 /* Don't consider CTAD for templates with the same name as a trait; that
30905 is ambiguous with e.g. __is_invocable(_Fn,_Args...). */
30906 return false;
30907 if (DECL_CLASS_TEMPLATE_P (tmpl)
30908 || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
30909 return true;
30910 if (!DECL_ALIAS_TEMPLATE_P (tmpl))
30911 return false;
30912 tree orig = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30913 if (tree tinfo = get_template_info (orig))
30914 return ctad_template_p (TI_TEMPLATE (tinfo));
30915 return false;
30918 /* Deduce template arguments for the class template placeholder PTYPE for
30919 template TMPL based on the initializer INIT, and return the resulting
30920 type. */
30922 static tree
30923 do_class_deduction (tree ptype, tree tmpl, tree init, tree outer_targs,
30924 int flags, tsubst_flags_t complain)
30926 /* We should have handled this in the caller. */
30927 if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
30928 return ptype;
30930 /* If the class was erroneous, don't try to deduce, because that
30931 can generate a lot of diagnostic. */
30932 if (TREE_TYPE (tmpl)
30933 && TYPE_LANG_SPECIFIC (TREE_TYPE (tmpl))
30934 && CLASSTYPE_ERRONEOUS (TREE_TYPE (tmpl)))
30935 return ptype;
30937 /* Wait until the enclosing scope is non-dependent. */
30938 if (DECL_CLASS_SCOPE_P (tmpl)
30939 && dependent_type_p (DECL_CONTEXT (tmpl)))
30940 return ptype;
30942 /* Initializing one placeholder from another. */
30943 if (init
30944 && (TREE_CODE (init) == TEMPLATE_PARM_INDEX
30945 || (TREE_CODE (init) == EXPR_PACK_EXPANSION
30946 && (TREE_CODE (PACK_EXPANSION_PATTERN (init))
30947 == TEMPLATE_PARM_INDEX)))
30948 && is_auto (TREE_TYPE (init))
30949 && CLASS_PLACEHOLDER_TEMPLATE (TREE_TYPE (init)) == tmpl)
30950 return cp_build_qualified_type (TREE_TYPE (init), cp_type_quals (ptype));
30952 if (!ctad_template_p (tmpl))
30954 if (complain & tf_error)
30955 error ("non-deducible template %qT used without template arguments", tmpl);
30956 return error_mark_node;
30958 else if (cxx_dialect < cxx20 && DECL_ALIAS_TEMPLATE_P (tmpl))
30960 if (complain & tf_error)
30962 /* Be permissive with equivalent alias templates. */
30963 tree u = get_underlying_template (tmpl);
30964 auto_diagnostic_group d;
30965 diagnostic_t dk = (u == tmpl) ? DK_ERROR : DK_PEDWARN;
30966 bool complained
30967 = emit_diagnostic (dk, input_location, 0,
30968 "alias template deduction only available "
30969 "with %<-std=c++20%> or %<-std=gnu++20%>");
30970 if (u == tmpl)
30971 return error_mark_node;
30972 else if (complained)
30974 inform (input_location, "use %qD directly instead", u);
30975 tmpl = u;
30978 else
30979 return error_mark_node;
30982 /* Wait until the initializer is non-dependent. */
30983 if (type_dependent_expression_p (init))
30984 return ptype;
30986 if (outer_targs)
30988 int args_depth = TMPL_ARGS_DEPTH (outer_targs);
30989 int parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
30990 if (parms_depth > 1)
30992 /* Substitute outer arguments into this CTAD template from the
30993 current instantiation. */
30994 int want = std::min (args_depth, parms_depth - 1);
30995 outer_targs = strip_innermost_template_args (outer_targs,
30996 args_depth - want);
30997 tmpl = tsubst (tmpl, outer_targs, complain, NULL_TREE);
30998 if (tmpl == error_mark_node)
30999 return error_mark_node;
31003 /* Don't bother with the alias rules for an equivalent template. */
31004 tmpl = get_underlying_template (tmpl);
31006 tree type = TREE_TYPE (tmpl);
31008 bool try_list_cand = false;
31009 bool list_init_p = false;
31011 releasing_vec rv_args = NULL;
31012 vec<tree,va_gc> *&args = *&rv_args;
31013 if (init == NULL_TREE)
31014 args = make_tree_vector ();
31015 else if (BRACE_ENCLOSED_INITIALIZER_P (init))
31017 list_init_p = true;
31018 try_list_cand = true;
31019 if (CONSTRUCTOR_NELTS (init) == 1
31020 && !CONSTRUCTOR_IS_DESIGNATED_INIT (init))
31022 /* As an exception, the first phase in 16.3.1.7 (considering the
31023 initializer list as a single argument) is omitted if the
31024 initializer list consists of a single expression of type cv U,
31025 where U is a specialization of C or a class derived from a
31026 specialization of C. */
31027 tree elt = CONSTRUCTOR_ELT (init, 0)->value;
31028 if (is_spec_or_derived (TREE_TYPE (elt), tmpl))
31029 try_list_cand = false;
31031 if (try_list_cand || is_std_init_list (type))
31032 args = make_tree_vector_single (init);
31033 else
31034 args = make_tree_vector_from_ctor (init);
31036 else if (TREE_CODE (init) == TREE_LIST)
31037 args = make_tree_vector_from_list (init);
31038 else
31039 args = make_tree_vector_single (init);
31041 /* Do this now to avoid problems with erroneous args later on. */
31042 args = resolve_args (args, complain);
31043 if (args == NULL)
31044 return error_mark_node;
31046 bool any_dguides_p = false;
31047 tree cands = deduction_guides_for (tmpl, any_dguides_p, complain);
31048 if (cands == error_mark_node)
31049 return error_mark_node;
31051 /* Prune explicit deduction guides in copy-initialization context (but
31052 not copy-list-initialization). */
31053 bool elided = false;
31054 if (!list_init_p && (flags & LOOKUP_ONLYCONVERTING))
31056 for (lkp_iterator iter (cands); !elided && iter; ++iter)
31057 if (DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
31058 elided = true;
31060 if (elided)
31062 /* Found a nonconverting guide, prune the candidates. */
31063 tree pruned = NULL_TREE;
31064 for (lkp_iterator iter (cands); iter; ++iter)
31065 if (!DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
31066 pruned = lookup_add (*iter, pruned);
31068 cands = pruned;
31072 if (!any_dguides_p)
31073 if (tree guide = maybe_aggr_guide (tmpl, init, args))
31074 cands = lookup_add (guide, cands);
31076 tree fndecl = error_mark_node;
31078 /* If this is list-initialization and the class has a list guide, first
31079 try deducing from the list as a single argument, as [over.match.list]. */
31080 if (try_list_cand)
31082 tree list_cands = NULL_TREE;
31083 for (tree dg : lkp_range (cands))
31084 if (is_list_ctor (dg))
31085 list_cands = lookup_add (dg, list_cands);
31086 if (list_cands)
31087 fndecl = perform_dguide_overload_resolution (list_cands, args, tf_none);
31088 if (fndecl == error_mark_node)
31090 /* That didn't work, now try treating the list as a sequence of
31091 arguments. */
31092 release_tree_vector (args);
31093 args = make_tree_vector_from_ctor (init);
31094 args = resolve_args (args, complain);
31095 if (args == NULL)
31096 return error_mark_node;
31100 if (elided && !cands)
31102 error ("cannot deduce template arguments for copy-initialization"
31103 " of %qT, as it has no non-explicit deduction guides or "
31104 "user-declared constructors", type);
31105 return error_mark_node;
31107 else if (!cands && fndecl == error_mark_node)
31109 error ("cannot deduce template arguments of %qT, as it has no viable "
31110 "deduction guides", type);
31111 return error_mark_node;
31114 if (fndecl == error_mark_node)
31115 fndecl = perform_dguide_overload_resolution (cands, args, tf_none);
31117 if (fndecl == error_mark_node)
31119 if (complain & tf_warning_or_error)
31121 auto_diagnostic_group d;
31122 error ("class template argument deduction failed:");
31123 perform_dguide_overload_resolution (cands, args, complain);
31124 if (elided)
31125 inform (input_location, "explicit deduction guides not considered "
31126 "for copy-initialization");
31128 return error_mark_node;
31130 /* [over.match.list]/1: In copy-list-initialization, if an explicit
31131 constructor is chosen, the initialization is ill-formed. */
31132 else if (flags & LOOKUP_ONLYCONVERTING)
31134 if (DECL_NONCONVERTING_P (fndecl))
31136 if (complain & tf_warning_or_error)
31138 // TODO: Pass down location from cp_finish_decl.
31139 auto_diagnostic_group d;
31140 error ("class template argument deduction for %qT failed: "
31141 "explicit deduction guide selected in "
31142 "copy-list-initialization", type);
31143 inform (DECL_SOURCE_LOCATION (fndecl),
31144 "explicit deduction guide declared here");
31147 return error_mark_node;
31151 /* If CTAD succeeded but the type doesn't have any explicit deduction
31152 guides, this deduction might not be what the user intended. */
31153 if (fndecl != error_mark_node && !any_dguides_p && (complain & tf_warning))
31155 auto_diagnostic_group d;
31156 if ((!DECL_IN_SYSTEM_HEADER (fndecl)
31157 || global_dc->m_warn_system_headers)
31158 && warning (OPT_Wctad_maybe_unsupported,
31159 "%qT may not intend to support class template argument "
31160 "deduction", type))
31161 inform (input_location, "add a deduction guide to suppress this "
31162 "warning");
31165 return cp_build_qualified_type (TREE_TYPE (TREE_TYPE (fndecl)),
31166 cp_type_quals (ptype));
31169 /* Return true if INIT is an unparenthesized id-expression or an
31170 unparenthesized class member access. Used for the argument of
31171 decltype(auto). */
31173 bool
31174 unparenthesized_id_or_class_member_access_p (tree init)
31176 STRIP_ANY_LOCATION_WRAPPER (init);
31178 /* We need to be able to tell '(r)' and 'r' apart (when it's of
31179 reference type). Only the latter is an id-expression. */
31180 if (REFERENCE_REF_P (init)
31181 && !REF_PARENTHESIZED_P (init))
31182 init = TREE_OPERAND (init, 0);
31183 return (DECL_P (init)
31184 || ((TREE_CODE (init) == COMPONENT_REF
31185 || TREE_CODE (init) == SCOPE_REF)
31186 && !REF_PARENTHESIZED_P (init)));
31189 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
31190 from INIT. AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.
31191 The CONTEXT determines the context in which auto deduction is performed
31192 and is used to control error diagnostics. FLAGS are the LOOKUP_* flags.
31194 OUTER_TARGS is used during template argument deduction (context == adc_unify)
31195 to properly substitute the result. It's also used in the adc_unify and
31196 adc_requirement contexts to communicate the necessary template arguments
31197 to satisfaction. OUTER_TARGS is ignored in other contexts.
31199 Additionally for adc_unify contexts TMPL is the template for which TYPE
31200 is a template parameter type.
31202 For partial-concept-ids, extra args from OUTER_TARGS, TMPL and the current
31203 scope may be appended to the list of deduced template arguments prior to
31204 determining constraint satisfaction as appropriate. */
31206 tree
31207 do_auto_deduction (tree type, tree init, tree auto_node,
31208 tsubst_flags_t complain /* = tf_warning_or_error */,
31209 auto_deduction_context context /* = adc_unspecified */,
31210 tree outer_targs /* = NULL_TREE */,
31211 int flags /* = LOOKUP_NORMAL */,
31212 tree tmpl /* = NULL_TREE */)
31214 if (type == error_mark_node || init == error_mark_node)
31215 return error_mark_node;
31217 if (init && type_dependent_expression_p (init)
31218 && context != adc_unify)
31219 /* Defining a subset of type-dependent expressions that we can deduce
31220 from ahead of time isn't worth the trouble. */
31221 return type;
31223 /* Similarly, we can't deduce from another undeduced decl. */
31224 if (init && undeduced_auto_decl (init))
31225 return type;
31227 /* We may be doing a partial substitution, but we still want to replace
31228 auto_node. */
31229 complain &= ~tf_partial;
31231 if (init && BRACE_ENCLOSED_INITIALIZER_P (init))
31233 /* We don't recurse here because we can't deduce from a nested
31234 initializer_list. */
31235 if (CONSTRUCTOR_ELTS (init))
31236 for (constructor_elt &elt : CONSTRUCTOR_ELTS (init))
31237 elt.value = resolve_nondeduced_context (elt.value, complain);
31239 else if (init)
31240 init = resolve_nondeduced_context (init, complain);
31242 /* In C++23, we must deduce the type to int&& for code like
31243 decltype(auto) f(int&& x) { return (x); }
31245 auto&& f(int x) { return x; }
31246 so we use treat_lvalue_as_rvalue_p. But don't do it for
31247 decltype(auto) f(int x) { return x; }
31248 where we should deduce 'int' rather than 'int&&'; transmogrifying
31249 INIT to an rvalue would break that. */
31250 tree r;
31251 if (cxx_dialect >= cxx23
31252 && context == adc_return_type
31253 && (!AUTO_IS_DECLTYPE (auto_node)
31254 || !unparenthesized_id_or_class_member_access_p (init))
31255 && (r = treat_lvalue_as_rvalue_p (maybe_undo_parenthesized_ref (init),
31256 /*return*/true)))
31257 init = r;
31259 if (tree ctmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node))
31260 /* C++17 class template argument deduction. */
31261 return do_class_deduction (type, ctmpl, init, outer_targs, flags, complain);
31263 if (init == NULL_TREE || TREE_TYPE (init) == NULL_TREE)
31264 /* Nothing we can do with this, even in deduction context. */
31265 return type;
31267 location_t loc = cp_expr_loc_or_input_loc (init);
31269 /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
31270 with either a new invented type template parameter U or, if the
31271 initializer is a braced-init-list (8.5.4), with
31272 std::initializer_list<U>. */
31273 if (BRACE_ENCLOSED_INITIALIZER_P (init))
31275 if (!DIRECT_LIST_INIT_P (init))
31276 type = listify_autos (type, auto_node);
31277 else if (CONSTRUCTOR_NELTS (init) == 1)
31278 init = CONSTRUCTOR_ELT (init, 0)->value;
31279 else
31281 if (complain & tf_warning_or_error)
31283 auto_diagnostic_group d;
31284 if (permerror (loc, "direct-list-initialization of "
31285 "%<auto%> requires exactly one element"))
31286 inform (loc,
31287 "for deduction to %<std::initializer_list%>, use copy-"
31288 "list-initialization (i.e. add %<=%> before the %<{%>)");
31290 type = listify_autos (type, auto_node);
31294 if (type == error_mark_node || init == error_mark_node)
31295 return error_mark_node;
31297 tree targs;
31298 if (context == adc_decomp_type
31299 && auto_node == type
31300 && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
31302 /* [dcl.struct.bind]/1 - if decomposition declaration has no ref-qualifiers
31303 and initializer has array type, deduce cv-qualified array type. */
31304 targs = make_tree_vec (1);
31305 TREE_VEC_ELT (targs, 0) = TREE_TYPE (init);
31307 else if (AUTO_IS_DECLTYPE (auto_node))
31309 const bool id = unparenthesized_id_or_class_member_access_p (init);
31310 tree deduced = finish_decltype_type (init, id, complain);
31311 deduced = canonicalize_type_argument (deduced, complain);
31312 if (deduced == error_mark_node)
31313 return error_mark_node;
31314 targs = make_tree_vec (1);
31315 TREE_VEC_ELT (targs, 0) = deduced;
31317 else
31319 if (error_operand_p (init))
31320 return error_mark_node;
31322 tree parms = build_tree_list (NULL_TREE, type);
31323 tree tparms = make_tree_vec (1);
31324 TREE_VEC_ELT (tparms, 0)
31325 = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
31327 targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
31328 int val = type_unification_real (tparms, targs, parms, &init, 1, 0,
31329 DEDUCE_CALL,
31330 NULL, /*explain_p=*/false);
31331 if (val > 0)
31333 if (processing_template_decl)
31334 /* Try again at instantiation time. */
31335 return type;
31336 if (type && type != error_mark_node
31337 && (complain & tf_error))
31338 /* If type is error_mark_node a diagnostic must have been
31339 emitted by now. Also, having a mention to '<type error>'
31340 in the diagnostic is not really useful to the user. */
31342 if (cfun
31343 && FNDECL_USED_AUTO (current_function_decl)
31344 && (auto_node
31345 == DECL_SAVED_AUTO_RETURN_TYPE (current_function_decl))
31346 && LAMBDA_FUNCTION_P (current_function_decl))
31347 error_at (loc, "unable to deduce lambda return type from %qE",
31348 init);
31349 else
31350 error_at (loc, "unable to deduce %qT from %qE", type, init);
31351 type_unification_real (tparms, targs, parms, &init, 1, 0,
31352 DEDUCE_CALL,
31353 NULL, /*explain_p=*/true);
31355 return error_mark_node;
31359 /* Check any placeholder constraints against the deduced type. */
31360 if (processing_template_decl && context == adc_unify)
31361 /* Constraints will be checked after deduction. */;
31362 else if (tree constr = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (auto_node)))
31364 if (processing_template_decl)
31366 gcc_checking_assert (context == adc_variable_type
31367 || context == adc_return_type
31368 || context == adc_decomp_type);
31369 gcc_checking_assert (!type_dependent_expression_p (init));
31370 /* If the constraint is dependent, we need to wait until
31371 instantiation time to resolve the placeholder. */
31372 if (placeholder_type_constraint_dependent_p (constr))
31373 return type;
31376 if (context == adc_return_type
31377 || context == adc_variable_type
31378 || context == adc_decomp_type)
31379 if (tree fn = current_function_decl)
31380 if (DECL_TEMPLATE_INFO (fn) || LAMBDA_FUNCTION_P (fn))
31382 outer_targs = DECL_TEMPLATE_INFO (fn)
31383 ? DECL_TI_ARGS (fn) : NULL_TREE;
31384 if (LAMBDA_FUNCTION_P (fn))
31386 /* As in satisfy_declaration_constraints. */
31387 tree regen_args = lambda_regenerating_args (fn);
31388 if (outer_targs)
31389 outer_targs = add_to_template_args (regen_args, outer_targs);
31390 else
31391 outer_targs = regen_args;
31395 tree full_targs = outer_targs;
31396 if (context == adc_unify && tmpl)
31397 full_targs = add_outermost_template_args (tmpl, full_targs);
31398 full_targs = add_to_template_args (full_targs, targs);
31400 /* HACK: Compensate for callers not always communicating all levels of
31401 outer template arguments by filling in the outermost missing levels
31402 with dummy levels before checking satisfaction. We'll still crash
31403 if the constraint depends on a template argument belonging to one of
31404 these missing levels, but this hack otherwise allows us to handle a
31405 large subset of possible constraints (including all non-dependent
31406 constraints). */
31407 if (int missing_levels = (TEMPLATE_TYPE_ORIG_LEVEL (auto_node)
31408 - TMPL_ARGS_DEPTH (full_targs)))
31410 tree dummy_levels = make_tree_vec (missing_levels);
31411 for (int i = 0; i < missing_levels; ++i)
31412 TREE_VEC_ELT (dummy_levels, i) = make_tree_vec (0);
31413 full_targs = add_to_template_args (dummy_levels, full_targs);
31416 if (!constraints_satisfied_p (auto_node, full_targs))
31418 if (complain & tf_warning_or_error)
31420 auto_diagnostic_group d;
31421 switch (context)
31423 case adc_unspecified:
31424 case adc_unify:
31425 error_at (loc, "placeholder constraints not satisfied");
31426 break;
31427 case adc_variable_type:
31428 case adc_decomp_type:
31429 error_at (loc, "deduced initializer does not satisfy "
31430 "placeholder constraints");
31431 break;
31432 case adc_return_type:
31433 error_at (loc, "deduced return type does not satisfy "
31434 "placeholder constraints");
31435 break;
31436 case adc_requirement:
31437 error_at (loc, "deduced expression type does not satisfy "
31438 "placeholder constraints");
31439 break;
31441 diagnose_constraints (loc, auto_node, full_targs);
31443 return error_mark_node;
31447 if (TEMPLATE_TYPE_LEVEL (auto_node) == 0)
31449 /* Substitute this level-less auto via tsubst by temporarily
31450 overriding its level to 1. */
31451 TEMPLATE_TYPE_LEVEL (auto_node) = 1;
31452 type = tsubst (type, targs, complain, NULL_TREE);
31453 TEMPLATE_TYPE_LEVEL (auto_node) = 0;
31454 return type;
31457 if (TEMPLATE_TYPE_LEVEL (auto_node) == 1)
31458 /* The outer template arguments are already substituted into type
31459 (but we still may have used them for constraint checking above). */;
31460 else if (context == adc_unify)
31461 targs = add_to_template_args (outer_targs, targs);
31462 else if (processing_template_decl)
31463 targs = add_to_template_args (current_template_args (), targs);
31464 return tsubst (type, targs, complain, NULL_TREE);
31467 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
31468 result. */
31470 tree
31471 splice_late_return_type (tree type, tree late_return_type)
31473 if (late_return_type)
31475 gcc_assert (is_auto (type) || seen_error ());
31476 return late_return_type;
31479 if (tree auto_node = find_type_usage (type, is_auto))
31480 if (TEMPLATE_TYPE_LEVEL (auto_node) <= current_template_depth)
31482 /* In an abbreviated function template we didn't know we were dealing
31483 with a function template when we saw the auto return type, so rebuild
31484 the return type using an auto with the correct level. */
31485 tree new_auto = make_auto_1 (TYPE_IDENTIFIER (auto_node), false);
31486 tree auto_vec = make_tree_vec (1);
31487 TREE_VEC_ELT (auto_vec, 0) = new_auto;
31488 tree targs = add_outermost_template_args (current_template_args (),
31489 auto_vec);
31490 /* Also rebuild the constraint info in terms of the new auto. */
31491 if (tree ci = PLACEHOLDER_TYPE_CONSTRAINTS_INFO (auto_node))
31492 PLACEHOLDER_TYPE_CONSTRAINTS_INFO (new_auto)
31493 = build_tree_list (current_template_parms,
31494 tsubst_constraint (TREE_VALUE (ci), targs,
31495 tf_none, NULL_TREE));
31496 TYPE_CANONICAL (new_auto) = canonical_type_parameter (new_auto);
31497 return tsubst (type, targs, tf_none, NULL_TREE);
31499 return type;
31502 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto' or
31503 'decltype(auto)' or a deduced class template. */
31505 bool
31506 is_auto (const_tree type)
31508 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
31509 && (TYPE_IDENTIFIER (type) == auto_identifier
31510 || TYPE_IDENTIFIER (type) == decltype_auto_identifier))
31511 return true;
31512 else
31513 return false;
31516 /* for_each_template_parm callback for type_uses_auto. */
31519 is_auto_r (tree tp, void */*data*/)
31521 return is_auto (tp);
31524 /* Returns the TEMPLATE_TYPE_PARM in TYPE representing `auto' iff TYPE contains
31525 a use of `auto'. Returns NULL_TREE otherwise. */
31527 tree
31528 type_uses_auto (tree type)
31530 if (type == NULL_TREE)
31531 return NULL_TREE;
31533 /* For parameter packs, check the contents of the pack. */
31534 if (PACK_EXPANSION_P (type))
31535 type = PACK_EXPANSION_PATTERN (type);
31537 return find_type_usage (type, is_auto);
31540 /* Recursively walk over && expressions searching for EXPR. Return a reference
31541 to that expression. */
31543 static tree *find_template_requirement (tree *t, tree key)
31545 if (*t == key)
31546 return t;
31547 if (TREE_CODE (*t) == TRUTH_ANDIF_EXPR)
31549 if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 0), key))
31550 return p;
31551 if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 1), key))
31552 return p;
31554 return 0;
31557 /* Convert the generic type parameters in PARM that match the types given in the
31558 range [START_IDX, END_IDX) from the current_template_parms into generic type
31559 packs. */
31561 tree
31562 convert_generic_types_to_packs (tree parm, int start_idx, int end_idx)
31564 tree current = current_template_parms;
31565 int depth = TMPL_PARMS_DEPTH (current);
31566 current = INNERMOST_TEMPLATE_PARMS (current);
31567 tree replacement = make_tree_vec (TREE_VEC_LENGTH (current));
31569 for (int i = 0; i < start_idx; ++i)
31570 TREE_VEC_ELT (replacement, i)
31571 = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
31573 for (int i = start_idx; i < end_idx; ++i)
31575 /* Create a distinct parameter pack type from the current parm and add it
31576 to the replacement args to tsubst below into the generic function
31577 parameter. */
31578 tree node = TREE_VEC_ELT (current, i);
31579 tree o = TREE_TYPE (TREE_VALUE (node));
31580 tree t = copy_type (o);
31581 TEMPLATE_TYPE_PARM_INDEX (t)
31582 = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (o),
31583 t, 0, 0, tf_none);
31584 TREE_TYPE (TEMPLATE_TYPE_DECL (t)) = t;
31585 TYPE_STUB_DECL (t) = TYPE_NAME (t) = TEMPLATE_TYPE_DECL (t);
31586 TYPE_MAIN_VARIANT (t) = t;
31587 TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
31588 TYPE_CANONICAL (t) = canonical_type_parameter (t);
31589 TREE_VEC_ELT (replacement, i) = t;
31591 /* Replace the current template parameter with new pack. */
31592 TREE_VALUE (node) = TREE_CHAIN (t);
31594 /* Surgically adjust the associated constraint of adjusted parameter
31595 and it's corresponding contribution to the current template
31596 requirements. */
31597 if (tree constr = TEMPLATE_PARM_CONSTRAINTS (node))
31599 gcc_assert (concept_check_p (constr));
31600 TREE_VEC_ELT (TREE_OPERAND (constr, 1), 0) = t;
31601 /* Use UNKNOWN_LOCATION so write_template_args can tell the
31602 difference between this and a fold the user wrote. */
31603 location_t loc = UNKNOWN_LOCATION;
31604 tree fold = finish_left_unary_fold_expr (loc, constr,
31605 TRUTH_ANDIF_EXPR);
31606 TEMPLATE_PARM_CONSTRAINTS (node) = fold;
31608 /* If there was a constraint, we also need to replace that in
31609 the template requirements, which we've already built. */
31610 tree *reqs = &TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
31611 reqs = find_template_requirement (reqs, constr);
31612 *reqs = fold;
31616 for (int i = end_idx, e = TREE_VEC_LENGTH (current); i < e; ++i)
31617 TREE_VEC_ELT (replacement, i)
31618 = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
31620 /* If there are more levels then build up the replacement with the outer
31621 template parms. */
31622 if (depth > 1)
31623 replacement = add_to_template_args (template_parms_to_args
31624 (TREE_CHAIN (current_template_parms)),
31625 replacement);
31627 return tsubst (parm, replacement, tf_none, NULL_TREE);
31630 /* __integer_pack(N) in a pack expansion expands to a sequence of numbers from
31631 0..N-1. */
31633 void
31634 declare_integer_pack (void)
31636 tree ipfn = push_library_fn (get_identifier ("__integer_pack"),
31637 build_function_type_list (integer_type_node,
31638 integer_type_node,
31639 NULL_TREE),
31640 NULL_TREE, ECF_CONST);
31641 DECL_DECLARED_CONSTEXPR_P (ipfn) = true;
31642 set_decl_built_in_function (ipfn, BUILT_IN_FRONTEND,
31643 CP_BUILT_IN_INTEGER_PACK);
31646 /* Walk the decl or type specialization table calling FN on each
31647 entry. */
31649 void
31650 walk_specializations (bool decls_p,
31651 void (*fn) (bool decls_p, spec_entry *entry, void *data),
31652 void *data)
31654 spec_hash_table *table = decls_p ? decl_specializations
31655 : type_specializations;
31656 spec_hash_table::iterator end (table->end ());
31657 for (spec_hash_table::iterator iter (table->begin ()); iter != end; ++iter)
31658 fn (decls_p, *iter, data);
31661 /* Lookup the specialization of *ELT, in the decl or type
31662 specialization table. Return the SPEC that's already there, or
31663 NULL if nothing. */
31665 tree
31666 match_mergeable_specialization (bool decl_p, spec_entry *elt)
31668 hash_table<spec_hasher> *specializations
31669 = decl_p ? decl_specializations : type_specializations;
31670 auto *slot = specializations->find_slot (elt, NO_INSERT);
31672 if (slot)
31673 return (*slot)->spec;
31675 return NULL_TREE;
31678 /* Return flags encoding whether SPEC is on the instantiation and/or
31679 specialization lists of TMPL. */
31681 unsigned
31682 get_mergeable_specialization_flags (bool decl_p, tree tmpl, tree decl)
31684 unsigned flags = 0;
31686 tree spec = decl_p ? decl : TREE_TYPE (decl);
31687 for (tree inst = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
31688 inst; inst = TREE_CHAIN (inst))
31689 if (TREE_VALUE (inst) == spec)
31691 flags |= 1;
31692 break;
31695 if (CLASS_TYPE_P (TREE_TYPE (decl))
31696 && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl))
31697 && CLASSTYPE_USE_TEMPLATE (TREE_TYPE (decl)) == 2)
31698 /* Only need to search if DECL is a partial specialization. */
31699 for (tree part = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
31700 part; part = TREE_CHAIN (part))
31701 if (TREE_VALUE (part) == decl)
31703 flags |= 2;
31704 break;
31707 return flags;
31710 /* Add a new specialization described by SPEC. DECL is the
31711 maybe-template decl and FLAGS is as returned from
31712 get_mergeable_specialization_flags. */
31714 void
31715 add_mergeable_specialization (bool decl_p, spec_entry *elt, tree decl,
31716 unsigned flags)
31718 if (decl_p)
31720 auto *slot = decl_specializations->find_slot (elt, INSERT);
31722 gcc_checking_assert (!*slot);
31723 auto entry = ggc_alloc<spec_entry> ();
31724 *entry = *elt;
31725 *slot = entry;
31727 else
31729 auto *slot = type_specializations->find_slot (elt, INSERT);
31731 /* We don't distinguish different constrained partial type
31732 specializations, so there could be duplicates. Everything else
31733 must be new. */
31734 if (!(flags & 2 && *slot))
31736 gcc_checking_assert (!*slot);
31738 auto entry = ggc_alloc<spec_entry> ();
31739 *entry = *elt;
31740 *slot = entry;
31744 if (flags & 1)
31745 DECL_TEMPLATE_INSTANTIATIONS (elt->tmpl)
31746 = tree_cons (elt->args, elt->spec,
31747 DECL_TEMPLATE_INSTANTIATIONS (elt->tmpl));
31749 if (flags & 2)
31751 /* A partial specialization. */
31752 tree cons = tree_cons (elt->args, decl,
31753 DECL_TEMPLATE_SPECIALIZATIONS (elt->tmpl));
31754 TREE_TYPE (cons) = decl_p ? TREE_TYPE (elt->spec) : elt->spec;
31755 DECL_TEMPLATE_SPECIALIZATIONS (elt->tmpl) = cons;
31756 set_defining_module_for_partial_spec (STRIP_TEMPLATE (decl));
31760 /* Set up the hash tables for template instantiations. */
31762 void
31763 init_template_processing (void)
31765 decl_specializations = hash_table<spec_hasher>::create_ggc (37);
31766 type_specializations = hash_table<spec_hasher>::create_ggc (37);
31768 if (cxx_dialect >= cxx11)
31769 declare_integer_pack ();
31772 /* Print stats about the template hash tables for -fstats. */
31774 void
31775 print_template_statistics (void)
31777 fprintf (stderr, "decl_specializations: size " HOST_SIZE_T_PRINT_DEC ", "
31778 HOST_SIZE_T_PRINT_DEC " elements, %f collisions\n",
31779 (fmt_size_t) decl_specializations->size (),
31780 (fmt_size_t) decl_specializations->elements (),
31781 decl_specializations->collisions ());
31782 fprintf (stderr, "type_specializations: size " HOST_SIZE_T_PRINT_DEC ", "
31783 HOST_SIZE_T_PRINT_DEC " elements, %f collisions\n",
31784 (fmt_size_t) type_specializations->size (),
31785 (fmt_size_t) type_specializations->elements (),
31786 type_specializations->collisions ());
31789 #if CHECKING_P
31791 namespace selftest {
31793 /* Verify that type_dependent_expression_p () works correctly, even
31794 in the presence of location wrapper nodes. */
31796 static void
31797 test_type_dependent_expression_p ()
31799 location_t loc = BUILTINS_LOCATION;
31801 tree name = get_identifier ("foo");
31803 /* If no templates are involved, nothing is type-dependent. */
31804 gcc_assert (!processing_template_decl);
31805 ASSERT_FALSE (type_dependent_expression_p (name));
31807 ++processing_template_decl;
31809 /* Within a template, an unresolved name is always type-dependent. */
31810 ASSERT_TRUE (type_dependent_expression_p (name));
31812 /* Ensure it copes with NULL_TREE and errors. */
31813 ASSERT_FALSE (type_dependent_expression_p (NULL_TREE));
31814 ASSERT_FALSE (type_dependent_expression_p (error_mark_node));
31816 /* A USING_DECL in a template should be type-dependent, even if wrapped
31817 with a location wrapper (PR c++/83799). */
31818 tree using_decl = build_lang_decl (USING_DECL, name, NULL_TREE);
31819 TREE_TYPE (using_decl) = integer_type_node;
31820 ASSERT_TRUE (type_dependent_expression_p (using_decl));
31821 tree wrapped_using_decl = maybe_wrap_with_location (using_decl, loc);
31822 ASSERT_TRUE (location_wrapper_p (wrapped_using_decl));
31823 ASSERT_TRUE (type_dependent_expression_p (wrapped_using_decl));
31825 --processing_template_decl;
31828 /* Run all of the selftests within this file. */
31830 void
31831 cp_pt_cc_tests ()
31833 test_type_dependent_expression_p ();
31836 } // namespace selftest
31838 #endif /* #if CHECKING_P */
31840 #include "gt-cp-pt.h"