c++: local alias in typename in lambda [PR105518]
[official-gcc.git] / gcc / cp / pt.cc
blob38e3a1672c1946b0d6e1211fd90c006201a0962a
1 /* Handle parameterized types (templates) for GNU -*- C++ -*-.
2 Copyright (C) 1992-2022 Free Software Foundation, Inc.
3 Written by Ken Raeburn (raeburn@cygnus.com) while at Watchmaker Computing.
4 Rewritten by Jason Merrill (jason@cygnus.com).
6 This file is part of GCC.
8 GCC is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3, or (at your option)
11 any later version.
13 GCC is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3. If not see
20 <http://www.gnu.org/licenses/>. */
22 /* Known bugs or deficiencies include:
24 all methods must be provided in header files; can't use a source
25 file that contains only the method templates and "just win".
27 Fixed by: C++20 modules. */
29 #include "config.h"
30 #define INCLUDE_ALGORITHM // for std::equal
31 #include "system.h"
32 #include "coretypes.h"
33 #include "cp-tree.h"
34 #include "timevar.h"
35 #include "stringpool.h"
36 #include "varasm.h"
37 #include "attribs.h"
38 #include "stor-layout.h"
39 #include "intl.h"
40 #include "c-family/c-objc.h"
41 #include "cp-objcp-common.h"
42 #include "toplev.h"
43 #include "tree-iterator.h"
44 #include "type-utils.h"
45 #include "gimplify.h"
46 #include "gcc-rich-location.h"
47 #include "selftest.h"
48 #include "target.h"
50 /* The type of functions taking a tree, and some additional data, and
51 returning an int. */
52 typedef int (*tree_fn_t) (tree, void*);
54 /* The PENDING_TEMPLATES is a list of templates whose instantiations
55 have been deferred, either because their definitions were not yet
56 available, or because we were putting off doing the work. */
57 struct GTY ((chain_next ("%h.next"))) pending_template
59 struct pending_template *next;
60 struct tinst_level *tinst;
63 static GTY(()) struct pending_template *pending_templates;
64 static GTY(()) struct pending_template *last_pending_template;
66 int processing_template_parmlist;
67 static int template_header_count;
69 static vec<int> inline_parm_levels;
71 static GTY(()) struct tinst_level *current_tinst_level;
73 static GTY(()) vec<tree, va_gc> *saved_access_scope;
75 /* Live only within one (recursive) call to tsubst_expr. We use
76 this to pass the statement expression node from the STMT_EXPR
77 to the EXPR_STMT that is its result. */
78 static tree cur_stmt_expr;
80 // -------------------------------------------------------------------------- //
81 // Local Specialization Stack
83 // Implementation of the RAII helper for creating new local
84 // specializations.
85 local_specialization_stack::local_specialization_stack (lss_policy policy)
86 : saved (local_specializations)
88 if (policy == lss_nop)
90 else if (policy == lss_blank || !saved)
91 local_specializations = new hash_map<tree, tree>;
92 else
93 local_specializations = new hash_map<tree, tree>(*saved);
96 local_specialization_stack::~local_specialization_stack ()
98 if (local_specializations != saved)
100 delete local_specializations;
101 local_specializations = saved;
105 /* True if we've recursed into fn_type_unification too many times. */
106 static bool excessive_deduction_depth;
108 struct spec_hasher : ggc_ptr_hash<spec_entry>
110 static hashval_t hash (tree, tree);
111 static hashval_t hash (spec_entry *);
112 static bool equal (spec_entry *, spec_entry *);
115 /* The general template is not in these tables. */
116 typedef hash_table<spec_hasher> spec_hash_table;
117 static GTY (()) spec_hash_table *decl_specializations;
118 static GTY (()) spec_hash_table *type_specializations;
120 /* Contains canonical template parameter types. The vector is indexed by
121 the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
122 TREE_LIST, whose TREE_VALUEs contain the canonical template
123 parameters of various types and levels. */
124 static GTY(()) vec<tree, va_gc> *canonical_template_parms;
126 #define UNIFY_ALLOW_NONE 0
127 #define UNIFY_ALLOW_MORE_CV_QUAL 1
128 #define UNIFY_ALLOW_LESS_CV_QUAL 2
129 #define UNIFY_ALLOW_DERIVED 4
130 #define UNIFY_ALLOW_INTEGER 8
131 #define UNIFY_ALLOW_OUTER_LEVEL 16
132 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
133 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
135 enum template_base_result {
136 tbr_incomplete_type,
137 tbr_ambiguous_baseclass,
138 tbr_success
141 static bool resolve_overloaded_unification (tree, tree, tree, tree,
142 unification_kind_t, int,
143 bool);
144 static int try_one_overload (tree, tree, tree, tree, tree,
145 unification_kind_t, int, bool, bool);
146 static int unify (tree, tree, tree, tree, int, bool);
147 static void add_pending_template (tree);
148 static tree reopen_tinst_level (struct tinst_level *);
149 static tree tsubst_initializer_list (tree, tree);
150 static tree get_partial_spec_bindings (tree, tree, tree);
151 static void tsubst_enum (tree, tree, tree);
152 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
153 static int check_non_deducible_conversion (tree, tree, unification_kind_t, int,
154 struct conversion **, bool);
155 static int maybe_adjust_types_for_deduction (tree, unification_kind_t,
156 tree*, tree*, tree);
157 static int type_unification_real (tree, tree, tree, const tree *,
158 unsigned int, int, unification_kind_t,
159 vec<deferred_access_check, va_gc> **,
160 bool);
161 static void note_template_header (int);
162 static tree convert_nontype_argument_function (tree, tree, tsubst_flags_t);
163 static tree convert_nontype_argument (tree, tree, tsubst_flags_t);
164 static tree convert_template_argument (tree, tree, tree,
165 tsubst_flags_t, int, tree);
166 static tree for_each_template_parm (tree, tree_fn_t, void*,
167 hash_set<tree> *, bool, tree_fn_t = NULL);
168 static tree expand_template_argument_pack (tree);
169 static tree build_template_parm_index (int, int, int, tree, tree);
170 static bool inline_needs_template_parms (tree, bool);
171 static void push_inline_template_parms_recursive (tree, int);
172 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
173 static int mark_template_parm (tree, void *);
174 static int template_parm_this_level_p (tree, void *);
175 static tree tsubst_friend_function (tree, tree);
176 static tree tsubst_friend_class (tree, tree);
177 static int can_complete_type_without_circularity (tree);
178 static tree get_bindings (tree, tree, tree, bool);
179 static int template_decl_level (tree);
180 static int check_cv_quals_for_unify (int, tree, tree);
181 static int unify_pack_expansion (tree, tree, tree,
182 tree, unification_kind_t, bool, bool);
183 static tree copy_template_args (tree);
184 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
185 static void tsubst_each_template_parm_constraints (tree, tree, tsubst_flags_t);
186 tree most_specialized_partial_spec (tree, tsubst_flags_t);
187 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
188 static tree tsubst_aggr_type_1 (tree, tree, tsubst_flags_t, tree, int);
189 static tree tsubst_arg_types (tree, tree, tree, tsubst_flags_t, tree);
190 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
191 static bool check_specialization_scope (void);
192 static tree process_partial_specialization (tree);
193 static enum template_base_result get_template_base (tree, tree, tree, tree,
194 bool , tree *);
195 static tree try_class_unification (tree, tree, tree, tree, bool);
196 static bool class_nttp_const_wrapper_p (tree t);
197 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
198 tree, tree);
199 static bool template_template_parm_bindings_ok_p (tree, tree);
200 static void tsubst_default_arguments (tree, tsubst_flags_t);
201 static tree for_each_template_parm_r (tree *, int *, void *);
202 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
203 static void copy_default_args_to_explicit_spec (tree);
204 static bool invalid_nontype_parm_type_p (tree, tsubst_flags_t);
205 static bool dependent_template_arg_p (tree);
206 static bool dependent_type_p_r (tree);
207 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
208 static tree tsubst_decl (tree, tree, tsubst_flags_t);
209 static void perform_instantiation_time_access_checks (tree, tree);
210 static tree listify (tree);
211 static tree listify_autos (tree, tree);
212 static tree tsubst_template_parm (tree, tree, tsubst_flags_t);
213 static tree instantiate_alias_template (tree, tree, tsubst_flags_t);
214 static bool complex_alias_template_p (const_tree tmpl);
215 static tree get_underlying_template (tree);
216 static tree tsubst_attributes (tree, tree, tsubst_flags_t, tree);
217 static tree canonicalize_expr_argument (tree, tsubst_flags_t);
218 static tree make_argument_pack (tree);
219 static tree enclosing_instantiation_of (tree tctx);
220 static void instantiate_body (tree pattern, tree args, tree d, bool nested);
221 static tree maybe_dependent_member_ref (tree, tree, tsubst_flags_t, tree);
223 /* Make the current scope suitable for access checking when we are
224 processing T. T can be FUNCTION_DECL for instantiated function
225 template, VAR_DECL for static member variable, or TYPE_DECL for
226 for a class or alias template (needed by instantiate_decl). */
228 void
229 push_access_scope (tree t)
231 gcc_assert (VAR_OR_FUNCTION_DECL_P (t)
232 || TREE_CODE (t) == TYPE_DECL);
234 if (DECL_FRIEND_CONTEXT (t))
235 push_nested_class (DECL_FRIEND_CONTEXT (t));
236 else if (DECL_IMPLICIT_TYPEDEF_P (t)
237 && CLASS_TYPE_P (TREE_TYPE (t)))
238 push_nested_class (TREE_TYPE (t));
239 else if (DECL_CLASS_SCOPE_P (t))
240 push_nested_class (DECL_CONTEXT (t));
241 else if (deduction_guide_p (t) && DECL_ARTIFICIAL (t))
242 /* An artificial deduction guide should have the same access as
243 the constructor. */
244 push_nested_class (TREE_TYPE (TREE_TYPE (t)));
245 else
246 push_to_top_level ();
248 if (TREE_CODE (t) == FUNCTION_DECL)
250 vec_safe_push (saved_access_scope, current_function_decl);
251 current_function_decl = t;
255 /* Restore the scope set up by push_access_scope. T is the node we
256 are processing. */
258 void
259 pop_access_scope (tree t)
261 if (TREE_CODE (t) == FUNCTION_DECL)
262 current_function_decl = saved_access_scope->pop();
264 if (DECL_FRIEND_CONTEXT (t)
265 || (DECL_IMPLICIT_TYPEDEF_P (t)
266 && CLASS_TYPE_P (TREE_TYPE (t)))
267 || DECL_CLASS_SCOPE_P (t)
268 || (deduction_guide_p (t) && DECL_ARTIFICIAL (t)))
269 pop_nested_class ();
270 else
271 pop_from_top_level ();
274 /* Do any processing required when DECL (a member template
275 declaration) is finished. Returns the TEMPLATE_DECL corresponding
276 to DECL, unless it is a specialization, in which case the DECL
277 itself is returned. */
279 tree
280 finish_member_template_decl (tree decl)
282 if (decl == error_mark_node)
283 return error_mark_node;
285 gcc_assert (DECL_P (decl));
287 if (TREE_CODE (decl) == TYPE_DECL)
289 tree type;
291 type = TREE_TYPE (decl);
292 if (type == error_mark_node)
293 return error_mark_node;
294 if (MAYBE_CLASS_TYPE_P (type)
295 && CLASSTYPE_TEMPLATE_INFO (type)
296 && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
298 tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
299 check_member_template (tmpl);
300 return tmpl;
302 return NULL_TREE;
304 else if (TREE_CODE (decl) == FIELD_DECL)
305 error_at (DECL_SOURCE_LOCATION (decl),
306 "data member %qD cannot be a member template", decl);
307 else if (DECL_TEMPLATE_INFO (decl))
309 if (!DECL_TEMPLATE_SPECIALIZATION (decl))
311 check_member_template (DECL_TI_TEMPLATE (decl));
312 return DECL_TI_TEMPLATE (decl);
314 else
315 return decl;
317 else
318 error_at (DECL_SOURCE_LOCATION (decl),
319 "invalid member template declaration %qD", decl);
321 return error_mark_node;
324 /* Create a template info node. */
326 tree
327 build_template_info (tree template_decl, tree template_args)
329 tree result = make_node (TEMPLATE_INFO);
330 TI_TEMPLATE (result) = template_decl;
331 TI_ARGS (result) = template_args;
332 return result;
335 /* Return the template info node corresponding to T, whatever T is. */
337 tree
338 get_template_info (const_tree t)
340 tree tinfo = NULL_TREE;
342 if (!t || t == error_mark_node)
343 return NULL;
345 if (TREE_CODE (t) == NAMESPACE_DECL
346 || TREE_CODE (t) == PARM_DECL)
347 return NULL;
349 if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
350 tinfo = DECL_TEMPLATE_INFO (t);
352 if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
353 t = TREE_TYPE (t);
355 if (OVERLOAD_TYPE_P (t))
356 tinfo = TYPE_TEMPLATE_INFO (t);
357 else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
358 tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
360 return tinfo;
363 /* Returns the template nesting level of the indicated class TYPE.
365 For example, in:
366 template <class T>
367 struct A
369 template <class U>
370 struct B {};
373 A<T>::B<U> has depth two, while A<T> has depth one.
374 Both A<T>::B<int> and A<int>::B<U> have depth one, if
375 they are instantiations, not specializations.
377 This function is guaranteed to return 0 if passed NULL_TREE so
378 that, for example, `template_class_depth (current_class_type)' is
379 always safe. */
382 template_class_depth (tree type)
384 int depth;
386 for (depth = 0; type && TREE_CODE (type) != NAMESPACE_DECL; )
388 tree tinfo = get_template_info (type);
390 if (tinfo
391 && TREE_CODE (TI_TEMPLATE (tinfo)) == TEMPLATE_DECL
392 && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
393 && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
394 ++depth;
396 if (DECL_P (type))
398 if (tree fctx = DECL_FRIEND_CONTEXT (type))
399 type = fctx;
400 else
401 type = CP_DECL_CONTEXT (type);
403 else if (LAMBDA_TYPE_P (type) && LAMBDA_TYPE_EXTRA_SCOPE (type))
404 type = LAMBDA_TYPE_EXTRA_SCOPE (type);
405 else
406 type = CP_TYPE_CONTEXT (type);
409 return depth;
412 /* Return TRUE if NODE instantiates a template that has arguments of
413 its own, be it directly a primary template or indirectly through a
414 partial specializations. */
415 static bool
416 instantiates_primary_template_p (tree node)
418 tree tinfo = get_template_info (node);
419 if (!tinfo)
420 return false;
422 tree tmpl = TI_TEMPLATE (tinfo);
423 if (PRIMARY_TEMPLATE_P (tmpl))
424 return true;
426 if (!DECL_TEMPLATE_SPECIALIZATION (tmpl))
427 return false;
429 /* So now we know we have a specialization, but it could be a full
430 or a partial specialization. To tell which, compare the depth of
431 its template arguments with those of its context. */
433 tree ctxt = DECL_CONTEXT (tmpl);
434 tree ctinfo = get_template_info (ctxt);
435 if (!ctinfo)
436 return true;
438 return (TMPL_ARGS_DEPTH (TI_ARGS (tinfo))
439 > TMPL_ARGS_DEPTH (TI_ARGS (ctinfo)));
442 /* Subroutine of maybe_begin_member_template_processing.
443 Returns true if processing DECL needs us to push template parms. */
445 static bool
446 inline_needs_template_parms (tree decl, bool nsdmi)
448 if (!decl || (!nsdmi && ! DECL_TEMPLATE_INFO (decl)))
449 return false;
451 return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
452 > (current_template_depth + DECL_TEMPLATE_SPECIALIZATION (decl)));
455 /* Subroutine of maybe_begin_member_template_processing.
456 Push the template parms in PARMS, starting from LEVELS steps into the
457 chain, and ending at the beginning, since template parms are listed
458 innermost first. */
460 static void
461 push_inline_template_parms_recursive (tree parmlist, int levels)
463 tree parms = TREE_VALUE (parmlist);
464 int i;
466 if (levels > 1)
467 push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
469 ++processing_template_decl;
470 current_template_parms
471 = tree_cons (size_int (current_template_depth + 1),
472 parms, current_template_parms);
473 TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
475 begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
476 NULL);
477 for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
479 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
481 if (error_operand_p (parm))
482 continue;
484 gcc_assert (DECL_P (parm));
486 switch (TREE_CODE (parm))
488 case TYPE_DECL:
489 case TEMPLATE_DECL:
490 pushdecl (parm);
491 break;
493 case PARM_DECL:
494 /* Push the CONST_DECL. */
495 pushdecl (TEMPLATE_PARM_DECL (DECL_INITIAL (parm)));
496 break;
498 default:
499 gcc_unreachable ();
504 /* Restore the template parameter context for a member template, a
505 friend template defined in a class definition, or a non-template
506 member of template class. */
508 void
509 maybe_begin_member_template_processing (tree decl)
511 tree parms;
512 int levels = 0;
513 bool nsdmi = TREE_CODE (decl) == FIELD_DECL;
515 if (nsdmi)
517 tree ctx = DECL_CONTEXT (decl);
518 decl = (CLASSTYPE_TEMPLATE_INFO (ctx)
519 /* Disregard full specializations (c++/60999). */
520 && uses_template_parms (ctx)
521 ? CLASSTYPE_TI_TEMPLATE (ctx) : NULL_TREE);
524 if (inline_needs_template_parms (decl, nsdmi))
526 parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
527 levels = TMPL_PARMS_DEPTH (parms) - current_template_depth;
529 if (DECL_TEMPLATE_SPECIALIZATION (decl))
531 --levels;
532 parms = TREE_CHAIN (parms);
535 push_inline_template_parms_recursive (parms, levels);
538 /* Remember how many levels of template parameters we pushed so that
539 we can pop them later. */
540 inline_parm_levels.safe_push (levels);
543 /* Undo the effects of maybe_begin_member_template_processing. */
545 void
546 maybe_end_member_template_processing (void)
548 int i;
549 int last;
551 if (inline_parm_levels.length () == 0)
552 return;
554 last = inline_parm_levels.pop ();
555 for (i = 0; i < last; ++i)
557 --processing_template_decl;
558 current_template_parms = TREE_CHAIN (current_template_parms);
559 poplevel (0, 0, 0);
563 /* Return a new template argument vector which contains all of ARGS,
564 but has as its innermost set of arguments the EXTRA_ARGS. */
566 tree
567 add_to_template_args (tree args, tree extra_args)
569 tree new_args;
570 int extra_depth;
571 int i;
572 int j;
574 if (args == NULL_TREE || extra_args == error_mark_node)
575 return extra_args;
577 extra_depth = TMPL_ARGS_DEPTH (extra_args);
578 new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
580 for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
581 SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
583 for (j = 1; j <= extra_depth; ++j, ++i)
584 SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
586 return new_args;
589 /* Like add_to_template_args, but only the outermost ARGS are added to
590 the EXTRA_ARGS. In particular, all but TMPL_ARGS_DEPTH
591 (EXTRA_ARGS) levels are added. This function is used to combine
592 the template arguments from a partial instantiation with the
593 template arguments used to attain the full instantiation from the
594 partial instantiation.
596 If ARGS is a TEMPLATE_DECL, use its parameters as args. */
598 tree
599 add_outermost_template_args (tree args, tree extra_args)
601 tree new_args;
603 if (!args)
604 return extra_args;
605 if (TREE_CODE (args) == TEMPLATE_DECL)
607 tree ti = get_template_info (DECL_TEMPLATE_RESULT (args));
608 args = TI_ARGS (ti);
611 /* If there are more levels of EXTRA_ARGS than there are ARGS,
612 something very fishy is going on. */
613 gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
615 /* If *all* the new arguments will be the EXTRA_ARGS, just return
616 them. */
617 if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
618 return extra_args;
620 /* For the moment, we make ARGS look like it contains fewer levels. */
621 TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
623 new_args = add_to_template_args (args, extra_args);
625 /* Now, we restore ARGS to its full dimensions. */
626 TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
628 return new_args;
631 /* Return the N levels of innermost template arguments from the ARGS. */
633 tree
634 get_innermost_template_args (tree args, int n)
636 tree new_args;
637 int extra_levels;
638 int i;
640 gcc_assert (n >= 0);
642 /* If N is 1, just return the innermost set of template arguments. */
643 if (n == 1)
644 return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
646 /* If we're not removing anything, just return the arguments we were
647 given. */
648 extra_levels = TMPL_ARGS_DEPTH (args) - n;
649 gcc_assert (extra_levels >= 0);
650 if (extra_levels == 0)
651 return args;
653 /* Make a new set of arguments, not containing the outer arguments. */
654 new_args = make_tree_vec (n);
655 for (i = 1; i <= n; ++i)
656 SET_TMPL_ARGS_LEVEL (new_args, i,
657 TMPL_ARGS_LEVEL (args, i + extra_levels));
659 return new_args;
662 /* The inverse of get_innermost_template_args: Return all but the innermost
663 EXTRA_LEVELS levels of template arguments from the ARGS. */
665 static tree
666 strip_innermost_template_args (tree args, int extra_levels)
668 tree new_args;
669 int n = TMPL_ARGS_DEPTH (args) - extra_levels;
670 int i;
672 gcc_assert (n >= 0);
674 /* If N is 1, just return the outermost set of template arguments. */
675 if (n == 1)
676 return TMPL_ARGS_LEVEL (args, 1);
678 /* If we're not removing anything, just return the arguments we were
679 given. */
680 gcc_assert (extra_levels >= 0);
681 if (extra_levels == 0)
682 return args;
684 /* Make a new set of arguments, not containing the inner arguments. */
685 new_args = make_tree_vec (n);
686 for (i = 1; i <= n; ++i)
687 SET_TMPL_ARGS_LEVEL (new_args, i,
688 TMPL_ARGS_LEVEL (args, i));
690 return new_args;
693 /* We've got a template header coming up; push to a new level for storing
694 the parms. */
696 void
697 begin_template_parm_list (void)
699 /* We use a non-tag-transparent scope here, which causes pushtag to
700 put tags in this scope, rather than in the enclosing class or
701 namespace scope. This is the right thing, since we want
702 TEMPLATE_DECLS, and not TYPE_DECLS for template classes. For a
703 global template class, push_template_decl handles putting the
704 TEMPLATE_DECL into top-level scope. For a nested template class,
705 e.g.:
707 template <class T> struct S1 {
708 template <class T> struct S2 {};
711 pushtag contains special code to insert the TEMPLATE_DECL for S2
712 at the right scope. */
713 begin_scope (sk_template_parms, NULL);
714 ++processing_template_decl;
715 ++processing_template_parmlist;
716 note_template_header (0);
718 /* Add a dummy parameter level while we process the parameter list. */
719 current_template_parms
720 = tree_cons (size_int (current_template_depth + 1),
721 make_tree_vec (0),
722 current_template_parms);
725 /* This routine is called when a specialization is declared. If it is
726 invalid to declare a specialization here, an error is reported and
727 false is returned, otherwise this routine will return true. */
729 static bool
730 check_specialization_scope (void)
732 tree scope = current_scope ();
734 /* [temp.expl.spec]
736 An explicit specialization shall be declared in the namespace of
737 which the template is a member, or, for member templates, in the
738 namespace of which the enclosing class or enclosing class
739 template is a member. An explicit specialization of a member
740 function, member class or static data member of a class template
741 shall be declared in the namespace of which the class template
742 is a member. */
743 if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
745 error ("explicit specialization in non-namespace scope %qD", scope);
746 return false;
749 /* [temp.expl.spec]
751 In an explicit specialization declaration for a member of a class
752 template or a member template that appears in namespace scope,
753 the member template and some of its enclosing class templates may
754 remain unspecialized, except that the declaration shall not
755 explicitly specialize a class member template if its enclosing
756 class templates are not explicitly specialized as well. */
757 if (current_template_parms)
759 error ("enclosing class templates are not explicitly specialized");
760 return false;
763 return true;
766 /* We've just seen template <>. */
768 bool
769 begin_specialization (void)
771 begin_scope (sk_template_spec, NULL);
772 note_template_header (1);
773 return check_specialization_scope ();
776 /* Called at then end of processing a declaration preceded by
777 template<>. */
779 void
780 end_specialization (void)
782 finish_scope ();
783 reset_specialization ();
786 /* Any template <>'s that we have seen thus far are not referring to a
787 function specialization. */
789 void
790 reset_specialization (void)
792 processing_specialization = 0;
793 template_header_count = 0;
796 /* We've just seen a template header. If SPECIALIZATION is nonzero,
797 it was of the form template <>. */
799 static void
800 note_template_header (int specialization)
802 processing_specialization = specialization;
803 template_header_count++;
806 /* We're beginning an explicit instantiation. */
808 void
809 begin_explicit_instantiation (void)
811 gcc_assert (!processing_explicit_instantiation);
812 processing_explicit_instantiation = true;
816 void
817 end_explicit_instantiation (void)
819 gcc_assert (processing_explicit_instantiation);
820 processing_explicit_instantiation = false;
823 /* An explicit specialization or partial specialization of TMPL is being
824 declared. Check that the namespace in which the specialization is
825 occurring is permissible. Returns false iff it is invalid to
826 specialize TMPL in the current namespace. */
828 static bool
829 check_specialization_namespace (tree tmpl)
831 tree tpl_ns = decl_namespace_context (tmpl);
833 /* [tmpl.expl.spec]
835 An explicit specialization shall be declared in a namespace enclosing the
836 specialized template. An explicit specialization whose declarator-id is
837 not qualified shall be declared in the nearest enclosing namespace of the
838 template, or, if the namespace is inline (7.3.1), any namespace from its
839 enclosing namespace set. */
840 if (current_scope() != DECL_CONTEXT (tmpl)
841 && !at_namespace_scope_p ())
843 error ("specialization of %qD must appear at namespace scope", tmpl);
844 return false;
847 if (is_nested_namespace (current_namespace, tpl_ns, cxx_dialect < cxx11))
848 /* Same or enclosing namespace. */
849 return true;
850 else
852 auto_diagnostic_group d;
853 if (permerror (input_location,
854 "specialization of %qD in different namespace", tmpl))
855 inform (DECL_SOURCE_LOCATION (tmpl),
856 " from definition of %q#D", tmpl);
857 return false;
861 /* SPEC is an explicit instantiation. Check that it is valid to
862 perform this explicit instantiation in the current namespace. */
864 static void
865 check_explicit_instantiation_namespace (tree spec)
867 tree ns;
869 /* DR 275: An explicit instantiation shall appear in an enclosing
870 namespace of its template. */
871 ns = decl_namespace_context (spec);
872 if (!is_nested_namespace (current_namespace, ns))
873 permerror (input_location, "explicit instantiation of %qD in namespace %qD "
874 "(which does not enclose namespace %qD)",
875 spec, current_namespace, ns);
878 /* Returns true if TYPE is a new partial specialization that needs to be
879 set up. This may also modify TYPE to point to the correct (new or
880 existing) constrained partial specialization. */
882 static bool
883 maybe_new_partial_specialization (tree& type)
885 /* An implicit instantiation of an incomplete type implies
886 the definition of a new class template.
888 template<typename T>
889 struct S;
891 template<typename T>
892 struct S<T*>;
894 Here, S<T*> is an implicit instantiation of S whose type
895 is incomplete. */
896 if (CLASSTYPE_IMPLICIT_INSTANTIATION (type) && !COMPLETE_TYPE_P (type))
897 return true;
899 /* It can also be the case that TYPE is a completed specialization.
900 Continuing the previous example, suppose we also declare:
902 template<typename T>
903 requires Integral<T>
904 struct S<T*>;
906 Here, S<T*> refers to the specialization S<T*> defined
907 above. However, we need to differentiate definitions because
908 we intend to define a new partial specialization. In this case,
909 we rely on the fact that the constraints are different for
910 this declaration than that above.
912 Note that we also get here for injected class names and
913 late-parsed template definitions. We must ensure that we
914 do not create new type declarations for those cases. */
915 if (flag_concepts && CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
917 tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
918 tree args = CLASSTYPE_TI_ARGS (type);
920 /* If there are no template parameters, this cannot be a new
921 partial template specialization? */
922 if (!current_template_parms)
923 return false;
925 /* The injected-class-name is not a new partial specialization. */
926 if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
927 return false;
929 /* If the constraints are not the same as those of the primary
930 then, we can probably create a new specialization. */
931 tree type_constr = current_template_constraints ();
933 if (type == TREE_TYPE (tmpl))
935 tree main_constr = get_constraints (tmpl);
936 if (equivalent_constraints (type_constr, main_constr))
937 return false;
940 /* Also, if there's a pre-existing specialization with matching
941 constraints, then this also isn't new. */
942 tree specs = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
943 while (specs)
945 tree spec_tmpl = TREE_VALUE (specs);
946 tree spec_args = TREE_PURPOSE (specs);
947 tree spec_constr = get_constraints (spec_tmpl);
948 if (comp_template_args (args, spec_args)
949 && equivalent_constraints (type_constr, spec_constr))
951 type = TREE_TYPE (spec_tmpl);
952 return false;
954 specs = TREE_CHAIN (specs);
957 /* Create a new type node (and corresponding type decl)
958 for the newly declared specialization. */
959 tree t = make_class_type (TREE_CODE (type));
960 CLASSTYPE_DECLARED_CLASS (t) = CLASSTYPE_DECLARED_CLASS (type);
961 SET_TYPE_TEMPLATE_INFO (t, build_template_info (tmpl, args));
963 /* We only need a separate type node for storing the definition of this
964 partial specialization; uses of S<T*> are unconstrained, so all are
965 equivalent. So keep TYPE_CANONICAL the same. */
966 TYPE_CANONICAL (t) = TYPE_CANONICAL (type);
968 /* Build the corresponding type decl. */
969 tree d = create_implicit_typedef (DECL_NAME (tmpl), t);
970 DECL_CONTEXT (d) = TYPE_CONTEXT (t);
971 DECL_SOURCE_LOCATION (d) = input_location;
972 TREE_PRIVATE (d) = (current_access_specifier == access_private_node);
973 TREE_PROTECTED (d) = (current_access_specifier == access_protected_node);
975 set_instantiating_module (d);
976 DECL_MODULE_EXPORT_P (d) = DECL_MODULE_EXPORT_P (tmpl);
978 type = t;
979 return true;
982 return false;
985 /* The TYPE is being declared. If it is a template type, that means it
986 is a partial specialization. Do appropriate error-checking. */
988 tree
989 maybe_process_partial_specialization (tree type)
991 tree context;
993 if (type == error_mark_node)
994 return error_mark_node;
996 /* A lambda that appears in specialization context is not itself a
997 specialization. */
998 if (CLASS_TYPE_P (type) && CLASSTYPE_LAMBDA_EXPR (type))
999 return type;
1001 /* An injected-class-name is not a specialization. */
1002 if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
1003 return type;
1005 if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
1007 error ("name of class shadows template template parameter %qD",
1008 TYPE_NAME (type));
1009 return error_mark_node;
1012 context = TYPE_CONTEXT (type);
1014 if (TYPE_ALIAS_P (type))
1016 tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (type);
1018 if (tinfo && DECL_ALIAS_TEMPLATE_P (TI_TEMPLATE (tinfo)))
1019 error ("specialization of alias template %qD",
1020 TI_TEMPLATE (tinfo));
1021 else
1022 error ("explicit specialization of non-template %qT", type);
1023 return error_mark_node;
1025 else if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
1027 /* This is for ordinary explicit specialization and partial
1028 specialization of a template class such as:
1030 template <> class C<int>;
1034 template <class T> class C<T*>;
1036 Make sure that `C<int>' and `C<T*>' are implicit instantiations. */
1038 if (maybe_new_partial_specialization (type))
1040 if (!check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type))
1041 && !at_namespace_scope_p ())
1042 return error_mark_node;
1043 SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
1044 DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
1045 if (processing_template_decl)
1047 tree decl = push_template_decl (TYPE_MAIN_DECL (type));
1048 if (decl == error_mark_node)
1049 return error_mark_node;
1050 return TREE_TYPE (decl);
1053 else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
1054 error ("specialization of %qT after instantiation", type);
1055 else if (errorcount && !processing_specialization
1056 && CLASSTYPE_TEMPLATE_SPECIALIZATION (type)
1057 && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
1058 /* Trying to define a specialization either without a template<> header
1059 or in an inappropriate place. We've already given an error, so just
1060 bail now so we don't actually define the specialization. */
1061 return error_mark_node;
1063 else if (CLASS_TYPE_P (type)
1064 && !CLASSTYPE_USE_TEMPLATE (type)
1065 && CLASSTYPE_TEMPLATE_INFO (type)
1066 && context && CLASS_TYPE_P (context)
1067 && CLASSTYPE_TEMPLATE_INFO (context))
1069 /* This is for an explicit specialization of member class
1070 template according to [temp.expl.spec/18]:
1072 template <> template <class U> class C<int>::D;
1074 The context `C<int>' must be an implicit instantiation.
1075 Otherwise this is just a member class template declared
1076 earlier like:
1078 template <> class C<int> { template <class U> class D; };
1079 template <> template <class U> class C<int>::D;
1081 In the first case, `C<int>::D' is a specialization of `C<T>::D'
1082 while in the second case, `C<int>::D' is a primary template
1083 and `C<T>::D' may not exist. */
1085 if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
1086 && !COMPLETE_TYPE_P (type))
1088 tree t;
1089 tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
1091 if (current_namespace
1092 != decl_namespace_context (tmpl))
1094 if (permerror (input_location,
1095 "specialization of %qD in different namespace",
1096 type))
1097 inform (DECL_SOURCE_LOCATION (tmpl),
1098 "from definition of %q#D", tmpl);
1101 /* Check for invalid specialization after instantiation:
1103 template <> template <> class C<int>::D<int>;
1104 template <> template <class U> class C<int>::D; */
1106 for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
1107 t; t = TREE_CHAIN (t))
1109 tree inst = TREE_VALUE (t);
1110 if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst)
1111 || !COMPLETE_OR_OPEN_TYPE_P (inst))
1113 /* We already have a full specialization of this partial
1114 instantiation, or a full specialization has been
1115 looked up but not instantiated. Reassign it to the
1116 new member specialization template. */
1117 spec_entry elt;
1118 spec_entry *entry;
1120 elt.tmpl = most_general_template (tmpl);
1121 elt.args = CLASSTYPE_TI_ARGS (inst);
1122 elt.spec = inst;
1124 type_specializations->remove_elt (&elt);
1126 elt.tmpl = tmpl;
1127 CLASSTYPE_TI_ARGS (inst)
1128 = elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
1130 spec_entry **slot
1131 = type_specializations->find_slot (&elt, INSERT);
1132 entry = ggc_alloc<spec_entry> ();
1133 *entry = elt;
1134 *slot = entry;
1136 else
1137 /* But if we've had an implicit instantiation, that's a
1138 problem ([temp.expl.spec]/6). */
1139 error ("specialization %qT after instantiation %qT",
1140 type, inst);
1143 /* Mark TYPE as a specialization. And as a result, we only
1144 have one level of template argument for the innermost
1145 class template. */
1146 SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
1147 DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
1148 CLASSTYPE_TI_ARGS (type)
1149 = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
1152 else if (processing_specialization)
1154 /* Someday C++0x may allow for enum template specialization. */
1155 if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
1156 && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
1157 pedwarn (input_location, OPT_Wpedantic, "template specialization "
1158 "of %qD not allowed by ISO C++", type);
1159 else
1161 error ("explicit specialization of non-template %qT", type);
1162 return error_mark_node;
1166 return type;
1169 /* Make sure ARGS doesn't use any inappropriate typedefs; we should have
1170 gone through coerce_template_parms by now. */
1172 static void
1173 verify_unstripped_args_1 (tree inner)
1175 for (int i = 0; i < TREE_VEC_LENGTH (inner); ++i)
1177 tree arg = TREE_VEC_ELT (inner, i);
1178 if (TREE_CODE (arg) == TEMPLATE_DECL)
1179 /* OK */;
1180 else if (TYPE_P (arg))
1181 gcc_assert (strip_typedefs (arg, NULL) == arg);
1182 else if (ARGUMENT_PACK_P (arg))
1183 verify_unstripped_args_1 (ARGUMENT_PACK_ARGS (arg));
1184 else if (strip_typedefs (TREE_TYPE (arg), NULL) != TREE_TYPE (arg))
1185 /* Allow typedefs on the type of a non-type argument, since a
1186 parameter can have them. */;
1187 else
1188 gcc_assert (strip_typedefs_expr (arg, NULL) == arg);
1192 static void
1193 verify_unstripped_args (tree args)
1195 ++processing_template_decl;
1196 if (!any_dependent_template_arguments_p (args))
1197 verify_unstripped_args_1 (INNERMOST_TEMPLATE_ARGS (args));
1198 --processing_template_decl;
1201 /* Retrieve the specialization (in the sense of [temp.spec] - a
1202 specialization is either an instantiation or an explicit
1203 specialization) of TMPL for the given template ARGS. If there is
1204 no such specialization, return NULL_TREE. The ARGS are a vector of
1205 arguments, or a vector of vectors of arguments, in the case of
1206 templates with more than one level of parameters.
1208 If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
1209 then we search for a partial specialization matching ARGS. This
1210 parameter is ignored if TMPL is not a class template.
1212 We can also look up a FIELD_DECL, if it is a lambda capture pack; the
1213 result is a NONTYPE_ARGUMENT_PACK. */
1215 static tree
1216 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
1218 if (tmpl == NULL_TREE)
1219 return NULL_TREE;
1221 if (args == error_mark_node)
1222 return NULL_TREE;
1224 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL
1225 || TREE_CODE (tmpl) == FIELD_DECL);
1227 /* There should be as many levels of arguments as there are
1228 levels of parameters. */
1229 gcc_assert (TMPL_ARGS_DEPTH (args)
1230 == (TREE_CODE (tmpl) == TEMPLATE_DECL
1231 ? TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl))
1232 : template_class_depth (DECL_CONTEXT (tmpl))));
1234 if (flag_checking)
1235 verify_unstripped_args (args);
1237 /* Lambda functions in templates aren't instantiated normally, but through
1238 tsubst_lambda_expr. */
1239 if (lambda_fn_in_template_p (tmpl))
1240 return NULL_TREE;
1242 spec_entry elt;
1243 elt.tmpl = tmpl;
1244 elt.args = args;
1245 elt.spec = NULL_TREE;
1247 spec_hash_table *specializations;
1248 if (DECL_CLASS_TEMPLATE_P (tmpl))
1249 specializations = type_specializations;
1250 else
1251 specializations = decl_specializations;
1253 if (hash == 0)
1254 hash = spec_hasher::hash (&elt);
1255 if (spec_entry *found = specializations->find_with_hash (&elt, hash))
1256 return found->spec;
1258 return NULL_TREE;
1261 /* Like retrieve_specialization, but for local declarations. */
1263 tree
1264 retrieve_local_specialization (tree tmpl)
1266 if (local_specializations == NULL)
1267 return NULL_TREE;
1269 tree *slot = local_specializations->get (tmpl);
1270 return slot ? *slot : NULL_TREE;
1273 /* Returns nonzero iff DECL is a specialization of TMPL. */
1276 is_specialization_of (tree decl, tree tmpl)
1278 tree t;
1280 if (TREE_CODE (decl) == FUNCTION_DECL)
1282 for (t = decl;
1283 t != NULL_TREE;
1284 t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1285 if (t == tmpl)
1286 return 1;
1288 else
1290 gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1292 for (t = TREE_TYPE (decl);
1293 t != NULL_TREE;
1294 t = CLASSTYPE_USE_TEMPLATE (t)
1295 ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1296 if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1297 return 1;
1300 return 0;
1303 /* Returns nonzero iff DECL is a specialization of friend declaration
1304 FRIEND_DECL according to [temp.friend]. */
1306 bool
1307 is_specialization_of_friend (tree decl, tree friend_decl)
1309 bool need_template = true;
1310 int template_depth;
1312 gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1313 || TREE_CODE (decl) == TYPE_DECL);
1315 /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1316 of a template class, we want to check if DECL is a specialization
1317 if this. */
1318 if (TREE_CODE (friend_decl) == FUNCTION_DECL
1319 && DECL_TEMPLATE_INFO (friend_decl)
1320 && !DECL_USE_TEMPLATE (friend_decl))
1322 /* We want a TEMPLATE_DECL for `is_specialization_of'. */
1323 friend_decl = DECL_TI_TEMPLATE (friend_decl);
1324 need_template = false;
1326 else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1327 && !PRIMARY_TEMPLATE_P (friend_decl))
1328 need_template = false;
1330 /* There is nothing to do if this is not a template friend. */
1331 if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1332 return false;
1334 if (is_specialization_of (decl, friend_decl))
1335 return true;
1337 /* [temp.friend/6]
1338 A member of a class template may be declared to be a friend of a
1339 non-template class. In this case, the corresponding member of
1340 every specialization of the class template is a friend of the
1341 class granting friendship.
1343 For example, given a template friend declaration
1345 template <class T> friend void A<T>::f();
1347 the member function below is considered a friend
1349 template <> struct A<int> {
1350 void f();
1353 For this type of template friend, TEMPLATE_DEPTH below will be
1354 nonzero. To determine if DECL is a friend of FRIEND, we first
1355 check if the enclosing class is a specialization of another. */
1357 template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1358 if (template_depth
1359 && DECL_CLASS_SCOPE_P (decl)
1360 && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1361 CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1363 /* Next, we check the members themselves. In order to handle
1364 a few tricky cases, such as when FRIEND_DECL's are
1366 template <class T> friend void A<T>::g(T t);
1367 template <class T> template <T t> friend void A<T>::h();
1369 and DECL's are
1371 void A<int>::g(int);
1372 template <int> void A<int>::h();
1374 we need to figure out ARGS, the template arguments from
1375 the context of DECL. This is required for template substitution
1376 of `T' in the function parameter of `g' and template parameter
1377 of `h' in the above examples. Here ARGS corresponds to `int'. */
1379 tree context = DECL_CONTEXT (decl);
1380 tree args = NULL_TREE;
1381 int current_depth = 0;
1383 while (current_depth < template_depth)
1385 if (CLASSTYPE_TEMPLATE_INFO (context))
1387 if (current_depth == 0)
1388 args = TYPE_TI_ARGS (context);
1389 else
1390 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1391 current_depth++;
1393 context = TYPE_CONTEXT (context);
1396 if (TREE_CODE (decl) == FUNCTION_DECL)
1398 bool is_template;
1399 tree friend_type;
1400 tree decl_type;
1401 tree friend_args_type;
1402 tree decl_args_type;
1404 /* Make sure that both DECL and FRIEND_DECL are templates or
1405 non-templates. */
1406 is_template = DECL_TEMPLATE_INFO (decl)
1407 && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1408 if (need_template ^ is_template)
1409 return false;
1410 else if (is_template)
1412 /* If both are templates, check template parameter list. */
1413 tree friend_parms
1414 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1415 args, tf_none);
1416 if (!comp_template_parms
1417 (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1418 friend_parms))
1419 return false;
1421 decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1423 else
1424 decl_type = TREE_TYPE (decl);
1426 friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1427 tf_none, NULL_TREE);
1428 if (friend_type == error_mark_node)
1429 return false;
1431 /* Check if return types match. */
1432 if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1433 return false;
1435 /* Check if function parameter types match, ignoring the
1436 `this' parameter. */
1437 friend_args_type = TYPE_ARG_TYPES (friend_type);
1438 decl_args_type = TYPE_ARG_TYPES (decl_type);
1439 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1440 friend_args_type = TREE_CHAIN (friend_args_type);
1441 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1442 decl_args_type = TREE_CHAIN (decl_args_type);
1444 return compparms (decl_args_type, friend_args_type);
1446 else
1448 /* DECL is a TYPE_DECL */
1449 bool is_template;
1450 tree decl_type = TREE_TYPE (decl);
1452 /* Make sure that both DECL and FRIEND_DECL are templates or
1453 non-templates. */
1454 is_template
1455 = CLASSTYPE_TEMPLATE_INFO (decl_type)
1456 && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1458 if (need_template ^ is_template)
1459 return false;
1460 else if (is_template)
1462 tree friend_parms;
1463 /* If both are templates, check the name of the two
1464 TEMPLATE_DECL's first because is_friend didn't. */
1465 if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1466 != DECL_NAME (friend_decl))
1467 return false;
1469 /* Now check template parameter list. */
1470 friend_parms
1471 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1472 args, tf_none);
1473 return comp_template_parms
1474 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1475 friend_parms);
1477 else
1478 return (DECL_NAME (decl)
1479 == DECL_NAME (friend_decl));
1482 return false;
1485 /* Register the specialization SPEC as a specialization of TMPL with
1486 the indicated ARGS. IS_FRIEND indicates whether the specialization
1487 is actually just a friend declaration. ATTRLIST is the list of
1488 attributes that the specialization is declared with or NULL when
1489 it isn't. Returns SPEC, or an equivalent prior declaration, if
1490 available.
1492 We also store instantiations of field packs in the hash table, even
1493 though they are not themselves templates, to make lookup easier. */
1495 static tree
1496 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1497 hashval_t hash)
1499 tree fn;
1501 gcc_assert ((TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec))
1502 || (TREE_CODE (tmpl) == FIELD_DECL
1503 && TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK));
1505 if (TREE_CODE (spec) == FUNCTION_DECL
1506 && uses_template_parms (DECL_TI_ARGS (spec)))
1507 /* This is the FUNCTION_DECL for a partial instantiation. Don't
1508 register it; we want the corresponding TEMPLATE_DECL instead.
1509 We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1510 the more obvious `uses_template_parms (spec)' to avoid problems
1511 with default function arguments. In particular, given
1512 something like this:
1514 template <class T> void f(T t1, T t = T())
1516 the default argument expression is not substituted for in an
1517 instantiation unless and until it is actually needed. */
1518 return spec;
1520 spec_entry elt;
1521 elt.tmpl = tmpl;
1522 elt.args = args;
1523 elt.spec = spec;
1525 if (hash == 0)
1526 hash = spec_hasher::hash (&elt);
1528 spec_entry **slot = decl_specializations->find_slot_with_hash (&elt, hash, INSERT);
1529 if (*slot)
1530 fn = (*slot)->spec;
1531 else
1532 fn = NULL_TREE;
1534 /* We can sometimes try to re-register a specialization that we've
1535 already got. In particular, regenerate_decl_from_template calls
1536 duplicate_decls which will update the specialization list. But,
1537 we'll still get called again here anyhow. It's more convenient
1538 to simply allow this than to try to prevent it. */
1539 if (fn == spec)
1540 return spec;
1541 else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1543 if (DECL_TEMPLATE_INSTANTIATION (fn))
1545 if (DECL_ODR_USED (fn)
1546 || DECL_EXPLICIT_INSTANTIATION (fn))
1548 error ("specialization of %qD after instantiation",
1549 fn);
1550 return error_mark_node;
1552 else
1554 tree clone;
1555 /* This situation should occur only if the first
1556 specialization is an implicit instantiation, the
1557 second is an explicit specialization, and the
1558 implicit instantiation has not yet been used. That
1559 situation can occur if we have implicitly
1560 instantiated a member function and then specialized
1561 it later.
1563 We can also wind up here if a friend declaration that
1564 looked like an instantiation turns out to be a
1565 specialization:
1567 template <class T> void foo(T);
1568 class S { friend void foo<>(int) };
1569 template <> void foo(int);
1571 We transform the existing DECL in place so that any
1572 pointers to it become pointers to the updated
1573 declaration.
1575 If there was a definition for the template, but not
1576 for the specialization, we want this to look as if
1577 there were no definition, and vice versa. */
1578 DECL_INITIAL (fn) = NULL_TREE;
1579 duplicate_decls (spec, fn, /*hiding=*/is_friend);
1581 /* The call to duplicate_decls will have applied
1582 [temp.expl.spec]:
1584 An explicit specialization of a function template
1585 is inline only if it is explicitly declared to be,
1586 and independently of whether its function template
1589 to the primary function; now copy the inline bits to
1590 the various clones. */
1591 FOR_EACH_CLONE (clone, fn)
1593 DECL_DECLARED_INLINE_P (clone)
1594 = DECL_DECLARED_INLINE_P (fn);
1595 DECL_SOURCE_LOCATION (clone)
1596 = DECL_SOURCE_LOCATION (fn);
1597 DECL_DELETED_FN (clone)
1598 = DECL_DELETED_FN (fn);
1600 check_specialization_namespace (tmpl);
1602 return fn;
1605 else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1607 tree dd = duplicate_decls (spec, fn, /*hiding=*/is_friend);
1608 if (dd == error_mark_node)
1609 /* We've already complained in duplicate_decls. */
1610 return error_mark_node;
1612 if (dd == NULL_TREE && DECL_INITIAL (spec))
1613 /* Dup decl failed, but this is a new definition. Set the
1614 line number so any errors match this new
1615 definition. */
1616 DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1618 return fn;
1621 else if (fn)
1622 return duplicate_decls (spec, fn, /*hiding=*/is_friend);
1624 /* A specialization must be declared in the same namespace as the
1625 template it is specializing. */
1626 if (DECL_P (spec) && DECL_TEMPLATE_SPECIALIZATION (spec)
1627 && !check_specialization_namespace (tmpl))
1628 DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1630 spec_entry *entry = ggc_alloc<spec_entry> ();
1631 gcc_assert (tmpl && args && spec);
1632 *entry = elt;
1633 *slot = entry;
1634 if ((TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1635 && PRIMARY_TEMPLATE_P (tmpl)
1636 && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1637 || variable_template_p (tmpl))
1638 /* If TMPL is a forward declaration of a template function, keep a list
1639 of all specializations in case we need to reassign them to a friend
1640 template later in tsubst_friend_function.
1642 Also keep a list of all variable template instantiations so that
1643 process_partial_specialization can check whether a later partial
1644 specialization would have used it. */
1645 DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1646 = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1648 return spec;
1651 /* Restricts tree and type comparisons. */
1652 int comparing_specializations;
1653 int comparing_dependent_aliases;
1655 /* Returns true iff two spec_entry nodes are equivalent. */
1657 bool
1658 spec_hasher::equal (spec_entry *e1, spec_entry *e2)
1660 int equal;
1662 ++comparing_specializations;
1663 ++comparing_dependent_aliases;
1664 ++processing_template_decl;
1665 equal = (e1->tmpl == e2->tmpl
1666 && comp_template_args (e1->args, e2->args));
1667 if (equal && flag_concepts
1668 /* tmpl could be a FIELD_DECL for a capture pack. */
1669 && TREE_CODE (e1->tmpl) == TEMPLATE_DECL
1670 && VAR_P (DECL_TEMPLATE_RESULT (e1->tmpl))
1671 && uses_template_parms (e1->args))
1673 /* Partial specializations of a variable template can be distinguished by
1674 constraints. */
1675 tree c1 = e1->spec ? get_constraints (e1->spec) : NULL_TREE;
1676 tree c2 = e2->spec ? get_constraints (e2->spec) : NULL_TREE;
1677 equal = equivalent_constraints (c1, c2);
1679 --processing_template_decl;
1680 --comparing_dependent_aliases;
1681 --comparing_specializations;
1683 return equal;
1686 /* Returns a hash for a template TMPL and template arguments ARGS. */
1688 static hashval_t
1689 hash_tmpl_and_args (tree tmpl, tree args)
1691 hashval_t val = iterative_hash_object (DECL_UID (tmpl), 0);
1692 return iterative_hash_template_arg (args, val);
1695 hashval_t
1696 spec_hasher::hash (tree tmpl, tree args)
1698 ++comparing_specializations;
1699 hashval_t val = hash_tmpl_and_args (tmpl, args);
1700 --comparing_specializations;
1701 return val;
1704 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1705 ignoring SPEC. */
1707 hashval_t
1708 spec_hasher::hash (spec_entry *e)
1710 return spec_hasher::hash (e->tmpl, e->args);
1713 /* Recursively calculate a hash value for a template argument ARG, for use
1714 in the hash tables of template specializations. We must be
1715 careful to (at least) skip the same entities template_args_equal
1716 does. */
1718 hashval_t
1719 iterative_hash_template_arg (tree arg, hashval_t val)
1721 if (arg == NULL_TREE)
1722 return iterative_hash_object (arg, val);
1724 if (!TYPE_P (arg))
1725 /* Strip nop-like things, but not the same as STRIP_NOPS. */
1726 while (CONVERT_EXPR_P (arg)
1727 || TREE_CODE (arg) == NON_LVALUE_EXPR
1728 || class_nttp_const_wrapper_p (arg))
1729 arg = TREE_OPERAND (arg, 0);
1731 enum tree_code code = TREE_CODE (arg);
1733 val = iterative_hash_object (code, val);
1735 switch (code)
1737 case ARGUMENT_PACK_SELECT:
1738 /* Getting here with an ARGUMENT_PACK_SELECT means we're probably
1739 preserving it in a hash table, which is bad because it will change
1740 meaning when gen_elem_of_pack_expansion_instantiation changes the
1741 ARGUMENT_PACK_SELECT_INDEX. */
1742 gcc_unreachable ();
1744 case ERROR_MARK:
1745 return val;
1747 case IDENTIFIER_NODE:
1748 return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1750 case TREE_VEC:
1751 for (tree elt : tree_vec_range (arg))
1752 val = iterative_hash_template_arg (elt, val);
1753 return val;
1755 case TYPE_PACK_EXPANSION:
1756 case EXPR_PACK_EXPANSION:
1757 val = iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1758 return iterative_hash_template_arg (PACK_EXPANSION_EXTRA_ARGS (arg), val);
1760 case TYPE_ARGUMENT_PACK:
1761 case NONTYPE_ARGUMENT_PACK:
1762 return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1764 case TREE_LIST:
1765 for (; arg; arg = TREE_CHAIN (arg))
1766 val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1767 return val;
1769 case OVERLOAD:
1770 for (lkp_iterator iter (arg); iter; ++iter)
1771 val = iterative_hash_template_arg (*iter, val);
1772 return val;
1774 case CONSTRUCTOR:
1776 iterative_hash_template_arg (TREE_TYPE (arg), val);
1777 for (auto &e: CONSTRUCTOR_ELTS (arg))
1779 val = iterative_hash_template_arg (e.index, val);
1780 val = iterative_hash_template_arg (e.value, val);
1782 return val;
1785 case PARM_DECL:
1786 if (!DECL_ARTIFICIAL (arg))
1788 val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1789 val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
1791 return iterative_hash_template_arg (TREE_TYPE (arg), val);
1793 case TARGET_EXPR:
1794 return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1796 case PTRMEM_CST:
1797 val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1798 return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1800 case TEMPLATE_PARM_INDEX:
1801 val = iterative_hash_template_arg
1802 (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1803 val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1804 return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1806 case TRAIT_EXPR:
1807 val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1808 val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1809 return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1811 case BASELINK:
1812 val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1813 val);
1814 return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1815 val);
1817 case MODOP_EXPR:
1818 val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1819 code = TREE_CODE (TREE_OPERAND (arg, 1));
1820 val = iterative_hash_object (code, val);
1821 return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1823 case LAMBDA_EXPR:
1824 /* [temp.over.link] Two lambda-expressions are never considered
1825 equivalent.
1827 So just hash the closure type. */
1828 return iterative_hash_template_arg (TREE_TYPE (arg), val);
1830 case CAST_EXPR:
1831 case IMPLICIT_CONV_EXPR:
1832 case STATIC_CAST_EXPR:
1833 case REINTERPRET_CAST_EXPR:
1834 case CONST_CAST_EXPR:
1835 case DYNAMIC_CAST_EXPR:
1836 case NEW_EXPR:
1837 val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1838 /* Now hash operands as usual. */
1839 break;
1841 case CALL_EXPR:
1843 tree fn = CALL_EXPR_FN (arg);
1844 if (tree name = dependent_name (fn))
1846 if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
1847 val = iterative_hash_template_arg (TREE_OPERAND (fn, 1), val);
1848 fn = name;
1850 val = iterative_hash_template_arg (fn, val);
1851 call_expr_arg_iterator ai;
1852 for (tree x = first_call_expr_arg (arg, &ai); x;
1853 x = next_call_expr_arg (&ai))
1854 val = iterative_hash_template_arg (x, val);
1855 return val;
1858 default:
1859 break;
1862 char tclass = TREE_CODE_CLASS (code);
1863 switch (tclass)
1865 case tcc_type:
1866 if (tree ats = alias_template_specialization_p (arg, nt_transparent))
1868 // We want an alias specialization that survived strip_typedefs
1869 // to hash differently from its TYPE_CANONICAL, to avoid hash
1870 // collisions that compare as different in template_args_equal.
1871 // These could be dependent specializations that strip_typedefs
1872 // left alone, or untouched specializations because
1873 // coerce_template_parms returns the unconverted template
1874 // arguments if it sees incomplete argument packs.
1875 tree ti = TYPE_ALIAS_TEMPLATE_INFO (ats);
1876 return hash_tmpl_and_args (TI_TEMPLATE (ti), TI_ARGS (ti));
1879 switch (TREE_CODE (arg))
1881 case TEMPLATE_TEMPLATE_PARM:
1883 tree tpi = TEMPLATE_TYPE_PARM_INDEX (arg);
1885 /* Do not recurse with TPI directly, as that is unbounded
1886 recursion. */
1887 val = iterative_hash_object (TEMPLATE_PARM_LEVEL (tpi), val);
1888 val = iterative_hash_object (TEMPLATE_PARM_IDX (tpi), val);
1890 break;
1892 case DECLTYPE_TYPE:
1893 val = iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1894 break;
1896 case TYPENAME_TYPE:
1897 if (comparing_specializations)
1899 /* Hash the components that are relevant to TYPENAME_TYPE
1900 equivalence as determined by structural_comptypes. We
1901 can only coherently do this when comparing_specializations
1902 is set, because otherwise structural_comptypes tries
1903 resolving TYPENAME_TYPE via the current instantiation. */
1904 tree context = TYPE_MAIN_VARIANT (TYPE_CONTEXT (arg));
1905 tree fullname = TYPENAME_TYPE_FULLNAME (arg);
1906 val = iterative_hash_template_arg (context, val);
1907 val = iterative_hash_template_arg (fullname, val);
1909 break;
1911 default:
1912 if (tree canonical = TYPE_CANONICAL (arg))
1913 val = iterative_hash_object (TYPE_HASH (canonical), val);
1914 break;
1917 return val;
1919 case tcc_declaration:
1920 case tcc_constant:
1921 return iterative_hash_expr (arg, val);
1923 default:
1924 gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1925 for (int i = 0, n = cp_tree_operand_length (arg); i < n; ++i)
1926 val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1927 return val;
1931 /* Unregister the specialization SPEC as a specialization of TMPL.
1932 Replace it with NEW_SPEC, if NEW_SPEC is non-NULL. Returns true
1933 if the SPEC was listed as a specialization of TMPL.
1935 Note that SPEC has been ggc_freed, so we can't look inside it. */
1937 bool
1938 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1940 spec_entry *entry;
1941 spec_entry elt;
1943 elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1944 elt.args = TI_ARGS (tinfo);
1945 elt.spec = NULL_TREE;
1947 entry = decl_specializations->find (&elt);
1948 if (entry != NULL)
1950 gcc_assert (entry->spec == spec || entry->spec == new_spec);
1951 gcc_assert (new_spec != NULL_TREE);
1952 entry->spec = new_spec;
1953 return 1;
1956 return 0;
1959 /* Like register_specialization, but for local declarations. We are
1960 registering SPEC, an instantiation of TMPL. */
1962 void
1963 register_local_specialization (tree spec, tree tmpl)
1965 gcc_assert (tmpl != spec);
1966 local_specializations->put (tmpl, spec);
1969 /* Registers T as a specialization of itself. This is used to preserve
1970 the references to already-parsed parameters when instantiating
1971 postconditions. */
1973 void
1974 register_local_identity (tree t)
1976 local_specializations->put (t, t);
1979 /* TYPE is a class type. Returns true if TYPE is an explicitly
1980 specialized class. */
1982 bool
1983 explicit_class_specialization_p (tree type)
1985 if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1986 return false;
1987 return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1990 /* Print the list of functions at FNS, going through all the overloads
1991 for each element of the list. Alternatively, FNS cannot be a
1992 TREE_LIST, in which case it will be printed together with all the
1993 overloads.
1995 MORE and *STR should respectively be FALSE and NULL when the function
1996 is called from the outside. They are used internally on recursive
1997 calls. print_candidates manages the two parameters and leaves NULL
1998 in *STR when it ends. */
2000 static void
2001 print_candidates_1 (tree fns, char **str, bool more = false)
2003 if (TREE_CODE (fns) == TREE_LIST)
2004 for (; fns; fns = TREE_CHAIN (fns))
2005 print_candidates_1 (TREE_VALUE (fns), str, more || TREE_CHAIN (fns));
2006 else
2007 for (lkp_iterator iter (fns); iter;)
2009 tree cand = *iter;
2010 ++iter;
2012 const char *pfx = *str;
2013 if (!pfx)
2015 if (more || iter)
2016 pfx = _("candidates are:");
2017 else
2018 pfx = _("candidate is:");
2019 *str = get_spaces (pfx);
2021 inform (DECL_SOURCE_LOCATION (cand), "%s %#qD", pfx, cand);
2025 /* Print the list of candidate FNS in an error message. FNS can also
2026 be a TREE_LIST of non-functions in the case of an ambiguous lookup. */
2028 void
2029 print_candidates (tree fns)
2031 char *str = NULL;
2032 print_candidates_1 (fns, &str);
2033 free (str);
2036 /* Get a (possibly) constrained template declaration for the
2037 purpose of ordering candidates. */
2038 static tree
2039 get_template_for_ordering (tree list)
2041 gcc_assert (TREE_CODE (list) == TREE_LIST);
2042 tree f = TREE_VALUE (list);
2043 if (tree ti = DECL_TEMPLATE_INFO (f))
2044 return TI_TEMPLATE (ti);
2045 return f;
2048 /* Among candidates having the same signature, return the
2049 most constrained or NULL_TREE if there is no best candidate.
2050 If the signatures of candidates vary (e.g., template
2051 specialization vs. member function), then there can be no
2052 most constrained.
2054 Note that we don't compare constraints on the functions
2055 themselves, but rather those of their templates. */
2056 static tree
2057 most_constrained_function (tree candidates)
2059 // Try to find the best candidate in a first pass.
2060 tree champ = candidates;
2061 for (tree c = TREE_CHAIN (champ); c; c = TREE_CHAIN (c))
2063 int winner = more_constrained (get_template_for_ordering (champ),
2064 get_template_for_ordering (c));
2065 if (winner == -1)
2066 champ = c; // The candidate is more constrained
2067 else if (winner == 0)
2068 return NULL_TREE; // Neither is more constrained
2071 // Verify that the champ is better than previous candidates.
2072 for (tree c = candidates; c != champ; c = TREE_CHAIN (c)) {
2073 if (!more_constrained (get_template_for_ordering (champ),
2074 get_template_for_ordering (c)))
2075 return NULL_TREE;
2078 return champ;
2082 /* Returns the template (one of the functions given by TEMPLATE_ID)
2083 which can be specialized to match the indicated DECL with the
2084 explicit template args given in TEMPLATE_ID. The DECL may be
2085 NULL_TREE if none is available. In that case, the functions in
2086 TEMPLATE_ID are non-members.
2088 If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
2089 specialization of a member template.
2091 The TEMPLATE_COUNT is the number of references to qualifying
2092 template classes that appeared in the name of the function. See
2093 check_explicit_specialization for a more accurate description.
2095 TSK indicates what kind of template declaration (if any) is being
2096 declared. TSK_TEMPLATE indicates that the declaration given by
2097 DECL, though a FUNCTION_DECL, has template parameters, and is
2098 therefore a template function.
2100 The template args (those explicitly specified and those deduced)
2101 are output in a newly created vector *TARGS_OUT.
2103 If it is impossible to determine the result, an error message is
2104 issued. The error_mark_node is returned to indicate failure. */
2106 static tree
2107 determine_specialization (tree template_id,
2108 tree decl,
2109 tree* targs_out,
2110 int need_member_template,
2111 int template_count,
2112 tmpl_spec_kind tsk)
2114 tree fns;
2115 tree targs;
2116 tree explicit_targs;
2117 tree candidates = NULL_TREE;
2119 /* A TREE_LIST of templates of which DECL may be a specialization.
2120 The TREE_VALUE of each node is a TEMPLATE_DECL. The
2121 corresponding TREE_PURPOSE is the set of template arguments that,
2122 when used to instantiate the template, would produce a function
2123 with the signature of DECL. */
2124 tree templates = NULL_TREE;
2125 int header_count;
2126 cp_binding_level *b;
2128 *targs_out = NULL_TREE;
2130 if (template_id == error_mark_node || decl == error_mark_node)
2131 return error_mark_node;
2133 /* We shouldn't be specializing a member template of an
2134 unspecialized class template; we already gave an error in
2135 check_specialization_scope, now avoid crashing. */
2136 if (!VAR_P (decl)
2137 && template_count && DECL_CLASS_SCOPE_P (decl)
2138 && template_class_depth (DECL_CONTEXT (decl)) > 0)
2140 gcc_assert (errorcount);
2141 return error_mark_node;
2144 fns = TREE_OPERAND (template_id, 0);
2145 explicit_targs = TREE_OPERAND (template_id, 1);
2147 if (fns == error_mark_node)
2148 return error_mark_node;
2150 /* Check for baselinks. */
2151 if (BASELINK_P (fns))
2152 fns = BASELINK_FUNCTIONS (fns);
2154 if (TREE_CODE (decl) == FUNCTION_DECL && !is_overloaded_fn (fns))
2156 error_at (DECL_SOURCE_LOCATION (decl),
2157 "%qD is not a function template", fns);
2158 return error_mark_node;
2160 else if (VAR_P (decl) && !variable_template_p (fns))
2162 error ("%qD is not a variable template", fns);
2163 return error_mark_node;
2166 /* Count the number of template headers specified for this
2167 specialization. */
2168 header_count = 0;
2169 for (b = current_binding_level;
2170 b->kind == sk_template_parms;
2171 b = b->level_chain)
2172 ++header_count;
2174 tree orig_fns = fns;
2175 bool header_mismatch = false;
2177 if (variable_template_p (fns))
2179 tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (fns));
2180 targs = coerce_template_parms (parms, explicit_targs, fns,
2181 tf_warning_or_error);
2182 if (targs != error_mark_node
2183 && constraints_satisfied_p (fns, targs))
2184 templates = tree_cons (targs, fns, templates);
2186 else for (lkp_iterator iter (fns); iter; ++iter)
2188 tree fn = *iter;
2190 if (TREE_CODE (fn) == TEMPLATE_DECL)
2192 tree decl_arg_types;
2193 tree fn_arg_types;
2195 /* In case of explicit specialization, we need to check if
2196 the number of template headers appearing in the specialization
2197 is correct. This is usually done in check_explicit_specialization,
2198 but the check done there cannot be exhaustive when specializing
2199 member functions. Consider the following code:
2201 template <> void A<int>::f(int);
2202 template <> template <> void A<int>::f(int);
2204 Assuming that A<int> is not itself an explicit specialization
2205 already, the first line specializes "f" which is a non-template
2206 member function, whilst the second line specializes "f" which
2207 is a template member function. So both lines are syntactically
2208 correct, and check_explicit_specialization does not reject
2209 them.
2211 Here, we can do better, as we are matching the specialization
2212 against the declarations. We count the number of template
2213 headers, and we check if they match TEMPLATE_COUNT + 1
2214 (TEMPLATE_COUNT is the number of qualifying template classes,
2215 plus there must be another header for the member template
2216 itself).
2218 Notice that if header_count is zero, this is not a
2219 specialization but rather a template instantiation, so there
2220 is no check we can perform here. */
2221 if (header_count && header_count != template_count + 1)
2223 header_mismatch = true;
2224 continue;
2227 /* Check that the number of template arguments at the
2228 innermost level for DECL is the same as for FN. */
2229 if (current_binding_level->kind == sk_template_parms
2230 && !current_binding_level->explicit_spec_p
2231 && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
2232 != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
2233 (current_template_parms))))
2234 continue;
2236 /* DECL might be a specialization of FN. */
2237 decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2238 fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
2240 /* For a non-static member function, we need to make sure
2241 that the const qualification is the same. Since
2242 get_bindings does not try to merge the "this" parameter,
2243 we must do the comparison explicitly. */
2244 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn))
2246 if (!same_type_p (TREE_VALUE (fn_arg_types),
2247 TREE_VALUE (decl_arg_types)))
2248 continue;
2250 /* And the ref-qualification. */
2251 if (type_memfn_rqual (TREE_TYPE (decl))
2252 != type_memfn_rqual (TREE_TYPE (fn)))
2253 continue;
2256 /* Skip the "this" parameter and, for constructors of
2257 classes with virtual bases, the VTT parameter. A
2258 full specialization of a constructor will have a VTT
2259 parameter, but a template never will. */
2260 decl_arg_types
2261 = skip_artificial_parms_for (decl, decl_arg_types);
2262 fn_arg_types
2263 = skip_artificial_parms_for (fn, fn_arg_types);
2265 /* Function templates cannot be specializations; there are
2266 no partial specializations of functions. Therefore, if
2267 the type of DECL does not match FN, there is no
2268 match.
2270 Note that it should never be the case that we have both
2271 candidates added here, and for regular member functions
2272 below. */
2273 if (tsk == tsk_template)
2275 if (!comp_template_parms (DECL_TEMPLATE_PARMS (fn),
2276 current_template_parms))
2277 continue;
2278 if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2279 TREE_TYPE (TREE_TYPE (fn))))
2280 continue;
2281 if (!compparms (fn_arg_types, decl_arg_types))
2282 continue;
2284 tree freq = get_constraints (fn);
2285 tree dreq = get_constraints (decl);
2286 if (!freq != !dreq)
2287 continue;
2288 if (freq)
2290 /* C++20 CA104: Substitute directly into the
2291 constraint-expression. */
2292 tree fargs = DECL_TI_ARGS (fn);
2293 tsubst_flags_t complain = tf_none;
2294 freq = tsubst_constraint_info (freq, fargs, complain, fn);
2295 if (!cp_tree_equal (freq, dreq))
2296 continue;
2299 candidates = tree_cons (NULL_TREE, fn, candidates);
2300 continue;
2303 /* See whether this function might be a specialization of this
2304 template. Suppress access control because we might be trying
2305 to make this specialization a friend, and we have already done
2306 access control for the declaration of the specialization. */
2307 push_deferring_access_checks (dk_no_check);
2308 targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
2309 pop_deferring_access_checks ();
2311 if (!targs)
2312 /* We cannot deduce template arguments that when used to
2313 specialize TMPL will produce DECL. */
2314 continue;
2316 if (uses_template_parms (targs))
2317 /* We deduced something involving 'auto', which isn't a valid
2318 template argument. */
2319 continue;
2321 /* Save this template, and the arguments deduced. */
2322 templates = tree_cons (targs, fn, templates);
2324 else if (need_member_template)
2325 /* FN is an ordinary member function, and we need a
2326 specialization of a member template. */
2328 else if (TREE_CODE (fn) != FUNCTION_DECL)
2329 /* We can get IDENTIFIER_NODEs here in certain erroneous
2330 cases. */
2332 else if (!DECL_FUNCTION_MEMBER_P (fn))
2333 /* This is just an ordinary non-member function. Nothing can
2334 be a specialization of that. */
2336 else if (DECL_ARTIFICIAL (fn))
2337 /* Cannot specialize functions that are created implicitly. */
2339 else
2341 tree decl_arg_types;
2343 /* This is an ordinary member function. However, since
2344 we're here, we can assume its enclosing class is a
2345 template class. For example,
2347 template <typename T> struct S { void f(); };
2348 template <> void S<int>::f() {}
2350 Here, S<int>::f is a non-template, but S<int> is a
2351 template class. If FN has the same type as DECL, we
2352 might be in business. */
2354 if (!DECL_TEMPLATE_INFO (fn))
2355 /* Its enclosing class is an explicit specialization
2356 of a template class. This is not a candidate. */
2357 continue;
2359 if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2360 TREE_TYPE (TREE_TYPE (fn))))
2361 /* The return types differ. */
2362 continue;
2364 /* Adjust the type of DECL in case FN is a static member. */
2365 decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2366 if (DECL_STATIC_FUNCTION_P (fn)
2367 && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2368 decl_arg_types = TREE_CHAIN (decl_arg_types);
2370 if (!compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
2371 decl_arg_types))
2372 continue;
2374 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
2375 && (type_memfn_rqual (TREE_TYPE (decl))
2376 != type_memfn_rqual (TREE_TYPE (fn))))
2377 continue;
2379 // If the deduced arguments do not satisfy the constraints,
2380 // this is not a candidate.
2381 if (flag_concepts && !constraints_satisfied_p (fn))
2382 continue;
2384 // Add the candidate.
2385 candidates = tree_cons (NULL_TREE, fn, candidates);
2389 if (templates && TREE_CHAIN (templates))
2391 /* We have:
2393 [temp.expl.spec]
2395 It is possible for a specialization with a given function
2396 signature to be instantiated from more than one function
2397 template. In such cases, explicit specification of the
2398 template arguments must be used to uniquely identify the
2399 function template specialization being specialized.
2401 Note that here, there's no suggestion that we're supposed to
2402 determine which of the candidate templates is most
2403 specialized. However, we, also have:
2405 [temp.func.order]
2407 Partial ordering of overloaded function template
2408 declarations is used in the following contexts to select
2409 the function template to which a function template
2410 specialization refers:
2412 -- when an explicit specialization refers to a function
2413 template.
2415 So, we do use the partial ordering rules, at least for now.
2416 This extension can only serve to make invalid programs valid,
2417 so it's safe. And, there is strong anecdotal evidence that
2418 the committee intended the partial ordering rules to apply;
2419 the EDG front end has that behavior, and John Spicer claims
2420 that the committee simply forgot to delete the wording in
2421 [temp.expl.spec]. */
2422 tree tmpl = most_specialized_instantiation (templates);
2423 if (tmpl != error_mark_node)
2425 templates = tmpl;
2426 TREE_CHAIN (templates) = NULL_TREE;
2430 // Concepts allows multiple declarations of member functions
2431 // with the same signature. Like above, we need to rely on
2432 // on the partial ordering of those candidates to determine which
2433 // is the best.
2434 if (flag_concepts && candidates && TREE_CHAIN (candidates))
2436 if (tree cand = most_constrained_function (candidates))
2438 candidates = cand;
2439 TREE_CHAIN (cand) = NULL_TREE;
2443 if (templates == NULL_TREE && candidates == NULL_TREE)
2445 error ("template-id %qD for %q+D does not match any template "
2446 "declaration", template_id, decl);
2447 if (header_mismatch)
2448 inform (DECL_SOURCE_LOCATION (decl),
2449 "saw %d %<template<>%>, need %d for "
2450 "specializing a member function template",
2451 header_count, template_count + 1);
2452 print_candidates (orig_fns);
2453 return error_mark_node;
2455 else if ((templates && TREE_CHAIN (templates))
2456 || (candidates && TREE_CHAIN (candidates))
2457 || (templates && candidates))
2459 error ("ambiguous template specialization %qD for %q+D",
2460 template_id, decl);
2461 candidates = chainon (candidates, templates);
2462 print_candidates (candidates);
2463 return error_mark_node;
2466 /* We have one, and exactly one, match. */
2467 if (candidates)
2469 tree fn = TREE_VALUE (candidates);
2470 *targs_out = copy_node (DECL_TI_ARGS (fn));
2472 /* Propagate the candidate's constraints to the declaration. */
2473 if (tsk != tsk_template)
2474 set_constraints (decl, get_constraints (fn));
2476 /* DECL is a re-declaration or partial instantiation of a template
2477 function. */
2478 if (TREE_CODE (fn) == TEMPLATE_DECL)
2479 return fn;
2480 /* It was a specialization of an ordinary member function in a
2481 template class. */
2482 return DECL_TI_TEMPLATE (fn);
2485 /* It was a specialization of a template. */
2486 tree tmpl = TREE_VALUE (templates);
2487 *targs_out = add_outermost_template_args (tmpl, TREE_PURPOSE (templates));
2489 /* Propagate the template's constraints to the declaration. */
2490 if (tsk != tsk_template)
2491 set_constraints (decl, get_constraints (tmpl));
2493 return tmpl;
2496 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2497 but with the default argument values filled in from those in the
2498 TMPL_TYPES. */
2500 static tree
2501 copy_default_args_to_explicit_spec_1 (tree spec_types,
2502 tree tmpl_types)
2504 tree new_spec_types;
2506 if (!spec_types)
2507 return NULL_TREE;
2509 if (spec_types == void_list_node)
2510 return void_list_node;
2512 /* Substitute into the rest of the list. */
2513 new_spec_types =
2514 copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2515 TREE_CHAIN (tmpl_types));
2517 /* Add the default argument for this parameter. */
2518 return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2519 TREE_VALUE (spec_types),
2520 new_spec_types);
2523 /* DECL is an explicit specialization. Replicate default arguments
2524 from the template it specializes. (That way, code like:
2526 template <class T> void f(T = 3);
2527 template <> void f(double);
2528 void g () { f (); }
2530 works, as required.) An alternative approach would be to look up
2531 the correct default arguments at the call-site, but this approach
2532 is consistent with how implicit instantiations are handled. */
2534 static void
2535 copy_default_args_to_explicit_spec (tree decl)
2537 tree tmpl;
2538 tree spec_types;
2539 tree tmpl_types;
2540 tree new_spec_types;
2541 tree old_type;
2542 tree new_type;
2543 tree t;
2544 tree object_type = NULL_TREE;
2545 tree in_charge = NULL_TREE;
2546 tree vtt = NULL_TREE;
2548 /* See if there's anything we need to do. */
2549 tmpl = DECL_TI_TEMPLATE (decl);
2550 tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2551 for (t = tmpl_types; t; t = TREE_CHAIN (t))
2552 if (TREE_PURPOSE (t))
2553 break;
2554 if (!t)
2555 return;
2557 old_type = TREE_TYPE (decl);
2558 spec_types = TYPE_ARG_TYPES (old_type);
2560 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2562 /* Remove the this pointer, but remember the object's type for
2563 CV quals. */
2564 object_type = TREE_TYPE (TREE_VALUE (spec_types));
2565 spec_types = TREE_CHAIN (spec_types);
2566 tmpl_types = TREE_CHAIN (tmpl_types);
2568 if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2570 /* DECL may contain more parameters than TMPL due to the extra
2571 in-charge parameter in constructors and destructors. */
2572 in_charge = spec_types;
2573 spec_types = TREE_CHAIN (spec_types);
2575 if (DECL_HAS_VTT_PARM_P (decl))
2577 vtt = spec_types;
2578 spec_types = TREE_CHAIN (spec_types);
2582 /* Compute the merged default arguments. */
2583 new_spec_types =
2584 copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2586 /* Compute the new FUNCTION_TYPE. */
2587 if (object_type)
2589 if (vtt)
2590 new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2591 TREE_VALUE (vtt),
2592 new_spec_types);
2594 if (in_charge)
2595 /* Put the in-charge parameter back. */
2596 new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2597 TREE_VALUE (in_charge),
2598 new_spec_types);
2600 new_type = build_method_type_directly (object_type,
2601 TREE_TYPE (old_type),
2602 new_spec_types);
2604 else
2605 new_type = build_function_type (TREE_TYPE (old_type),
2606 new_spec_types);
2607 new_type = cp_build_type_attribute_variant (new_type,
2608 TYPE_ATTRIBUTES (old_type));
2609 new_type = cxx_copy_lang_qualifiers (new_type, old_type);
2611 TREE_TYPE (decl) = new_type;
2614 /* Return the number of template headers we expect to see for a definition
2615 or specialization of CTYPE or one of its non-template members. */
2618 num_template_headers_for_class (tree ctype)
2620 int num_templates = 0;
2622 while (ctype && CLASS_TYPE_P (ctype))
2624 /* You're supposed to have one `template <...>' for every
2625 template class, but you don't need one for a full
2626 specialization. For example:
2628 template <class T> struct S{};
2629 template <> struct S<int> { void f(); };
2630 void S<int>::f () {}
2632 is correct; there shouldn't be a `template <>' for the
2633 definition of `S<int>::f'. */
2634 if (!CLASSTYPE_TEMPLATE_INFO (ctype))
2635 /* If CTYPE does not have template information of any
2636 kind, then it is not a template, nor is it nested
2637 within a template. */
2638 break;
2639 if (explicit_class_specialization_p (ctype))
2640 break;
2641 if (PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (ctype)))
2642 ++num_templates;
2644 ctype = TYPE_CONTEXT (ctype);
2647 return num_templates;
2650 /* Do a simple sanity check on the template headers that precede the
2651 variable declaration DECL. */
2653 void
2654 check_template_variable (tree decl)
2656 tree ctx = CP_DECL_CONTEXT (decl);
2657 int wanted = num_template_headers_for_class (ctx);
2658 if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)
2659 && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl)))
2661 if (cxx_dialect < cxx14)
2662 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wc__14_extensions,
2663 "variable templates only available with "
2664 "%<-std=c++14%> or %<-std=gnu++14%>");
2666 // Namespace-scope variable templates should have a template header.
2667 ++wanted;
2669 if (template_header_count > wanted)
2671 auto_diagnostic_group d;
2672 bool warned = pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2673 "too many template headers for %qD "
2674 "(should be %d)",
2675 decl, wanted);
2676 if (warned && CLASS_TYPE_P (ctx)
2677 && CLASSTYPE_TEMPLATE_SPECIALIZATION (ctx))
2678 inform (DECL_SOURCE_LOCATION (decl),
2679 "members of an explicitly specialized class are defined "
2680 "without a template header");
2684 /* An explicit specialization whose declarator-id or class-head-name is not
2685 qualified shall be declared in the nearest enclosing namespace of the
2686 template, or, if the namespace is inline (7.3.1), any namespace from its
2687 enclosing namespace set.
2689 If the name declared in the explicit instantiation is an unqualified name,
2690 the explicit instantiation shall appear in the namespace where its template
2691 is declared or, if that namespace is inline (7.3.1), any namespace from its
2692 enclosing namespace set. */
2694 void
2695 check_unqualified_spec_or_inst (tree t, location_t loc)
2697 tree tmpl = most_general_template (t);
2698 if (DECL_NAMESPACE_SCOPE_P (tmpl)
2699 && !is_nested_namespace (current_namespace,
2700 CP_DECL_CONTEXT (tmpl), true))
2702 if (processing_specialization)
2703 permerror (loc, "explicit specialization of %qD outside its "
2704 "namespace must use a nested-name-specifier", tmpl);
2705 else if (processing_explicit_instantiation
2706 && cxx_dialect >= cxx11)
2707 /* This was allowed in C++98, so only pedwarn. */
2708 pedwarn (loc, OPT_Wpedantic, "explicit instantiation of %qD "
2709 "outside its namespace must use a nested-name-"
2710 "specifier", tmpl);
2714 /* Warn for a template specialization SPEC that is missing some of a set
2715 of function or type attributes that the template TEMPL is declared with.
2716 ATTRLIST is a list of additional attributes that SPEC should be taken
2717 to ultimately be declared with. */
2719 static void
2720 warn_spec_missing_attributes (tree tmpl, tree spec, tree attrlist)
2722 if (DECL_FUNCTION_TEMPLATE_P (tmpl))
2723 tmpl = DECL_TEMPLATE_RESULT (tmpl);
2725 /* Avoid warning if the difference between the primary and
2726 the specialization is not in one of the attributes below. */
2727 const char* const blacklist[] = {
2728 "alloc_align", "alloc_size", "assume_aligned", "format",
2729 "format_arg", "malloc", "nonnull", NULL
2732 /* Put together a list of the black listed attributes that the primary
2733 template is declared with that the specialization is not, in case
2734 it's not apparent from the most recent declaration of the primary. */
2735 pretty_printer str;
2736 unsigned nattrs = decls_mismatched_attributes (tmpl, spec, attrlist,
2737 blacklist, &str);
2739 if (!nattrs)
2740 return;
2742 auto_diagnostic_group d;
2743 if (warning_at (DECL_SOURCE_LOCATION (spec), OPT_Wmissing_attributes,
2744 "explicit specialization %q#D may be missing attributes",
2745 spec))
2746 inform (DECL_SOURCE_LOCATION (tmpl),
2747 nattrs > 1
2748 ? G_("missing primary template attributes %s")
2749 : G_("missing primary template attribute %s"),
2750 pp_formatted_text (&str));
2753 /* Check to see if the function just declared, as indicated in
2754 DECLARATOR, and in DECL, is a specialization of a function
2755 template. We may also discover that the declaration is an explicit
2756 instantiation at this point.
2758 Returns DECL, or an equivalent declaration that should be used
2759 instead if all goes well. Issues an error message if something is
2760 amiss. Returns error_mark_node if the error is not easily
2761 recoverable.
2763 FLAGS is a bitmask consisting of the following flags:
2765 2: The function has a definition.
2766 4: The function is a friend.
2768 The TEMPLATE_COUNT is the number of references to qualifying
2769 template classes that appeared in the name of the function. For
2770 example, in
2772 template <class T> struct S { void f(); };
2773 void S<int>::f();
2775 the TEMPLATE_COUNT would be 1. However, explicitly specialized
2776 classes are not counted in the TEMPLATE_COUNT, so that in
2778 template <class T> struct S {};
2779 template <> struct S<int> { void f(); }
2780 template <> void S<int>::f();
2782 the TEMPLATE_COUNT would be 0. (Note that this declaration is
2783 invalid; there should be no template <>.)
2785 If the function is a specialization, it is marked as such via
2786 DECL_TEMPLATE_SPECIALIZATION. Furthermore, its DECL_TEMPLATE_INFO
2787 is set up correctly, and it is added to the list of specializations
2788 for that template. */
2790 tree
2791 check_explicit_specialization (tree declarator,
2792 tree decl,
2793 int template_count,
2794 int flags,
2795 tree attrlist)
2797 int have_def = flags & 2;
2798 int is_friend = flags & 4;
2799 bool is_concept = flags & 8;
2800 int specialization = 0;
2801 int explicit_instantiation = 0;
2802 int member_specialization = 0;
2803 tree ctype = DECL_CLASS_CONTEXT (decl);
2804 tree dname = DECL_NAME (decl);
2805 tmpl_spec_kind tsk;
2807 if (is_friend)
2809 if (!processing_specialization)
2810 tsk = tsk_none;
2811 else
2812 tsk = tsk_excessive_parms;
2814 else
2815 tsk = current_tmpl_spec_kind (template_count);
2817 switch (tsk)
2819 case tsk_none:
2820 if (processing_specialization && !VAR_P (decl))
2822 specialization = 1;
2823 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2825 else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR
2826 || (DECL_LANG_SPECIFIC (decl)
2827 && DECL_IMPLICIT_INSTANTIATION (decl)))
2829 if (is_friend)
2830 /* This could be something like:
2832 template <class T> void f(T);
2833 class S { friend void f<>(int); } */
2834 specialization = 1;
2835 else
2837 /* This case handles bogus declarations like template <>
2838 template <class T> void f<int>(); */
2840 error_at (cp_expr_loc_or_input_loc (declarator),
2841 "template-id %qE in declaration of primary template",
2842 declarator);
2843 return decl;
2846 break;
2848 case tsk_invalid_member_spec:
2849 /* The error has already been reported in
2850 check_specialization_scope. */
2851 return error_mark_node;
2853 case tsk_invalid_expl_inst:
2854 error ("template parameter list used in explicit instantiation");
2856 /* Fall through. */
2858 case tsk_expl_inst:
2859 if (have_def)
2860 error ("definition provided for explicit instantiation");
2862 explicit_instantiation = 1;
2863 break;
2865 case tsk_excessive_parms:
2866 case tsk_insufficient_parms:
2867 if (tsk == tsk_excessive_parms)
2868 error ("too many template parameter lists in declaration of %qD",
2869 decl);
2870 else if (template_header_count)
2871 error("too few template parameter lists in declaration of %qD", decl);
2872 else
2873 error("explicit specialization of %qD must be introduced by "
2874 "%<template <>%>", decl);
2876 /* Fall through. */
2877 case tsk_expl_spec:
2878 if (is_concept)
2879 error ("explicit specialization declared %<concept%>");
2881 if (VAR_P (decl) && TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2882 /* In cases like template<> constexpr bool v = true;
2883 We'll give an error in check_template_variable. */
2884 break;
2886 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2887 if (ctype)
2888 member_specialization = 1;
2889 else
2890 specialization = 1;
2891 break;
2893 case tsk_template:
2894 if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2896 /* This case handles bogus declarations like template <>
2897 template <class T> void f<int>(); */
2899 if (!uses_template_parms (TREE_OPERAND (declarator, 1)))
2900 error_at (cp_expr_loc_or_input_loc (declarator),
2901 "template-id %qE in declaration of primary template",
2902 declarator);
2903 else if (variable_template_p (TREE_OPERAND (declarator, 0)))
2905 /* Partial specialization of variable template. */
2906 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2907 specialization = 1;
2908 goto ok;
2910 else if (cxx_dialect < cxx14)
2911 error_at (cp_expr_loc_or_input_loc (declarator),
2912 "non-type partial specialization %qE "
2913 "is not allowed", declarator);
2914 else
2915 error_at (cp_expr_loc_or_input_loc (declarator),
2916 "non-class, non-variable partial specialization %qE "
2917 "is not allowed", declarator);
2918 return decl;
2919 ok:;
2922 if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2923 /* This is a specialization of a member template, without
2924 specialization the containing class. Something like:
2926 template <class T> struct S {
2927 template <class U> void f (U);
2929 template <> template <class U> void S<int>::f(U) {}
2931 That's a specialization -- but of the entire template. */
2932 specialization = 1;
2933 break;
2935 default:
2936 gcc_unreachable ();
2939 if ((specialization || member_specialization)
2940 /* This doesn't apply to variable templates. */
2941 && FUNC_OR_METHOD_TYPE_P (TREE_TYPE (decl)))
2943 tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2944 for (; t; t = TREE_CHAIN (t))
2945 if (TREE_PURPOSE (t))
2947 permerror (input_location,
2948 "default argument specified in explicit specialization");
2949 break;
2953 if (specialization || member_specialization || explicit_instantiation)
2955 tree tmpl = NULL_TREE;
2956 tree targs = NULL_TREE;
2957 bool was_template_id = (TREE_CODE (declarator) == TEMPLATE_ID_EXPR);
2958 bool found_hidden = false;
2960 /* Make sure that the declarator is a TEMPLATE_ID_EXPR. */
2961 if (!was_template_id)
2963 tree fns;
2965 gcc_assert (identifier_p (declarator));
2966 if (ctype)
2967 fns = dname;
2968 else
2970 /* If there is no class context, the explicit instantiation
2971 must be at namespace scope. */
2972 gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2974 /* Find the namespace binding, using the declaration
2975 context. */
2976 fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2977 LOOK_want::NORMAL, true);
2978 if (fns == error_mark_node)
2980 /* If lookup fails, look for a friend declaration so we can
2981 give a better diagnostic. */
2982 fns = (lookup_qualified_name
2983 (CP_DECL_CONTEXT (decl), dname,
2984 LOOK_want::NORMAL | LOOK_want::HIDDEN_FRIEND,
2985 /*complain*/true));
2986 found_hidden = true;
2989 if (fns == error_mark_node || !is_overloaded_fn (fns))
2991 error ("%qD is not a template function", dname);
2992 fns = error_mark_node;
2996 declarator = lookup_template_function (fns, NULL_TREE);
2999 if (declarator == error_mark_node)
3000 return error_mark_node;
3002 if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
3004 if (!explicit_instantiation)
3005 /* A specialization in class scope. This is invalid,
3006 but the error will already have been flagged by
3007 check_specialization_scope. */
3008 return error_mark_node;
3009 else
3011 /* It's not valid to write an explicit instantiation in
3012 class scope, e.g.:
3014 class C { template void f(); }
3016 This case is caught by the parser. However, on
3017 something like:
3019 template class C { void f(); };
3021 (which is invalid) we can get here. The error will be
3022 issued later. */
3026 return decl;
3028 else if (ctype != NULL_TREE
3029 && (identifier_p (TREE_OPERAND (declarator, 0))))
3031 // We'll match variable templates in start_decl.
3032 if (VAR_P (decl))
3033 return decl;
3035 /* Find the list of functions in ctype that have the same
3036 name as the declared function. */
3037 tree name = TREE_OPERAND (declarator, 0);
3039 if (constructor_name_p (name, ctype))
3041 if (DECL_CONSTRUCTOR_P (decl)
3042 ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
3043 : !CLASSTYPE_DESTRUCTOR (ctype))
3045 /* From [temp.expl.spec]:
3047 If such an explicit specialization for the member
3048 of a class template names an implicitly-declared
3049 special member function (clause _special_), the
3050 program is ill-formed.
3052 Similar language is found in [temp.explicit]. */
3053 error ("specialization of implicitly-declared special member function");
3054 return error_mark_node;
3057 name = DECL_NAME (decl);
3060 /* For a type-conversion operator, We might be looking for
3061 `operator int' which will be a specialization of
3062 `operator T'. Grab all the conversion operators, and
3063 then select from them. */
3064 tree fns = get_class_binding (ctype, IDENTIFIER_CONV_OP_P (name)
3065 ? conv_op_identifier : name);
3067 if (fns == NULL_TREE)
3069 error ("no member function %qD declared in %qT", name, ctype);
3070 return error_mark_node;
3072 else
3073 TREE_OPERAND (declarator, 0) = fns;
3076 /* Figure out what exactly is being specialized at this point.
3077 Note that for an explicit instantiation, even one for a
3078 member function, we cannot tell a priori whether the
3079 instantiation is for a member template, or just a member
3080 function of a template class. Even if a member template is
3081 being instantiated, the member template arguments may be
3082 elided if they can be deduced from the rest of the
3083 declaration. */
3084 tmpl = determine_specialization (declarator, decl,
3085 &targs,
3086 member_specialization,
3087 template_count,
3088 tsk);
3090 if (!tmpl || tmpl == error_mark_node)
3091 /* We couldn't figure out what this declaration was
3092 specializing. */
3093 return error_mark_node;
3094 else
3096 if (found_hidden && TREE_CODE (decl) == FUNCTION_DECL)
3098 auto_diagnostic_group d;
3099 if (pedwarn (DECL_SOURCE_LOCATION (decl), 0,
3100 "friend declaration %qD is not visible to "
3101 "explicit specialization", tmpl))
3102 inform (DECL_SOURCE_LOCATION (tmpl),
3103 "friend declaration here");
3106 if (!ctype && !is_friend
3107 && CP_DECL_CONTEXT (decl) == current_namespace)
3108 check_unqualified_spec_or_inst (tmpl, DECL_SOURCE_LOCATION (decl));
3110 tree gen_tmpl = most_general_template (tmpl);
3112 if (explicit_instantiation)
3114 /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
3115 is done by do_decl_instantiation later. */
3117 int arg_depth = TMPL_ARGS_DEPTH (targs);
3118 int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
3120 if (arg_depth > parm_depth)
3122 /* If TMPL is not the most general template (for
3123 example, if TMPL is a friend template that is
3124 injected into namespace scope), then there will
3125 be too many levels of TARGS. Remove some of them
3126 here. */
3127 int i;
3128 tree new_targs;
3130 new_targs = make_tree_vec (parm_depth);
3131 for (i = arg_depth - parm_depth; i < arg_depth; ++i)
3132 TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
3133 = TREE_VEC_ELT (targs, i);
3134 targs = new_targs;
3137 return instantiate_template (tmpl, targs, tf_error);
3140 /* If we thought that the DECL was a member function, but it
3141 turns out to be specializing a static member function,
3142 make DECL a static member function as well. */
3143 if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3144 && DECL_STATIC_FUNCTION_P (tmpl)
3145 && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
3146 revert_static_member_fn (decl);
3148 /* If this is a specialization of a member template of a
3149 template class, we want to return the TEMPLATE_DECL, not
3150 the specialization of it. */
3151 if (tsk == tsk_template && !was_template_id)
3153 tree result = DECL_TEMPLATE_RESULT (tmpl);
3154 SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3155 DECL_INITIAL (result) = NULL_TREE;
3156 if (have_def)
3158 tree parm;
3159 DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
3160 DECL_SOURCE_LOCATION (result)
3161 = DECL_SOURCE_LOCATION (decl);
3162 /* We want to use the argument list specified in the
3163 definition, not in the original declaration. */
3164 DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
3165 for (parm = DECL_ARGUMENTS (result); parm;
3166 parm = DECL_CHAIN (parm))
3167 DECL_CONTEXT (parm) = result;
3169 decl = register_specialization (tmpl, gen_tmpl, targs,
3170 is_friend, 0);
3171 remove_contract_attributes (result);
3172 return decl;
3175 /* Set up the DECL_TEMPLATE_INFO for DECL. */
3176 DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
3178 if (was_template_id)
3179 TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl)) = true;
3181 /* Inherit default function arguments from the template
3182 DECL is specializing. */
3183 if (DECL_FUNCTION_TEMPLATE_P (tmpl))
3184 copy_default_args_to_explicit_spec (decl);
3186 /* This specialization has the same protection as the
3187 template it specializes. */
3188 TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
3189 TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
3191 /* 7.1.1-1 [dcl.stc]
3193 A storage-class-specifier shall not be specified in an
3194 explicit specialization...
3196 The parser rejects these, so unless action is taken here,
3197 explicit function specializations will always appear with
3198 global linkage.
3200 The action recommended by the C++ CWG in response to C++
3201 defect report 605 is to make the storage class and linkage
3202 of the explicit specialization match the templated function:
3204 http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
3206 if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
3208 tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
3209 gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
3211 /* A concept cannot be specialized. */
3212 if (DECL_DECLARED_CONCEPT_P (tmpl_func))
3214 error ("explicit specialization of function concept %qD",
3215 gen_tmpl);
3216 return error_mark_node;
3219 /* This specialization has the same linkage and visibility as
3220 the function template it specializes. */
3221 TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
3222 if (! TREE_PUBLIC (decl))
3224 DECL_INTERFACE_KNOWN (decl) = 1;
3225 DECL_NOT_REALLY_EXTERN (decl) = 1;
3227 DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
3228 if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
3230 DECL_VISIBILITY_SPECIFIED (decl) = 1;
3231 DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
3235 /* If DECL is a friend declaration, declared using an
3236 unqualified name, the namespace associated with DECL may
3237 have been set incorrectly. For example, in:
3239 template <typename T> void f(T);
3240 namespace N {
3241 struct S { friend void f<int>(int); }
3244 we will have set the DECL_CONTEXT for the friend
3245 declaration to N, rather than to the global namespace. */
3246 if (DECL_NAMESPACE_SCOPE_P (decl))
3247 DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
3249 if (is_friend && !have_def)
3250 /* This is not really a declaration of a specialization.
3251 It's just the name of an instantiation. But, it's not
3252 a request for an instantiation, either. */
3253 SET_DECL_IMPLICIT_INSTANTIATION (decl);
3254 else if (TREE_CODE (decl) == FUNCTION_DECL)
3255 /* A specialization is not necessarily COMDAT. */
3256 DECL_COMDAT (decl) = (TREE_PUBLIC (decl)
3257 && DECL_DECLARED_INLINE_P (decl));
3258 else if (VAR_P (decl))
3259 DECL_COMDAT (decl) = false;
3261 /* If this is a full specialization, register it so that we can find
3262 it again. Partial specializations will be registered in
3263 process_partial_specialization. */
3264 if (!processing_template_decl)
3266 warn_spec_missing_attributes (gen_tmpl, decl, attrlist);
3268 decl = register_specialization (decl, gen_tmpl, targs,
3269 is_friend, 0);
3272 /* If this is a specialization, splice any contracts that may have
3273 been inherited from the template, removing them. */
3274 if (decl != error_mark_node && DECL_TEMPLATE_SPECIALIZATION (decl))
3275 remove_contract_attributes (decl);
3277 /* A 'structor should already have clones. */
3278 gcc_assert (decl == error_mark_node
3279 || variable_template_p (tmpl)
3280 || !(DECL_CONSTRUCTOR_P (decl)
3281 || DECL_DESTRUCTOR_P (decl))
3282 || DECL_CLONED_FUNCTION_P (DECL_CHAIN (decl)));
3286 return decl;
3289 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
3290 parameters. These are represented in the same format used for
3291 DECL_TEMPLATE_PARMS. */
3294 comp_template_parms (const_tree parms1, const_tree parms2)
3296 const_tree p1;
3297 const_tree p2;
3299 if (parms1 == parms2)
3300 return 1;
3302 for (p1 = parms1, p2 = parms2;
3303 p1 != NULL_TREE && p2 != NULL_TREE;
3304 p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
3306 tree t1 = TREE_VALUE (p1);
3307 tree t2 = TREE_VALUE (p2);
3308 int i;
3310 gcc_assert (TREE_CODE (t1) == TREE_VEC);
3311 gcc_assert (TREE_CODE (t2) == TREE_VEC);
3313 if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
3314 return 0;
3316 for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
3318 tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
3319 tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
3321 /* If either of the template parameters are invalid, assume
3322 they match for the sake of error recovery. */
3323 if (error_operand_p (parm1) || error_operand_p (parm2))
3324 return 1;
3326 if (TREE_CODE (parm1) != TREE_CODE (parm2))
3327 return 0;
3329 if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
3330 && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
3331 == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
3332 continue;
3333 else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
3334 return 0;
3338 if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
3339 /* One set of parameters has more parameters lists than the
3340 other. */
3341 return 0;
3343 return 1;
3346 /* Returns true if two template parameters are declared with
3347 equivalent constraints. */
3349 static bool
3350 template_parameter_constraints_equivalent_p (const_tree parm1, const_tree parm2)
3352 tree req1 = TREE_TYPE (parm1);
3353 tree req2 = TREE_TYPE (parm2);
3354 if (!req1 != !req2)
3355 return false;
3356 if (req1)
3357 return cp_tree_equal (req1, req2);
3358 return true;
3361 /* Returns true when two template parameters are equivalent. */
3363 static bool
3364 template_parameters_equivalent_p (const_tree parm1, const_tree parm2)
3366 tree decl1 = TREE_VALUE (parm1);
3367 tree decl2 = TREE_VALUE (parm2);
3369 /* If either of the template parameters are invalid, assume
3370 they match for the sake of error recovery. */
3371 if (error_operand_p (decl1) || error_operand_p (decl2))
3372 return true;
3374 /* ... they declare parameters of the same kind. */
3375 if (TREE_CODE (decl1) != TREE_CODE (decl2))
3376 return false;
3378 /* ... one parameter was introduced by a parameter declaration, then
3379 both are. This case arises as a result of eagerly rewriting declarations
3380 during parsing. */
3381 if (DECL_VIRTUAL_P (decl1) != DECL_VIRTUAL_P (decl2))
3382 return false;
3384 /* ... if either declares a pack, they both do. */
3385 if (template_parameter_pack_p (decl1) != template_parameter_pack_p (decl2))
3386 return false;
3388 if (TREE_CODE (decl1) == PARM_DECL)
3390 /* ... if they declare non-type parameters, the types are equivalent. */
3391 if (!same_type_p (TREE_TYPE (decl1), TREE_TYPE (decl2)))
3392 return false;
3394 else if (TREE_CODE (decl2) == TEMPLATE_DECL)
3396 /* ... if they declare template template parameters, their template
3397 parameter lists are equivalent. */
3398 if (!template_heads_equivalent_p (decl1, decl2))
3399 return false;
3402 /* ... if they are declared with a qualified-concept name, they both
3403 are, and those names are equivalent. */
3404 return template_parameter_constraints_equivalent_p (parm1, parm2);
3407 /* Returns true if two template parameters lists are equivalent.
3408 Two template parameter lists are equivalent if they have the
3409 same length and their corresponding parameters are equivalent.
3411 PARMS1 and PARMS2 are TREE_LISTs containing TREE_VECs: the
3412 data structure returned by DECL_TEMPLATE_PARMS.
3414 This is generally the same implementation as comp_template_parms
3415 except that it also the concept names and arguments used to
3416 introduce parameters. */
3418 static bool
3419 template_parameter_lists_equivalent_p (const_tree parms1, const_tree parms2)
3421 if (parms1 == parms2)
3422 return true;
3424 const_tree p1 = parms1;
3425 const_tree p2 = parms2;
3426 while (p1 != NULL_TREE && p2 != NULL_TREE)
3428 tree list1 = TREE_VALUE (p1);
3429 tree list2 = TREE_VALUE (p2);
3431 if (TREE_VEC_LENGTH (list1) != TREE_VEC_LENGTH (list2))
3432 return 0;
3434 for (int i = 0; i < TREE_VEC_LENGTH (list2); ++i)
3436 tree parm1 = TREE_VEC_ELT (list1, i);
3437 tree parm2 = TREE_VEC_ELT (list2, i);
3438 if (!template_parameters_equivalent_p (parm1, parm2))
3439 return false;
3442 p1 = TREE_CHAIN (p1);
3443 p2 = TREE_CHAIN (p2);
3446 if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
3447 return false;
3449 return true;
3452 /* Return true if the requires-clause of the template parameter lists are
3453 equivalent and false otherwise. */
3454 static bool
3455 template_requirements_equivalent_p (const_tree parms1, const_tree parms2)
3457 tree req1 = TEMPLATE_PARMS_CONSTRAINTS (parms1);
3458 tree req2 = TEMPLATE_PARMS_CONSTRAINTS (parms2);
3459 if ((req1 != NULL_TREE) != (req2 != NULL_TREE))
3460 return false;
3461 if (!cp_tree_equal (req1, req2))
3462 return false;
3463 return true;
3466 /* Returns true if two template heads are equivalent. 17.6.6.1p6:
3467 Two template heads are equivalent if their template parameter
3468 lists are equivalent and their requires clauses are equivalent.
3470 In pre-C++20, this is equivalent to calling comp_template_parms
3471 for the template parameters of TMPL1 and TMPL2. */
3473 bool
3474 template_heads_equivalent_p (const_tree tmpl1, const_tree tmpl2)
3476 tree parms1 = DECL_TEMPLATE_PARMS (tmpl1);
3477 tree parms2 = DECL_TEMPLATE_PARMS (tmpl2);
3479 /* Don't change the matching rules for pre-C++20. */
3480 if (cxx_dialect < cxx20)
3481 return comp_template_parms (parms1, parms2);
3483 /* ... have the same number of template parameters, and their
3484 corresponding parameters are equivalent. */
3485 if (!template_parameter_lists_equivalent_p (parms1, parms2))
3486 return false;
3488 /* ... if either has a requires-clause, they both do and their
3489 corresponding constraint-expressions are equivalent. */
3490 return template_requirements_equivalent_p (parms1, parms2);
3493 /* Determine whether PARM is a parameter pack. */
3495 bool
3496 template_parameter_pack_p (const_tree parm)
3498 /* Determine if we have a non-type template parameter pack. */
3499 if (TREE_CODE (parm) == PARM_DECL)
3500 return (DECL_TEMPLATE_PARM_P (parm)
3501 && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
3502 if (TREE_CODE (parm) == TEMPLATE_PARM_INDEX)
3503 return TEMPLATE_PARM_PARAMETER_PACK (parm);
3505 /* If this is a list of template parameters, we could get a
3506 TYPE_DECL or a TEMPLATE_DECL. */
3507 if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
3508 parm = TREE_TYPE (parm);
3510 /* Otherwise it must be a type template parameter. */
3511 return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
3512 || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
3513 && TEMPLATE_TYPE_PARAMETER_PACK (parm));
3516 /* Determine if T is a function parameter pack. */
3518 bool
3519 function_parameter_pack_p (const_tree t)
3521 if (t && TREE_CODE (t) == PARM_DECL)
3522 return DECL_PACK_P (t);
3523 return false;
3526 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
3527 PRIMARY_FUNC_TMPL_INST is a primary function template instantiation. */
3529 tree
3530 get_function_template_decl (const_tree primary_func_tmpl_inst)
3532 if (! primary_func_tmpl_inst
3533 || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
3534 || ! primary_template_specialization_p (primary_func_tmpl_inst))
3535 return NULL;
3537 return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
3540 /* Return true iff the function parameter PARAM_DECL was expanded
3541 from the function parameter pack PACK. */
3543 bool
3544 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
3546 if (DECL_ARTIFICIAL (param_decl)
3547 || !function_parameter_pack_p (pack))
3548 return false;
3550 /* The parameter pack and its pack arguments have the same
3551 DECL_PARM_INDEX. */
3552 return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
3555 /* Determine whether ARGS describes a variadic template args list,
3556 i.e., one that is terminated by a template argument pack. */
3558 static bool
3559 template_args_variadic_p (tree args)
3561 int nargs;
3562 tree last_parm;
3564 if (args == NULL_TREE)
3565 return false;
3567 args = INNERMOST_TEMPLATE_ARGS (args);
3568 nargs = TREE_VEC_LENGTH (args);
3570 if (nargs == 0)
3571 return false;
3573 last_parm = TREE_VEC_ELT (args, nargs - 1);
3575 return ARGUMENT_PACK_P (last_parm);
3578 /* Generate a new name for the parameter pack name NAME (an
3579 IDENTIFIER_NODE) that incorporates its */
3581 static tree
3582 make_ith_pack_parameter_name (tree name, int i)
3584 /* Munge the name to include the parameter index. */
3585 #define NUMBUF_LEN 128
3586 char numbuf[NUMBUF_LEN];
3587 char* newname;
3588 int newname_len;
3590 if (name == NULL_TREE)
3591 return name;
3592 snprintf (numbuf, NUMBUF_LEN, "%i", i);
3593 newname_len = IDENTIFIER_LENGTH (name)
3594 + strlen (numbuf) + 2;
3595 newname = (char*)alloca (newname_len);
3596 snprintf (newname, newname_len,
3597 "%s#%i", IDENTIFIER_POINTER (name), i);
3598 return get_identifier (newname);
3601 /* Return true if T is a primary function, class or alias template
3602 specialization, not including the template pattern. */
3604 bool
3605 primary_template_specialization_p (const_tree t)
3607 if (!t)
3608 return false;
3610 if (VAR_OR_FUNCTION_DECL_P (t))
3611 return (DECL_LANG_SPECIFIC (t)
3612 && DECL_USE_TEMPLATE (t)
3613 && DECL_TEMPLATE_INFO (t)
3614 && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t)));
3615 else if (CLASS_TYPE_P (t) && !TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
3616 return (CLASSTYPE_TEMPLATE_INFO (t)
3617 && CLASSTYPE_USE_TEMPLATE (t)
3618 && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)));
3619 else if (alias_template_specialization_p (t, nt_transparent))
3620 return true;
3621 return false;
3624 /* Return true if PARM is a template template parameter. */
3626 bool
3627 template_template_parameter_p (const_tree parm)
3629 return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
3632 /* Return true iff PARM is a DECL representing a type template
3633 parameter. */
3635 bool
3636 template_type_parameter_p (const_tree parm)
3638 return (parm
3639 && (TREE_CODE (parm) == TYPE_DECL
3640 || TREE_CODE (parm) == TEMPLATE_DECL)
3641 && DECL_TEMPLATE_PARM_P (parm));
3644 /* Return the template parameters of T if T is a
3645 primary template instantiation, NULL otherwise. */
3647 tree
3648 get_primary_template_innermost_parameters (const_tree t)
3650 tree parms = NULL, template_info = NULL;
3652 if ((template_info = get_template_info (t))
3653 && primary_template_specialization_p (t))
3654 parms = INNERMOST_TEMPLATE_PARMS
3655 (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
3657 return parms;
3660 /* Returns the template arguments of T if T is a template instantiation,
3661 NULL otherwise. */
3663 tree
3664 get_template_innermost_arguments (const_tree t)
3666 tree args = NULL, template_info = NULL;
3668 if ((template_info = get_template_info (t))
3669 && TI_ARGS (template_info))
3670 args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
3672 return args;
3675 /* Return the argument pack elements of T if T is a template argument pack,
3676 NULL otherwise. */
3678 tree
3679 get_template_argument_pack_elems (const_tree t)
3681 if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
3682 && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
3683 return NULL;
3685 return ARGUMENT_PACK_ARGS (t);
3688 /* In an ARGUMENT_PACK_SELECT, the actual underlying argument that the
3689 ARGUMENT_PACK_SELECT represents. */
3691 static tree
3692 argument_pack_select_arg (tree t)
3694 tree args = ARGUMENT_PACK_ARGS (ARGUMENT_PACK_SELECT_FROM_PACK (t));
3695 tree arg = TREE_VEC_ELT (args, ARGUMENT_PACK_SELECT_INDEX (t));
3697 /* If the selected argument is an expansion E, that most likely means we were
3698 called from gen_elem_of_pack_expansion_instantiation during the
3699 substituting of an argument pack (of which the Ith element is a pack
3700 expansion, where I is ARGUMENT_PACK_SELECT_INDEX) into a pack expansion.
3701 In this case, the Ith element resulting from this substituting is going to
3702 be a pack expansion, which pattern is the pattern of E. Let's return the
3703 pattern of E, and gen_elem_of_pack_expansion_instantiation will build the
3704 resulting pack expansion from it. */
3705 if (PACK_EXPANSION_P (arg))
3707 /* Make sure we aren't throwing away arg info. */
3708 gcc_assert (!PACK_EXPANSION_EXTRA_ARGS (arg));
3709 arg = PACK_EXPANSION_PATTERN (arg);
3712 return arg;
3715 /* Return a modification of ARGS that's suitable for preserving inside a hash
3716 table. In particular, this replaces each ARGUMENT_PACK_SELECT with its
3717 underlying argument. ARGS is copied (upon modification) iff COW_P. */
3719 static tree
3720 preserve_args (tree args, bool cow_p = true)
3722 if (!args)
3723 return NULL_TREE;
3725 for (int i = 0, len = TREE_VEC_LENGTH (args); i < len; ++i)
3727 tree t = TREE_VEC_ELT (args, i);
3728 tree r;
3729 if (!t)
3730 r = NULL_TREE;
3731 else if (TREE_CODE (t) == ARGUMENT_PACK_SELECT)
3732 r = argument_pack_select_arg (t);
3733 else if (TREE_CODE (t) == TREE_VEC)
3734 r = preserve_args (t, cow_p);
3735 else
3736 r = t;
3737 if (r != t)
3739 if (cow_p)
3741 args = copy_template_args (args);
3742 cow_p = false;
3744 TREE_VEC_ELT (args, i) = r;
3748 return args;
3751 /* True iff FN is a function representing a built-in variadic parameter
3752 pack. */
3754 bool
3755 builtin_pack_fn_p (tree fn)
3757 if (!fn
3758 || TREE_CODE (fn) != FUNCTION_DECL
3759 || !DECL_IS_UNDECLARED_BUILTIN (fn))
3760 return false;
3762 if (id_equal (DECL_NAME (fn), "__integer_pack"))
3763 return true;
3765 return false;
3768 /* True iff CALL is a call to a function representing a built-in variadic
3769 parameter pack. */
3771 static bool
3772 builtin_pack_call_p (tree call)
3774 if (TREE_CODE (call) != CALL_EXPR)
3775 return false;
3776 return builtin_pack_fn_p (CALL_EXPR_FN (call));
3779 /* Return a TREE_VEC for the expansion of __integer_pack(HI). */
3781 static tree
3782 expand_integer_pack (tree call, tree args, tsubst_flags_t complain,
3783 tree in_decl)
3785 tree ohi = CALL_EXPR_ARG (call, 0);
3786 tree hi = tsubst_copy_and_build (ohi, args, complain, in_decl);
3788 if (instantiation_dependent_expression_p (hi))
3790 if (hi != ohi)
3792 call = copy_node (call);
3793 CALL_EXPR_ARG (call, 0) = hi;
3795 tree ex = make_pack_expansion (call, complain);
3796 tree vec = make_tree_vec (1);
3797 TREE_VEC_ELT (vec, 0) = ex;
3798 return vec;
3800 else
3802 hi = instantiate_non_dependent_expr (hi, complain);
3803 hi = cxx_constant_value (hi, complain);
3804 int len = valid_constant_size_p (hi) ? tree_to_shwi (hi) : -1;
3806 /* Calculate the largest value of len that won't make the size of the vec
3807 overflow an int. The compiler will exceed resource limits long before
3808 this, but it seems a decent place to diagnose. */
3809 int max = ((INT_MAX - sizeof (tree_vec)) / sizeof (tree)) + 1;
3811 if (len < 0 || len > max)
3813 if ((complain & tf_error)
3814 && hi != error_mark_node)
3815 error ("argument to %<__integer_pack%> must be between 0 and %d",
3816 max);
3817 return error_mark_node;
3820 tree vec = make_tree_vec (len);
3822 for (int i = 0; i < len; ++i)
3823 TREE_VEC_ELT (vec, i) = size_int (i);
3825 return vec;
3829 /* Return a TREE_VEC for the expansion of built-in template parameter pack
3830 CALL. */
3832 static tree
3833 expand_builtin_pack_call (tree call, tree args, tsubst_flags_t complain,
3834 tree in_decl)
3836 if (!builtin_pack_call_p (call))
3837 return NULL_TREE;
3839 tree fn = CALL_EXPR_FN (call);
3841 if (id_equal (DECL_NAME (fn), "__integer_pack"))
3842 return expand_integer_pack (call, args, complain, in_decl);
3844 return NULL_TREE;
3847 /* Return true if the tree T has the extra args mechanism for
3848 avoiding partial instantiation. */
3850 static bool
3851 has_extra_args_mechanism_p (const_tree t)
3853 return (PACK_EXPANSION_P (t) /* PACK_EXPANSION_EXTRA_ARGS */
3854 || TREE_CODE (t) == REQUIRES_EXPR /* REQUIRES_EXPR_EXTRA_ARGS */
3855 || (TREE_CODE (t) == IF_STMT
3856 && IF_STMT_CONSTEXPR_P (t))); /* IF_STMT_EXTRA_ARGS */
3859 /* Structure used to track the progress of find_parameter_packs_r. */
3860 struct find_parameter_pack_data
3862 /* TREE_LIST that will contain all of the parameter packs found by
3863 the traversal. */
3864 tree* parameter_packs;
3866 /* Set of AST nodes that have been visited by the traversal. */
3867 hash_set<tree> *visited;
3869 /* True iff we're making a type pack expansion. */
3870 bool type_pack_expansion_p;
3872 /* True iff we found a subtree that has the extra args mechanism. */
3873 bool found_extra_args_tree_p = false;
3876 /* Identifies all of the argument packs that occur in a template
3877 argument and appends them to the TREE_LIST inside DATA, which is a
3878 find_parameter_pack_data structure. This is a subroutine of
3879 make_pack_expansion and uses_parameter_packs. */
3880 static tree
3881 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
3883 tree t = *tp;
3884 struct find_parameter_pack_data* ppd =
3885 (struct find_parameter_pack_data*)data;
3886 bool parameter_pack_p = false;
3888 #define WALK_SUBTREE(NODE) \
3889 cp_walk_tree (&(NODE), &find_parameter_packs_r, \
3890 ppd, ppd->visited) \
3892 /* Don't look through typedefs; we are interested in whether a
3893 parameter pack is actually written in the expression/type we're
3894 looking at, not the target type. */
3895 if (TYPE_P (t) && typedef_variant_p (t))
3897 /* But do look at arguments for an alias template. */
3898 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
3899 cp_walk_tree (&TI_ARGS (tinfo),
3900 &find_parameter_packs_r,
3901 ppd, ppd->visited);
3902 *walk_subtrees = 0;
3903 return NULL_TREE;
3906 /* Identify whether this is a parameter pack or not. */
3907 switch (TREE_CODE (t))
3909 case TEMPLATE_PARM_INDEX:
3910 if (TEMPLATE_PARM_PARAMETER_PACK (t))
3911 parameter_pack_p = true;
3912 break;
3914 case TEMPLATE_TYPE_PARM:
3915 t = TYPE_MAIN_VARIANT (t);
3916 /* FALLTHRU */
3917 case TEMPLATE_TEMPLATE_PARM:
3918 /* If the placeholder appears in the decl-specifier-seq of a function
3919 parameter pack (14.6.3), or the type-specifier-seq of a type-id that
3920 is a pack expansion, the invented template parameter is a template
3921 parameter pack. */
3922 if (ppd->type_pack_expansion_p && is_auto (t))
3923 TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
3924 if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3925 parameter_pack_p = true;
3926 break;
3928 case FIELD_DECL:
3929 case PARM_DECL:
3930 if (DECL_PACK_P (t))
3932 /* We don't want to walk into the type of a PARM_DECL,
3933 because we don't want to see the type parameter pack. */
3934 *walk_subtrees = 0;
3935 parameter_pack_p = true;
3937 break;
3939 case VAR_DECL:
3940 if (DECL_PACK_P (t))
3942 /* We don't want to walk into the type of a variadic capture proxy,
3943 because we don't want to see the type parameter pack. */
3944 *walk_subtrees = 0;
3945 parameter_pack_p = true;
3947 else if (variable_template_specialization_p (t))
3949 cp_walk_tree (&DECL_TI_ARGS (t),
3950 find_parameter_packs_r,
3951 ppd, ppd->visited);
3952 *walk_subtrees = 0;
3954 break;
3956 case CALL_EXPR:
3957 if (builtin_pack_call_p (t))
3958 parameter_pack_p = true;
3959 break;
3961 case BASES:
3962 parameter_pack_p = true;
3963 break;
3964 default:
3965 /* Not a parameter pack. */
3966 break;
3969 if (parameter_pack_p)
3971 /* Add this parameter pack to the list. */
3972 *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
3975 if (has_extra_args_mechanism_p (t) && !PACK_EXPANSION_P (t))
3976 ppd->found_extra_args_tree_p = true;
3978 if (TYPE_P (t))
3979 cp_walk_tree (&TYPE_CONTEXT (t),
3980 &find_parameter_packs_r, ppd, ppd->visited);
3982 /* This switch statement will return immediately if we don't find a
3983 parameter pack. ??? Should some of these be in cp_walk_subtrees? */
3984 switch (TREE_CODE (t))
3986 case BOUND_TEMPLATE_TEMPLATE_PARM:
3987 /* Check the template itself. */
3988 cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)),
3989 &find_parameter_packs_r, ppd, ppd->visited);
3990 return NULL_TREE;
3992 case DECL_EXPR:
3994 tree decl = DECL_EXPR_DECL (t);
3995 /* Ignore the declaration of a capture proxy for a parameter pack. */
3996 if (is_capture_proxy (decl))
3997 *walk_subtrees = 0;
3998 if (is_typedef_decl (decl))
3999 /* Since we stop at typedefs above, we need to look through them at
4000 the point of the DECL_EXPR. */
4001 cp_walk_tree (&DECL_ORIGINAL_TYPE (decl),
4002 &find_parameter_packs_r, ppd, ppd->visited);
4003 return NULL_TREE;
4006 case TEMPLATE_DECL:
4007 if (!DECL_TEMPLATE_TEMPLATE_PARM_P (t))
4008 return NULL_TREE;
4009 cp_walk_tree (&TREE_TYPE (t),
4010 &find_parameter_packs_r, ppd, ppd->visited);
4011 return NULL_TREE;
4013 case TYPE_PACK_EXPANSION:
4014 case EXPR_PACK_EXPANSION:
4015 *walk_subtrees = 0;
4016 return NULL_TREE;
4018 case INTEGER_TYPE:
4019 cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r,
4020 ppd, ppd->visited);
4021 *walk_subtrees = 0;
4022 return NULL_TREE;
4024 case IDENTIFIER_NODE:
4025 cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd,
4026 ppd->visited);
4027 *walk_subtrees = 0;
4028 return NULL_TREE;
4030 case LAMBDA_EXPR:
4032 /* Since we defer implicit capture, look in the parms and body. */
4033 tree fn = lambda_function (t);
4034 cp_walk_tree (&TREE_TYPE (fn), &find_parameter_packs_r, ppd,
4035 ppd->visited);
4036 cp_walk_tree (&DECL_SAVED_TREE (fn), &find_parameter_packs_r, ppd,
4037 ppd->visited);
4038 return NULL_TREE;
4041 case DECLTYPE_TYPE:
4043 /* When traversing a DECLTYPE_TYPE_EXPR, we need to set
4044 type_pack_expansion_p to false so that any placeholders
4045 within the expression don't get marked as parameter packs. */
4046 bool type_pack_expansion_p = ppd->type_pack_expansion_p;
4047 ppd->type_pack_expansion_p = false;
4048 cp_walk_tree (&DECLTYPE_TYPE_EXPR (t), &find_parameter_packs_r,
4049 ppd, ppd->visited);
4050 ppd->type_pack_expansion_p = type_pack_expansion_p;
4051 *walk_subtrees = 0;
4052 return NULL_TREE;
4055 case IF_STMT:
4056 cp_walk_tree (&IF_COND (t), &find_parameter_packs_r,
4057 ppd, ppd->visited);
4058 cp_walk_tree (&THEN_CLAUSE (t), &find_parameter_packs_r,
4059 ppd, ppd->visited);
4060 cp_walk_tree (&ELSE_CLAUSE (t), &find_parameter_packs_r,
4061 ppd, ppd->visited);
4062 /* Don't walk into IF_STMT_EXTRA_ARGS. */
4063 *walk_subtrees = 0;
4064 return NULL_TREE;
4066 case TAG_DEFN:
4067 t = TREE_TYPE (t);
4068 if (CLASS_TYPE_P (t))
4069 /* Local class, need to look through the whole definition. */
4070 for (tree bb : BINFO_BASE_BINFOS (TYPE_BINFO (t)))
4071 cp_walk_tree (&BINFO_TYPE (bb), &find_parameter_packs_r,
4072 ppd, ppd->visited);
4073 else
4074 /* Enum, look at the values. */
4075 for (tree l = TYPE_VALUES (t); l; l = TREE_CHAIN (l))
4076 cp_walk_tree (&DECL_INITIAL (TREE_VALUE (l)),
4077 &find_parameter_packs_r,
4078 ppd, ppd->visited);
4079 return NULL_TREE;
4081 case FUNCTION_TYPE:
4082 case METHOD_TYPE:
4083 WALK_SUBTREE (TYPE_RAISES_EXCEPTIONS (t));
4084 break;
4086 default:
4087 return NULL_TREE;
4090 #undef WALK_SUBTREE
4092 return NULL_TREE;
4095 /* Determines if the expression or type T uses any parameter packs. */
4096 tree
4097 uses_parameter_packs (tree t)
4099 tree parameter_packs = NULL_TREE;
4100 struct find_parameter_pack_data ppd;
4101 ppd.parameter_packs = &parameter_packs;
4102 ppd.visited = new hash_set<tree>;
4103 ppd.type_pack_expansion_p = false;
4104 cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4105 delete ppd.visited;
4106 return parameter_packs;
4109 /* Turn ARG, which may be an expression, type, or a TREE_LIST
4110 representation a base-class initializer into a parameter pack
4111 expansion. If all goes well, the resulting node will be an
4112 EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
4113 respectively. */
4114 tree
4115 make_pack_expansion (tree arg, tsubst_flags_t complain)
4117 tree result;
4118 tree parameter_packs = NULL_TREE;
4119 bool for_types = false;
4120 struct find_parameter_pack_data ppd;
4122 if (!arg || arg == error_mark_node)
4123 return arg;
4125 if (TREE_CODE (arg) == TREE_LIST && TREE_PURPOSE (arg))
4127 /* A TREE_LIST with a non-null TREE_PURPOSE is for a base
4128 class initializer. In this case, the TREE_PURPOSE will be a
4129 _TYPE node (representing the base class expansion we're
4130 initializing) and the TREE_VALUE will be a TREE_LIST
4131 containing the initialization arguments.
4133 The resulting expansion looks somewhat different from most
4134 expansions. Rather than returning just one _EXPANSION, we
4135 return a TREE_LIST whose TREE_PURPOSE is a
4136 TYPE_PACK_EXPANSION containing the bases that will be
4137 initialized. The TREE_VALUE will be identical to the
4138 original TREE_VALUE, which is a list of arguments that will
4139 be passed to each base. We do not introduce any new pack
4140 expansion nodes into the TREE_VALUE (although it is possible
4141 that some already exist), because the TREE_PURPOSE and
4142 TREE_VALUE all need to be expanded together with the same
4143 _EXPANSION node. Note that the TYPE_PACK_EXPANSION in the
4144 resulting TREE_PURPOSE will mention the parameter packs in
4145 both the bases and the arguments to the bases. */
4146 tree purpose;
4147 tree value;
4148 tree parameter_packs = NULL_TREE;
4150 /* Determine which parameter packs will be used by the base
4151 class expansion. */
4152 ppd.visited = new hash_set<tree>;
4153 ppd.parameter_packs = &parameter_packs;
4154 ppd.type_pack_expansion_p = false;
4155 gcc_assert (TYPE_P (TREE_PURPOSE (arg)));
4156 cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r,
4157 &ppd, ppd.visited);
4159 if (parameter_packs == NULL_TREE)
4161 if (complain & tf_error)
4162 error ("base initializer expansion %qT contains no parameter packs",
4163 arg);
4164 delete ppd.visited;
4165 return error_mark_node;
4168 if (TREE_VALUE (arg) != void_type_node)
4170 /* Collect the sets of parameter packs used in each of the
4171 initialization arguments. */
4172 for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
4174 /* Determine which parameter packs will be expanded in this
4175 argument. */
4176 cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r,
4177 &ppd, ppd.visited);
4181 delete ppd.visited;
4183 /* Create the pack expansion type for the base type. */
4184 purpose = cxx_make_type (TYPE_PACK_EXPANSION);
4185 PACK_EXPANSION_PATTERN (purpose) = TREE_PURPOSE (arg);
4186 PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
4187 PACK_EXPANSION_LOCAL_P (purpose) = at_function_scope_p ();
4189 /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
4190 they will rarely be compared to anything. */
4191 SET_TYPE_STRUCTURAL_EQUALITY (purpose);
4193 return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
4196 if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
4197 for_types = true;
4199 /* Build the PACK_EXPANSION_* node. */
4200 result = for_types
4201 ? cxx_make_type (TYPE_PACK_EXPANSION)
4202 : make_node (EXPR_PACK_EXPANSION);
4203 PACK_EXPANSION_PATTERN (result) = arg;
4204 if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
4206 /* Propagate type and const-expression information. */
4207 TREE_TYPE (result) = TREE_TYPE (arg);
4208 TREE_CONSTANT (result) = TREE_CONSTANT (arg);
4209 /* Mark this read now, since the expansion might be length 0. */
4210 mark_exp_read (arg);
4212 else
4213 /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
4214 they will rarely be compared to anything. */
4215 SET_TYPE_STRUCTURAL_EQUALITY (result);
4217 /* Determine which parameter packs will be expanded. */
4218 ppd.parameter_packs = &parameter_packs;
4219 ppd.visited = new hash_set<tree>;
4220 ppd.type_pack_expansion_p = TYPE_P (arg);
4221 cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
4222 delete ppd.visited;
4224 /* Make sure we found some parameter packs. */
4225 if (parameter_packs == NULL_TREE)
4227 if (complain & tf_error)
4229 if (TYPE_P (arg))
4230 error ("expansion pattern %qT contains no parameter packs", arg);
4231 else
4232 error ("expansion pattern %qE contains no parameter packs", arg);
4234 return error_mark_node;
4236 PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
4238 PACK_EXPANSION_LOCAL_P (result) = at_function_scope_p ();
4239 if (ppd.found_extra_args_tree_p)
4240 /* If the pattern of this pack expansion contains a subtree that has
4241 the extra args mechanism for avoiding partial instantiation, then
4242 force this pack expansion to also use extra args. Otherwise
4243 partial instantiation of this pack expansion may not lower the
4244 level of some parameter packs within the pattern, which would
4245 confuse tsubst_pack_expansion later (PR101764). */
4246 PACK_EXPANSION_FORCE_EXTRA_ARGS_P (result) = true;
4248 return result;
4251 /* Checks T for any "bare" parameter packs, which have not yet been
4252 expanded, and issues an error if any are found. This operation can
4253 only be done on full expressions or types (e.g., an expression
4254 statement, "if" condition, etc.), because we could have expressions like:
4256 foo(f(g(h(args)))...)
4258 where "args" is a parameter pack. check_for_bare_parameter_packs
4259 should not be called for the subexpressions args, h(args),
4260 g(h(args)), or f(g(h(args))), because we would produce erroneous
4261 error messages.
4263 Returns TRUE and emits an error if there were bare parameter packs,
4264 returns FALSE otherwise. */
4265 bool
4266 check_for_bare_parameter_packs (tree t, location_t loc /* = UNKNOWN_LOCATION */)
4268 tree parameter_packs = NULL_TREE;
4269 struct find_parameter_pack_data ppd;
4271 if (!processing_template_decl || !t || t == error_mark_node)
4272 return false;
4274 if (TREE_CODE (t) == TYPE_DECL)
4275 t = TREE_TYPE (t);
4277 ppd.parameter_packs = &parameter_packs;
4278 ppd.visited = new hash_set<tree>;
4279 ppd.type_pack_expansion_p = false;
4280 cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4281 delete ppd.visited;
4283 if (!parameter_packs)
4284 return false;
4286 if (loc == UNKNOWN_LOCATION)
4287 loc = cp_expr_loc_or_input_loc (t);
4289 /* It's OK for a lambda to have an unexpanded parameter pack from the
4290 containing context, but do complain about unexpanded capture packs. */
4291 tree lam = current_lambda_expr ();
4292 if (lam)
4293 lam = TREE_TYPE (lam);
4295 if (lam && lam != current_class_type)
4297 /* We're in a lambda, but it isn't the innermost class.
4298 This should work, but currently doesn't. */
4299 sorry_at (loc, "unexpanded parameter pack in local class in lambda");
4300 return true;
4303 if (lam && CLASSTYPE_TEMPLATE_INFO (lam))
4304 for (; parameter_packs;
4305 parameter_packs = TREE_CHAIN (parameter_packs))
4307 tree pack = TREE_VALUE (parameter_packs);
4308 if (is_capture_proxy (pack)
4309 || (TREE_CODE (pack) == PARM_DECL
4310 && DECL_CONTEXT (DECL_CONTEXT (pack)) == lam))
4311 break;
4314 if (parameter_packs)
4316 error_at (loc, "parameter packs not expanded with %<...%>:");
4317 while (parameter_packs)
4319 tree pack = TREE_VALUE (parameter_packs);
4320 tree name = NULL_TREE;
4322 if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
4323 || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
4324 name = TYPE_NAME (pack);
4325 else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
4326 name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
4327 else if (TREE_CODE (pack) == CALL_EXPR)
4328 name = DECL_NAME (CALL_EXPR_FN (pack));
4329 else
4330 name = DECL_NAME (pack);
4332 if (name)
4333 inform (loc, " %qD", name);
4334 else
4335 inform (loc, " %s", "<anonymous>");
4337 parameter_packs = TREE_CHAIN (parameter_packs);
4340 return true;
4343 return false;
4346 /* Expand any parameter packs that occur in the template arguments in
4347 ARGS. */
4348 tree
4349 expand_template_argument_pack (tree args)
4351 if (args == error_mark_node)
4352 return error_mark_node;
4354 tree result_args = NULL_TREE;
4355 int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
4356 int num_result_args = -1;
4357 int non_default_args_count = -1;
4359 /* First, determine if we need to expand anything, and the number of
4360 slots we'll need. */
4361 for (in_arg = 0; in_arg < nargs; ++in_arg)
4363 tree arg = TREE_VEC_ELT (args, in_arg);
4364 if (arg == NULL_TREE)
4365 return args;
4366 if (ARGUMENT_PACK_P (arg))
4368 int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
4369 if (num_result_args < 0)
4370 num_result_args = in_arg + num_packed;
4371 else
4372 num_result_args += num_packed;
4374 else
4376 if (num_result_args >= 0)
4377 num_result_args++;
4381 /* If no expansion is necessary, we're done. */
4382 if (num_result_args < 0)
4383 return args;
4385 /* Expand arguments. */
4386 result_args = make_tree_vec (num_result_args);
4387 if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
4388 non_default_args_count =
4389 GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
4390 for (in_arg = 0; in_arg < nargs; ++in_arg)
4392 tree arg = TREE_VEC_ELT (args, in_arg);
4393 if (ARGUMENT_PACK_P (arg))
4395 tree packed = ARGUMENT_PACK_ARGS (arg);
4396 int i, num_packed = TREE_VEC_LENGTH (packed);
4397 for (i = 0; i < num_packed; ++i, ++out_arg)
4398 TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
4399 if (non_default_args_count > 0)
4400 non_default_args_count += num_packed - 1;
4402 else
4404 TREE_VEC_ELT (result_args, out_arg) = arg;
4405 ++out_arg;
4408 if (non_default_args_count >= 0)
4409 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
4410 return result_args;
4413 /* Checks if DECL shadows a template parameter.
4415 [temp.local]: A template-parameter shall not be redeclared within its
4416 scope (including nested scopes).
4418 Emits an error and returns TRUE if the DECL shadows a parameter,
4419 returns FALSE otherwise. */
4421 bool
4422 check_template_shadow (tree decl)
4424 tree olddecl;
4426 /* If we're not in a template, we can't possibly shadow a template
4427 parameter. */
4428 if (!current_template_parms)
4429 return true;
4431 /* Figure out what we're shadowing. */
4432 decl = OVL_FIRST (decl);
4433 olddecl = innermost_non_namespace_value (DECL_NAME (decl));
4435 /* If there's no previous binding for this name, we're not shadowing
4436 anything, let alone a template parameter. */
4437 if (!olddecl)
4438 return true;
4440 /* If we're not shadowing a template parameter, we're done. Note
4441 that OLDDECL might be an OVERLOAD (or perhaps even an
4442 ERROR_MARK), so we can't just blithely assume it to be a _DECL
4443 node. */
4444 if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
4445 return true;
4447 /* We check for decl != olddecl to avoid bogus errors for using a
4448 name inside a class. We check TPFI to avoid duplicate errors for
4449 inline member templates. */
4450 if (decl == olddecl
4451 || (DECL_TEMPLATE_PARM_P (decl)
4452 && TEMPLATE_PARMS_FOR_INLINE (current_template_parms)))
4453 return true;
4455 /* Don't complain about the injected class name, as we've already
4456 complained about the class itself. */
4457 if (DECL_SELF_REFERENCE_P (decl))
4458 return false;
4460 if (DECL_TEMPLATE_PARM_P (decl))
4461 error ("declaration of template parameter %q+D shadows "
4462 "template parameter", decl);
4463 else
4464 error ("declaration of %q+#D shadows template parameter", decl);
4465 inform (DECL_SOURCE_LOCATION (olddecl),
4466 "template parameter %qD declared here", olddecl);
4467 return false;
4470 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
4471 ORIG_LEVEL, DECL, and TYPE. */
4473 static tree
4474 build_template_parm_index (int index,
4475 int level,
4476 int orig_level,
4477 tree decl,
4478 tree type)
4480 tree t = make_node (TEMPLATE_PARM_INDEX);
4481 TEMPLATE_PARM_IDX (t) = index;
4482 TEMPLATE_PARM_LEVEL (t) = level;
4483 TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
4484 TEMPLATE_PARM_DECL (t) = decl;
4485 TREE_TYPE (t) = type;
4486 TREE_CONSTANT (t) = TREE_CONSTANT (decl);
4487 TREE_READONLY (t) = TREE_READONLY (decl);
4489 return t;
4492 struct ctp_hasher : ggc_ptr_hash<tree_node>
4494 static hashval_t hash (tree t)
4496 ++comparing_specializations;
4497 tree_code code = TREE_CODE (t);
4498 hashval_t val = iterative_hash_object (code, 0);
4499 val = iterative_hash_object (TEMPLATE_TYPE_LEVEL (t), val);
4500 val = iterative_hash_object (TEMPLATE_TYPE_IDX (t), val);
4501 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
4502 val = iterative_hash_template_arg (TYPE_TI_ARGS (t), val);
4503 --comparing_specializations;
4504 return val;
4507 static bool equal (tree t, tree u)
4509 ++comparing_specializations;
4510 bool eq = comptypes (t, u, COMPARE_STRUCTURAL);
4511 --comparing_specializations;
4512 return eq;
4516 static GTY (()) hash_table<ctp_hasher> *ctp_table;
4518 /* Find the canonical type parameter for the given template type
4519 parameter. Returns the canonical type parameter, which may be TYPE
4520 if no such parameter existed. */
4522 tree
4523 canonical_type_parameter (tree type)
4525 if (ctp_table == NULL)
4526 ctp_table = hash_table<ctp_hasher>::create_ggc (61);
4528 tree& slot = *ctp_table->find_slot (type, INSERT);
4529 if (slot == NULL_TREE)
4530 slot = type;
4531 return slot;
4534 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
4535 TEMPLATE_PARM_LEVEL has been decreased by LEVELS. If such a
4536 TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
4537 new one is created. */
4539 static tree
4540 reduce_template_parm_level (tree index, tree type, int levels, tree args,
4541 tsubst_flags_t complain)
4543 if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
4544 || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
4545 != TEMPLATE_PARM_LEVEL (index) - levels)
4546 || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
4548 tree orig_decl = TEMPLATE_PARM_DECL (index);
4550 tree decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
4551 TREE_CODE (orig_decl), DECL_NAME (orig_decl),
4552 type);
4553 TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
4554 TREE_READONLY (decl) = TREE_READONLY (orig_decl);
4555 DECL_VIRTUAL_P (decl) = DECL_VIRTUAL_P (orig_decl);
4556 DECL_ARTIFICIAL (decl) = 1;
4557 SET_DECL_TEMPLATE_PARM_P (decl);
4559 tree tpi = build_template_parm_index (TEMPLATE_PARM_IDX (index),
4560 TEMPLATE_PARM_LEVEL (index) - levels,
4561 TEMPLATE_PARM_ORIG_LEVEL (index),
4562 decl, type);
4563 TEMPLATE_PARM_DESCENDANTS (index) = tpi;
4564 TEMPLATE_PARM_PARAMETER_PACK (tpi)
4565 = TEMPLATE_PARM_PARAMETER_PACK (index);
4567 /* Template template parameters need this. */
4568 tree inner = decl;
4569 if (TREE_CODE (decl) == TEMPLATE_DECL)
4571 inner = build_decl (DECL_SOURCE_LOCATION (decl),
4572 TYPE_DECL, DECL_NAME (decl), type);
4573 DECL_TEMPLATE_RESULT (decl) = inner;
4574 DECL_ARTIFICIAL (inner) = true;
4575 DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
4576 (DECL_TEMPLATE_PARMS (orig_decl), args, complain);
4579 /* Attach the TPI to the decl. */
4580 if (TREE_CODE (inner) == TYPE_DECL)
4581 TEMPLATE_TYPE_PARM_INDEX (type) = tpi;
4582 else
4583 DECL_INITIAL (decl) = tpi;
4586 return TEMPLATE_PARM_DESCENDANTS (index);
4589 /* Process information from new template parameter PARM and append it
4590 to the LIST being built. This new parameter is a non-type
4591 parameter iff IS_NON_TYPE is true. This new parameter is a
4592 parameter pack iff IS_PARAMETER_PACK is true. The location of PARM
4593 is in PARM_LOC. */
4595 tree
4596 process_template_parm (tree list, location_t parm_loc, tree parm,
4597 bool is_non_type, bool is_parameter_pack)
4599 gcc_assert (TREE_CODE (parm) == TREE_LIST);
4600 tree prev = NULL_TREE;
4601 int idx = 0;
4603 if (list)
4605 prev = tree_last (list);
4607 tree p = TREE_VALUE (prev);
4608 if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
4609 idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
4610 else if (TREE_CODE (p) == PARM_DECL)
4611 idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
4613 ++idx;
4616 tree decl = NULL_TREE;
4617 tree defval = TREE_PURPOSE (parm);
4618 tree constr = TREE_TYPE (parm);
4620 if (is_non_type)
4622 parm = TREE_VALUE (parm);
4624 SET_DECL_TEMPLATE_PARM_P (parm);
4626 if (TREE_TYPE (parm) != error_mark_node)
4628 /* [temp.param]
4630 The top-level cv-qualifiers on the template-parameter are
4631 ignored when determining its type. */
4632 TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
4633 if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
4634 TREE_TYPE (parm) = error_mark_node;
4635 else if (uses_parameter_packs (TREE_TYPE (parm))
4636 && !is_parameter_pack
4637 /* If we're in a nested template parameter list, the template
4638 template parameter could be a parameter pack. */
4639 && processing_template_parmlist == 1)
4641 /* This template parameter is not a parameter pack, but it
4642 should be. Complain about "bare" parameter packs. */
4643 check_for_bare_parameter_packs (TREE_TYPE (parm));
4645 /* Recover by calling this a parameter pack. */
4646 is_parameter_pack = true;
4650 /* A template parameter is not modifiable. */
4651 TREE_CONSTANT (parm) = 1;
4652 TREE_READONLY (parm) = 1;
4653 decl = build_decl (parm_loc,
4654 CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
4655 TREE_CONSTANT (decl) = 1;
4656 TREE_READONLY (decl) = 1;
4657 DECL_INITIAL (parm) = DECL_INITIAL (decl)
4658 = build_template_parm_index (idx, current_template_depth,
4659 current_template_depth,
4660 decl, TREE_TYPE (parm));
4662 TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))
4663 = is_parameter_pack;
4665 else
4667 tree t;
4668 parm = TREE_VALUE (TREE_VALUE (parm));
4670 if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
4672 t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
4673 /* This is for distinguishing between real templates and template
4674 template parameters */
4675 TREE_TYPE (parm) = t;
4677 /* any_template_parm_r expects to be able to get the targs of a
4678 DECL_TEMPLATE_RESULT. */
4679 tree result = DECL_TEMPLATE_RESULT (parm);
4680 TREE_TYPE (result) = t;
4681 tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (parm));
4682 tree tinfo = build_template_info (parm, args);
4683 retrofit_lang_decl (result);
4684 DECL_TEMPLATE_INFO (result) = tinfo;
4686 decl = parm;
4688 else
4690 t = cxx_make_type (TEMPLATE_TYPE_PARM);
4691 /* parm is either IDENTIFIER_NODE or NULL_TREE. */
4692 decl = build_decl (parm_loc,
4693 TYPE_DECL, parm, t);
4696 TYPE_NAME (t) = decl;
4697 TYPE_STUB_DECL (t) = decl;
4698 parm = decl;
4699 TEMPLATE_TYPE_PARM_INDEX (t)
4700 = build_template_parm_index (idx, current_template_depth,
4701 current_template_depth,
4702 decl, TREE_TYPE (parm));
4703 TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
4704 TYPE_CANONICAL (t) = canonical_type_parameter (t);
4706 DECL_ARTIFICIAL (decl) = 1;
4707 SET_DECL_TEMPLATE_PARM_P (decl);
4709 /* Build requirements for the type/template parameter.
4710 This must be done after SET_DECL_TEMPLATE_PARM_P or
4711 process_template_parm could fail. */
4712 tree reqs = finish_shorthand_constraint (parm, constr);
4714 decl = pushdecl (decl);
4715 if (!is_non_type)
4716 parm = decl;
4718 /* Build the parameter node linking the parameter declaration,
4719 its default argument (if any), and its constraints (if any). */
4720 parm = build_tree_list (defval, parm);
4721 TEMPLATE_PARM_CONSTRAINTS (parm) = reqs;
4723 if (prev)
4724 TREE_CHAIN (prev) = parm;
4725 else
4726 list = parm;
4728 return list;
4731 /* The end of a template parameter list has been reached. Process the
4732 tree list into a parameter vector, converting each parameter into a more
4733 useful form. Type parameters are saved as IDENTIFIER_NODEs, and others
4734 as PARM_DECLs. */
4736 tree
4737 end_template_parm_list (tree parms)
4739 tree saved_parmlist = make_tree_vec (list_length (parms));
4741 /* Pop the dummy parameter level and add the real one. We do not
4742 morph the dummy parameter in place, as it might have been
4743 captured by a (nested) template-template-parm. */
4744 current_template_parms = TREE_CHAIN (current_template_parms);
4746 current_template_parms
4747 = tree_cons (size_int (current_template_depth + 1),
4748 saved_parmlist, current_template_parms);
4750 for (unsigned ix = 0; parms; ix++)
4752 tree parm = parms;
4753 parms = TREE_CHAIN (parms);
4754 TREE_CHAIN (parm) = NULL_TREE;
4756 TREE_VEC_ELT (saved_parmlist, ix) = parm;
4759 --processing_template_parmlist;
4761 return saved_parmlist;
4764 // Explicitly indicate the end of the template parameter list. We assume
4765 // that the current template parameters have been constructed and/or
4766 // managed explicitly, as when creating new template template parameters
4767 // from a shorthand constraint.
4768 void
4769 end_template_parm_list ()
4771 --processing_template_parmlist;
4774 /* end_template_decl is called after a template declaration is seen. */
4776 void
4777 end_template_decl (void)
4779 reset_specialization ();
4781 if (! processing_template_decl)
4782 return;
4784 /* This matches the pushlevel in begin_template_parm_list. */
4785 finish_scope ();
4787 --processing_template_decl;
4788 current_template_parms = TREE_CHAIN (current_template_parms);
4791 /* Takes a TEMPLATE_PARM_P or DECL_TEMPLATE_PARM_P node or a TREE_LIST
4792 thereof, and converts it into an argument suitable to be passed to
4793 the type substitution functions. Note that if the TREE_LIST contains
4794 an error_mark node, the returned argument is error_mark_node. */
4796 tree
4797 template_parm_to_arg (tree t)
4799 if (!t)
4800 return NULL_TREE;
4802 if (TREE_CODE (t) == TREE_LIST)
4803 t = TREE_VALUE (t);
4805 if (error_operand_p (t))
4806 return error_mark_node;
4808 if (DECL_P (t) && DECL_TEMPLATE_PARM_P (t))
4810 if (TREE_CODE (t) == TYPE_DECL
4811 || TREE_CODE (t) == TEMPLATE_DECL)
4812 t = TREE_TYPE (t);
4813 else
4814 t = DECL_INITIAL (t);
4817 gcc_assert (TEMPLATE_PARM_P (t));
4819 if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
4820 || TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
4822 if (TEMPLATE_TYPE_PARAMETER_PACK (t))
4824 /* Turn this argument into a TYPE_ARGUMENT_PACK
4825 with a single element, which expands T. */
4826 tree vec = make_tree_vec (1);
4827 if (CHECKING_P)
4828 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4830 TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4832 t = cxx_make_type (TYPE_ARGUMENT_PACK);
4833 ARGUMENT_PACK_ARGS (t) = vec;
4836 else
4838 if (TEMPLATE_PARM_PARAMETER_PACK (t))
4840 /* Turn this argument into a NONTYPE_ARGUMENT_PACK
4841 with a single element, which expands T. */
4842 tree vec = make_tree_vec (1);
4843 if (CHECKING_P)
4844 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4846 t = convert_from_reference (t);
4847 TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4849 t = make_node (NONTYPE_ARGUMENT_PACK);
4850 ARGUMENT_PACK_ARGS (t) = vec;
4852 else
4853 t = convert_from_reference (t);
4855 return t;
4858 /* If T looks like a generic template argument produced by template_parm_to_arg,
4859 return the corresponding template parameter, otherwise return NULL_TREE. */
4861 static tree
4862 template_arg_to_parm (tree t)
4864 if (t == NULL_TREE)
4865 return NULL_TREE;
4867 if (ARGUMENT_PACK_P (t))
4869 tree args = ARGUMENT_PACK_ARGS (t);
4870 if (TREE_VEC_LENGTH (args) == 1
4871 && PACK_EXPANSION_P (TREE_VEC_ELT (args, 0)))
4872 t = PACK_EXPANSION_PATTERN (TREE_VEC_ELT (args, 0));
4875 if (REFERENCE_REF_P (t))
4876 t = TREE_OPERAND (t, 0);
4878 if (TEMPLATE_PARM_P (t))
4879 return t;
4880 else
4881 return NULL_TREE;
4884 /* Given a single level of template parameters (a TREE_VEC), return it
4885 as a set of template arguments. */
4887 tree
4888 template_parms_level_to_args (tree parms)
4890 parms = copy_node (parms);
4891 TREE_TYPE (parms) = NULL_TREE;
4892 for (tree& parm : tree_vec_range (parms))
4893 parm = template_parm_to_arg (parm);
4895 if (CHECKING_P)
4896 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (parms, TREE_VEC_LENGTH (parms));
4898 return parms;
4901 /* Given a set of template parameters, return them as a set of template
4902 arguments. The template parameters are represented as a TREE_VEC, in
4903 the form documented in cp-tree.h for template arguments. */
4905 tree
4906 template_parms_to_args (tree parms)
4908 tree header;
4909 tree args = NULL_TREE;
4910 int length = TMPL_PARMS_DEPTH (parms);
4911 int l = length;
4913 /* If there is only one level of template parameters, we do not
4914 create a TREE_VEC of TREE_VECs. Instead, we return a single
4915 TREE_VEC containing the arguments. */
4916 if (length > 1)
4917 args = make_tree_vec (length);
4919 for (header = parms; header; header = TREE_CHAIN (header))
4921 tree a = template_parms_level_to_args (TREE_VALUE (header));
4923 if (length > 1)
4924 TREE_VEC_ELT (args, --l) = a;
4925 else
4926 args = a;
4929 return args;
4932 /* Within the declaration of a template, return the currently active
4933 template parameters as an argument TREE_VEC. */
4935 static tree
4936 current_template_args (void)
4938 return template_parms_to_args (current_template_parms);
4941 /* Return the fully generic arguments for of TMPL, i.e. what
4942 current_template_args would be while parsing it. */
4944 tree
4945 generic_targs_for (tree tmpl)
4947 if (tmpl == NULL_TREE)
4948 return NULL_TREE;
4949 if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
4950 || DECL_TEMPLATE_SPECIALIZATION (tmpl))
4951 /* DECL_TEMPLATE_RESULT doesn't have the arguments we want. For a template
4952 template parameter, it has no TEMPLATE_INFO; for a partial
4953 specialization, it has the arguments for the primary template, and we
4954 want the arguments for the partial specialization. */;
4955 else if (tree result = DECL_TEMPLATE_RESULT (tmpl))
4956 if (tree ti = get_template_info (result))
4957 return TI_ARGS (ti);
4958 return template_parms_to_args (DECL_TEMPLATE_PARMS (tmpl));
4961 /* Update the declared TYPE by doing any lookups which were thought to be
4962 dependent, but are not now that we know the SCOPE of the declarator. */
4964 tree
4965 maybe_update_decl_type (tree orig_type, tree scope)
4967 tree type = orig_type;
4969 if (type == NULL_TREE)
4970 return type;
4972 if (TREE_CODE (orig_type) == TYPE_DECL)
4973 type = TREE_TYPE (type);
4975 if (scope && TYPE_P (scope) && dependent_type_p (scope)
4976 && dependent_type_p (type)
4977 /* Don't bother building up the args in this case. */
4978 && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
4980 /* tsubst in the args corresponding to the template parameters,
4981 including auto if present. Most things will be unchanged, but
4982 make_typename_type and tsubst_qualified_id will resolve
4983 TYPENAME_TYPEs and SCOPE_REFs that were previously dependent. */
4984 tree args = current_template_args ();
4985 tree auto_node = type_uses_auto (type);
4986 tree pushed;
4987 if (auto_node)
4989 tree auto_vec = make_tree_vec (1);
4990 TREE_VEC_ELT (auto_vec, 0) = auto_node;
4991 args = add_to_template_args (args, auto_vec);
4993 pushed = push_scope (scope);
4994 type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
4995 if (pushed)
4996 pop_scope (scope);
4999 if (type == error_mark_node)
5000 return orig_type;
5002 if (TREE_CODE (orig_type) == TYPE_DECL)
5004 if (same_type_p (type, TREE_TYPE (orig_type)))
5005 type = orig_type;
5006 else
5007 type = TYPE_NAME (type);
5009 return type;
5012 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
5013 template PARMS and constraints, CONSTR. If MEMBER_TEMPLATE_P is true,
5014 the new template is a member template. */
5016 static tree
5017 build_template_decl (tree decl, tree parms, bool member_template_p)
5019 gcc_checking_assert (TREE_CODE (decl) != TEMPLATE_DECL);
5021 tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
5022 SET_DECL_LANGUAGE (tmpl, DECL_LANGUAGE (decl));
5023 DECL_TEMPLATE_PARMS (tmpl) = parms;
5024 DECL_TEMPLATE_RESULT (tmpl) = decl;
5025 DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
5026 TREE_TYPE (tmpl) = TREE_TYPE (decl);
5027 DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
5028 DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
5030 /* Propagate module information from the decl. */
5031 DECL_MODULE_EXPORT_P (tmpl) = DECL_MODULE_EXPORT_P (decl);
5033 return tmpl;
5036 struct template_parm_data
5038 /* The level of the template parameters we are currently
5039 processing. */
5040 int level;
5042 /* The index of the specialization argument we are currently
5043 processing. */
5044 int current_arg;
5046 /* An array whose size is the number of template parameters. The
5047 elements are nonzero if the parameter has been used in any one
5048 of the arguments processed so far. */
5049 int* parms;
5051 /* An array whose size is the number of template arguments. The
5052 elements are nonzero if the argument makes use of template
5053 parameters of this level. */
5054 int* arg_uses_template_parms;
5057 /* Subroutine of push_template_decl used to see if each template
5058 parameter in a partial specialization is used in the explicit
5059 argument list. If T is of the LEVEL given in DATA (which is
5060 treated as a template_parm_data*), then DATA->PARMS is marked
5061 appropriately. */
5063 static int
5064 mark_template_parm (tree t, void* data)
5066 int level;
5067 int idx;
5068 struct template_parm_data* tpd = (struct template_parm_data*) data;
5070 template_parm_level_and_index (t, &level, &idx);
5072 if (level == tpd->level)
5074 tpd->parms[idx] = 1;
5075 tpd->arg_uses_template_parms[tpd->current_arg] = 1;
5078 /* In C++17 the type of a non-type argument is a deduced context. */
5079 if (cxx_dialect >= cxx17
5080 && TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5081 for_each_template_parm (TREE_TYPE (t),
5082 &mark_template_parm,
5083 data,
5084 NULL,
5085 /*include_nondeduced_p=*/false);
5087 /* Return zero so that for_each_template_parm will continue the
5088 traversal of the tree; we want to mark *every* template parm. */
5089 return 0;
5092 /* Process the partial specialization DECL. */
5094 static tree
5095 process_partial_specialization (tree decl)
5097 tree type = TREE_TYPE (decl);
5098 tree tinfo = get_template_info (decl);
5099 tree maintmpl = TI_TEMPLATE (tinfo);
5100 tree specargs = TI_ARGS (tinfo);
5101 tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
5102 tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
5103 tree inner_parms;
5104 tree inst;
5105 int nargs = TREE_VEC_LENGTH (inner_args);
5106 int ntparms;
5107 int i;
5108 bool did_error_intro = false;
5109 struct template_parm_data tpd;
5110 struct template_parm_data tpd2;
5112 gcc_assert (current_template_parms);
5114 /* A concept cannot be specialized. */
5115 if (flag_concepts && variable_concept_p (maintmpl))
5117 error ("specialization of variable concept %q#D", maintmpl);
5118 return error_mark_node;
5121 inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
5122 ntparms = TREE_VEC_LENGTH (inner_parms);
5124 /* We check that each of the template parameters given in the
5125 partial specialization is used in the argument list to the
5126 specialization. For example:
5128 template <class T> struct S;
5129 template <class T> struct S<T*>;
5131 The second declaration is OK because `T*' uses the template
5132 parameter T, whereas
5134 template <class T> struct S<int>;
5136 is no good. Even trickier is:
5138 template <class T>
5139 struct S1
5141 template <class U>
5142 struct S2;
5143 template <class U>
5144 struct S2<T>;
5147 The S2<T> declaration is actually invalid; it is a
5148 full-specialization. Of course,
5150 template <class U>
5151 struct S2<T (*)(U)>;
5153 or some such would have been OK. */
5154 tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
5155 tpd.parms = XALLOCAVEC (int, ntparms);
5156 memset (tpd.parms, 0, sizeof (int) * ntparms);
5158 tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
5159 memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
5160 for (i = 0; i < nargs; ++i)
5162 tpd.current_arg = i;
5163 for_each_template_parm (TREE_VEC_ELT (inner_args, i),
5164 &mark_template_parm,
5165 &tpd,
5166 NULL,
5167 /*include_nondeduced_p=*/false);
5169 for (i = 0; i < ntparms; ++i)
5170 if (tpd.parms[i] == 0)
5172 /* One of the template parms was not used in a deduced context in the
5173 specialization. */
5174 if (!did_error_intro)
5176 error ("template parameters not deducible in "
5177 "partial specialization:");
5178 did_error_intro = true;
5181 inform (input_location, " %qD",
5182 TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
5185 if (did_error_intro)
5186 return error_mark_node;
5188 /* [temp.class.spec]
5190 The argument list of the specialization shall not be identical to
5191 the implicit argument list of the primary template. */
5192 tree main_args
5193 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (maintmpl)));
5194 if (comp_template_args (inner_args, INNERMOST_TEMPLATE_ARGS (main_args))
5195 && (!flag_concepts
5196 || !strictly_subsumes (current_template_constraints (), maintmpl)))
5198 if (!flag_concepts)
5199 error ("partial specialization %q+D does not specialize "
5200 "any template arguments; to define the primary template, "
5201 "remove the template argument list", decl);
5202 else
5203 error ("partial specialization %q+D does not specialize any "
5204 "template arguments and is not more constrained than "
5205 "the primary template; to define the primary template, "
5206 "remove the template argument list", decl);
5207 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5210 /* A partial specialization that replaces multiple parameters of the
5211 primary template with a pack expansion is less specialized for those
5212 parameters. */
5213 if (nargs < DECL_NTPARMS (maintmpl))
5215 error ("partial specialization is not more specialized than the "
5216 "primary template because it replaces multiple parameters "
5217 "with a pack expansion");
5218 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5219 /* Avoid crash in process_partial_specialization. */
5220 return decl;
5223 else if (nargs > DECL_NTPARMS (maintmpl))
5225 error ("too many arguments for partial specialization %qT", type);
5226 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5227 /* Avoid crash below. */
5228 return decl;
5231 /* If we aren't in a dependent class, we can actually try deduction. */
5232 else if (tpd.level == 1
5233 /* FIXME we should be able to handle a partial specialization of a
5234 partial instantiation, but currently we can't (c++/41727). */
5235 && TMPL_ARGS_DEPTH (specargs) == 1
5236 && !get_partial_spec_bindings (maintmpl, maintmpl, specargs))
5238 auto_diagnostic_group d;
5239 if (pedwarn (input_location, 0,
5240 "partial specialization %qD is not more specialized than",
5241 decl))
5242 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template %qD",
5243 maintmpl);
5246 /* [temp.spec.partial]
5248 The type of a template parameter corresponding to a specialized
5249 non-type argument shall not be dependent on a parameter of the
5250 specialization.
5252 Also, we verify that pack expansions only occur at the
5253 end of the argument list. */
5254 tpd2.parms = 0;
5255 for (i = 0; i < nargs; ++i)
5257 tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
5258 tree arg = TREE_VEC_ELT (inner_args, i);
5259 tree packed_args = NULL_TREE;
5260 int j, len = 1;
5262 if (ARGUMENT_PACK_P (arg))
5264 /* Extract the arguments from the argument pack. We'll be
5265 iterating over these in the following loop. */
5266 packed_args = ARGUMENT_PACK_ARGS (arg);
5267 len = TREE_VEC_LENGTH (packed_args);
5270 for (j = 0; j < len; j++)
5272 if (packed_args)
5273 /* Get the Jth argument in the parameter pack. */
5274 arg = TREE_VEC_ELT (packed_args, j);
5276 if (PACK_EXPANSION_P (arg))
5278 /* Pack expansions must come at the end of the
5279 argument list. */
5280 if ((packed_args && j < len - 1)
5281 || (!packed_args && i < nargs - 1))
5283 if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5284 error ("parameter pack argument %qE must be at the "
5285 "end of the template argument list", arg);
5286 else
5287 error ("parameter pack argument %qT must be at the "
5288 "end of the template argument list", arg);
5292 if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5293 /* We only care about the pattern. */
5294 arg = PACK_EXPANSION_PATTERN (arg);
5296 if (/* These first two lines are the `non-type' bit. */
5297 !TYPE_P (arg)
5298 && TREE_CODE (arg) != TEMPLATE_DECL
5299 /* This next two lines are the `argument expression is not just a
5300 simple identifier' condition and also the `specialized
5301 non-type argument' bit. */
5302 && TREE_CODE (arg) != TEMPLATE_PARM_INDEX
5303 && !((REFERENCE_REF_P (arg)
5304 || TREE_CODE (arg) == VIEW_CONVERT_EXPR)
5305 && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_PARM_INDEX))
5307 /* Look at the corresponding template parameter,
5308 marking which template parameters its type depends
5309 upon. */
5310 tree type = TREE_TYPE (parm);
5312 if (!tpd2.parms)
5314 /* We haven't yet initialized TPD2. Do so now. */
5315 tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
5316 /* The number of parameters here is the number in the
5317 main template, which, as checked in the assertion
5318 above, is NARGS. */
5319 tpd2.parms = XALLOCAVEC (int, nargs);
5320 tpd2.level =
5321 TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
5324 /* Mark the template parameters. But this time, we're
5325 looking for the template parameters of the main
5326 template, not in the specialization. */
5327 tpd2.current_arg = i;
5328 tpd2.arg_uses_template_parms[i] = 0;
5329 memset (tpd2.parms, 0, sizeof (int) * nargs);
5330 for_each_template_parm (type,
5331 &mark_template_parm,
5332 &tpd2,
5333 NULL,
5334 /*include_nondeduced_p=*/false);
5336 if (tpd2.arg_uses_template_parms [i])
5338 /* The type depended on some template parameters.
5339 If they are fully specialized in the
5340 specialization, that's OK. */
5341 int j;
5342 int count = 0;
5343 for (j = 0; j < nargs; ++j)
5344 if (tpd2.parms[j] != 0
5345 && tpd.arg_uses_template_parms [j])
5346 ++count;
5347 if (count != 0)
5348 error_n (input_location, count,
5349 "type %qT of template argument %qE depends "
5350 "on a template parameter",
5351 "type %qT of template argument %qE depends "
5352 "on template parameters",
5353 type,
5354 arg);
5360 /* We should only get here once. */
5361 if (TREE_CODE (decl) == TYPE_DECL)
5362 gcc_assert (!COMPLETE_TYPE_P (type));
5364 // Build the template decl.
5365 tree tmpl = build_template_decl (decl, current_template_parms,
5366 DECL_MEMBER_TEMPLATE_P (maintmpl));
5367 SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5368 DECL_TEMPLATE_INFO (tmpl) = build_template_info (maintmpl, specargs);
5369 DECL_PRIMARY_TEMPLATE (tmpl) = maintmpl;
5371 /* Give template template parms a DECL_CONTEXT of the template
5372 for which they are a parameter. */
5373 for (i = 0; i < ntparms; ++i)
5375 tree parm = TREE_VALUE (TREE_VEC_ELT (inner_parms, i));
5376 if (TREE_CODE (parm) == TEMPLATE_DECL)
5377 DECL_CONTEXT (parm) = tmpl;
5380 if (VAR_P (decl))
5381 /* We didn't register this in check_explicit_specialization so we could
5382 wait until the constraints were set. */
5383 decl = register_specialization (decl, maintmpl, specargs, false, 0);
5384 else
5385 associate_classtype_constraints (type);
5387 DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
5388 = tree_cons (specargs, tmpl,
5389 DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
5390 TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
5392 for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
5393 inst = TREE_CHAIN (inst))
5395 tree instance = TREE_VALUE (inst);
5396 if (TYPE_P (instance)
5397 ? (COMPLETE_TYPE_P (instance)
5398 && CLASSTYPE_IMPLICIT_INSTANTIATION (instance))
5399 : DECL_TEMPLATE_INSTANTIATION (instance))
5401 tree spec = most_specialized_partial_spec (instance, tf_none);
5402 tree inst_decl = (DECL_P (instance)
5403 ? instance : TYPE_NAME (instance));
5404 if (!spec)
5405 /* OK */;
5406 else if (spec == error_mark_node)
5407 permerror (input_location,
5408 "declaration of %qD ambiguates earlier template "
5409 "instantiation for %qD", decl, inst_decl);
5410 else if (TREE_VALUE (spec) == tmpl)
5411 permerror (input_location,
5412 "partial specialization of %qD after instantiation "
5413 "of %qD", decl, inst_decl);
5417 return decl;
5420 /* PARM is a template parameter of some form; return the corresponding
5421 TEMPLATE_PARM_INDEX. */
5423 static tree
5424 get_template_parm_index (tree parm)
5426 if (TREE_CODE (parm) == PARM_DECL
5427 || TREE_CODE (parm) == CONST_DECL)
5428 parm = DECL_INITIAL (parm);
5429 else if (TREE_CODE (parm) == TYPE_DECL
5430 || TREE_CODE (parm) == TEMPLATE_DECL)
5431 parm = TREE_TYPE (parm);
5432 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
5433 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM
5434 || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
5435 parm = TEMPLATE_TYPE_PARM_INDEX (parm);
5436 gcc_assert (TREE_CODE (parm) == TEMPLATE_PARM_INDEX);
5437 return parm;
5440 /* Subroutine of fixed_parameter_pack_p below. Look for any template
5441 parameter packs used by the template parameter PARM. */
5443 static void
5444 fixed_parameter_pack_p_1 (tree parm, struct find_parameter_pack_data *ppd)
5446 /* A type parm can't refer to another parm. */
5447 if (TREE_CODE (parm) == TYPE_DECL || parm == error_mark_node)
5448 return;
5449 else if (TREE_CODE (parm) == PARM_DECL)
5451 cp_walk_tree (&TREE_TYPE (parm), &find_parameter_packs_r,
5452 ppd, ppd->visited);
5453 return;
5456 gcc_assert (TREE_CODE (parm) == TEMPLATE_DECL);
5458 tree vec = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
5459 for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
5461 tree p = TREE_VALUE (TREE_VEC_ELT (vec, i));
5462 if (template_parameter_pack_p (p))
5463 /* Any packs in the type are expanded by this parameter. */;
5464 else
5465 fixed_parameter_pack_p_1 (p, ppd);
5469 /* PARM is a template parameter pack. Return any parameter packs used in
5470 its type or the type of any of its template parameters. If there are
5471 any such packs, it will be instantiated into a fixed template parameter
5472 list by partial instantiation rather than be fully deduced. */
5474 tree
5475 fixed_parameter_pack_p (tree parm)
5477 /* This can only be true in a member template. */
5478 if (TEMPLATE_PARM_ORIG_LEVEL (get_template_parm_index (parm)) < 2)
5479 return NULL_TREE;
5480 /* This can only be true for a parameter pack. */
5481 if (!template_parameter_pack_p (parm))
5482 return NULL_TREE;
5483 /* A type parm can't refer to another parm. */
5484 if (TREE_CODE (parm) == TYPE_DECL)
5485 return NULL_TREE;
5487 tree parameter_packs = NULL_TREE;
5488 struct find_parameter_pack_data ppd;
5489 ppd.parameter_packs = &parameter_packs;
5490 ppd.visited = new hash_set<tree>;
5491 ppd.type_pack_expansion_p = false;
5493 fixed_parameter_pack_p_1 (parm, &ppd);
5495 delete ppd.visited;
5496 return parameter_packs;
5499 /* Check that a template declaration's use of default arguments and
5500 parameter packs is not invalid. Here, PARMS are the template
5501 parameters. IS_PRIMARY is true if DECL is the thing declared by
5502 a primary template. IS_PARTIAL is true if DECL is a partial
5503 specialization.
5505 IS_FRIEND_DECL is nonzero if DECL is either a non-defining friend
5506 function template declaration or a friend class template
5507 declaration. In the function case, 1 indicates a declaration, 2
5508 indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
5509 emitted for extraneous default arguments.
5511 Returns TRUE if there were no errors found, FALSE otherwise. */
5513 bool
5514 check_default_tmpl_args (tree decl, tree parms, bool is_primary,
5515 bool is_partial, int is_friend_decl)
5517 const char *msg;
5518 int last_level_to_check;
5519 tree parm_level;
5520 bool no_errors = true;
5522 /* [temp.param]
5524 A default template-argument shall not be specified in a
5525 function template declaration or a function template definition, nor
5526 in the template-parameter-list of the definition of a member of a
5527 class template. */
5529 if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL
5530 || (TREE_CODE (decl) == FUNCTION_DECL && DECL_LOCAL_DECL_P (decl)))
5531 /* You can't have a function template declaration in a local
5532 scope, nor you can you define a member of a class template in a
5533 local scope. */
5534 return true;
5536 if ((TREE_CODE (decl) == TYPE_DECL
5537 && TREE_TYPE (decl)
5538 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5539 || (TREE_CODE (decl) == FUNCTION_DECL
5540 && LAMBDA_FUNCTION_P (decl)))
5541 /* A lambda doesn't have an explicit declaration; don't complain
5542 about the parms of the enclosing class. */
5543 return true;
5545 if (current_class_type
5546 && !TYPE_BEING_DEFINED (current_class_type)
5547 && DECL_LANG_SPECIFIC (decl)
5548 && DECL_DECLARES_FUNCTION_P (decl)
5549 /* If this is either a friend defined in the scope of the class
5550 or a member function. */
5551 && (DECL_FUNCTION_MEMBER_P (decl)
5552 ? same_type_p (DECL_CONTEXT (decl), current_class_type)
5553 : DECL_FRIEND_CONTEXT (decl)
5554 ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
5555 : false)
5556 /* And, if it was a member function, it really was defined in
5557 the scope of the class. */
5558 && (!DECL_FUNCTION_MEMBER_P (decl)
5559 || DECL_INITIALIZED_IN_CLASS_P (decl)))
5560 /* We already checked these parameters when the template was
5561 declared, so there's no need to do it again now. This function
5562 was defined in class scope, but we're processing its body now
5563 that the class is complete. */
5564 return true;
5566 /* Core issue 226 (C++0x only): the following only applies to class
5567 templates. */
5568 if (is_primary
5569 && ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL))
5571 /* [temp.param]
5573 If a template-parameter has a default template-argument, all
5574 subsequent template-parameters shall have a default
5575 template-argument supplied. */
5576 for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
5578 tree inner_parms = TREE_VALUE (parm_level);
5579 int ntparms = TREE_VEC_LENGTH (inner_parms);
5580 int seen_def_arg_p = 0;
5581 int i;
5583 for (i = 0; i < ntparms; ++i)
5585 tree parm = TREE_VEC_ELT (inner_parms, i);
5587 if (parm == error_mark_node)
5588 continue;
5590 if (TREE_PURPOSE (parm))
5591 seen_def_arg_p = 1;
5592 else if (seen_def_arg_p
5593 && !template_parameter_pack_p (TREE_VALUE (parm)))
5595 error ("no default argument for %qD", TREE_VALUE (parm));
5596 /* For better subsequent error-recovery, we indicate that
5597 there should have been a default argument. */
5598 TREE_PURPOSE (parm) = error_mark_node;
5599 no_errors = false;
5601 else if (!is_partial
5602 && !is_friend_decl
5603 /* Don't complain about an enclosing partial
5604 specialization. */
5605 && parm_level == parms
5606 && (TREE_CODE (decl) == TYPE_DECL || VAR_P (decl))
5607 && i < ntparms - 1
5608 && template_parameter_pack_p (TREE_VALUE (parm))
5609 /* A fixed parameter pack will be partially
5610 instantiated into a fixed length list. */
5611 && !fixed_parameter_pack_p (TREE_VALUE (parm)))
5613 /* A primary class template, primary variable template
5614 (DR 2032), or alias template can only have one
5615 parameter pack, at the end of the template
5616 parameter list. */
5618 error ("parameter pack %q+D must be at the end of the"
5619 " template parameter list", TREE_VALUE (parm));
5621 TREE_VALUE (TREE_VEC_ELT (inner_parms, i))
5622 = error_mark_node;
5623 no_errors = false;
5629 if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
5630 || is_partial
5631 || !is_primary
5632 || is_friend_decl)
5633 /* For an ordinary class template, default template arguments are
5634 allowed at the innermost level, e.g.:
5635 template <class T = int>
5636 struct S {};
5637 but, in a partial specialization, they're not allowed even
5638 there, as we have in [temp.class.spec]:
5640 The template parameter list of a specialization shall not
5641 contain default template argument values.
5643 So, for a partial specialization, or for a function template
5644 (in C++98/C++03), we look at all of them. */
5646 else
5647 /* But, for a primary class template that is not a partial
5648 specialization we look at all template parameters except the
5649 innermost ones. */
5650 parms = TREE_CHAIN (parms);
5652 /* Figure out what error message to issue. */
5653 if (is_friend_decl == 2)
5654 msg = G_("default template arguments may not be used in function template "
5655 "friend re-declaration");
5656 else if (is_friend_decl)
5657 msg = G_("default template arguments may not be used in template "
5658 "friend declarations");
5659 else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
5660 msg = G_("default template arguments may not be used in function templates "
5661 "without %<-std=c++11%> or %<-std=gnu++11%>");
5662 else if (is_partial)
5663 msg = G_("default template arguments may not be used in "
5664 "partial specializations");
5665 else if (current_class_type && CLASSTYPE_IS_TEMPLATE (current_class_type))
5666 msg = G_("default argument for template parameter for class enclosing %qD");
5667 else
5668 /* Per [temp.param]/9, "A default template-argument shall not be
5669 specified in the template-parameter-lists of the definition of
5670 a member of a class template that appears outside of the member's
5671 class.", thus if we aren't handling a member of a class template
5672 there is no need to examine the parameters. */
5673 return true;
5675 if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
5676 /* If we're inside a class definition, there's no need to
5677 examine the parameters to the class itself. On the one
5678 hand, they will be checked when the class is defined, and,
5679 on the other, default arguments are valid in things like:
5680 template <class T = double>
5681 struct S { template <class U> void f(U); };
5682 Here the default argument for `S' has no bearing on the
5683 declaration of `f'. */
5684 last_level_to_check = template_class_depth (current_class_type) + 1;
5685 else
5686 /* Check everything. */
5687 last_level_to_check = 0;
5689 for (parm_level = parms;
5690 parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
5691 parm_level = TREE_CHAIN (parm_level))
5693 tree inner_parms = TREE_VALUE (parm_level);
5694 int i;
5695 int ntparms;
5697 ntparms = TREE_VEC_LENGTH (inner_parms);
5698 for (i = 0; i < ntparms; ++i)
5700 if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
5701 continue;
5703 if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
5705 if (msg)
5707 no_errors = false;
5708 if (is_friend_decl == 2)
5709 return no_errors;
5711 error (msg, decl);
5712 msg = 0;
5715 /* Clear out the default argument so that we are not
5716 confused later. */
5717 TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
5721 /* At this point, if we're still interested in issuing messages,
5722 they must apply to classes surrounding the object declared. */
5723 if (msg)
5724 msg = G_("default argument for template parameter for class "
5725 "enclosing %qD");
5728 return no_errors;
5731 /* Worker for push_template_decl_real, called via
5732 for_each_template_parm. DATA is really an int, indicating the
5733 level of the parameters we are interested in. If T is a template
5734 parameter of that level, return nonzero. */
5736 static int
5737 template_parm_this_level_p (tree t, void* data)
5739 int this_level = *(int *)data;
5740 int level;
5742 if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5743 level = TEMPLATE_PARM_LEVEL (t);
5744 else
5745 level = TEMPLATE_TYPE_LEVEL (t);
5746 return level == this_level;
5749 /* Worker for uses_outer_template_parms, called via for_each_template_parm.
5750 DATA is really an int, indicating the innermost outer level of parameters.
5751 If T is a template parameter of that level or further out, return
5752 nonzero. */
5754 static int
5755 template_parm_outer_level (tree t, void *data)
5757 int this_level = *(int *)data;
5758 int level;
5760 if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5761 level = TEMPLATE_PARM_LEVEL (t);
5762 else
5763 level = TEMPLATE_TYPE_LEVEL (t);
5764 return level <= this_level;
5767 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
5768 parameters given by current_template_args, or reuses a
5769 previously existing one, if appropriate. Returns the DECL, or an
5770 equivalent one, if it is replaced via a call to duplicate_decls.
5772 If IS_FRIEND is true, DECL is a friend declaration. */
5774 tree
5775 push_template_decl (tree decl, bool is_friend)
5777 if (decl == error_mark_node || !current_template_parms)
5778 return error_mark_node;
5780 /* See if this is a partial specialization. */
5781 bool is_partial = ((DECL_IMPLICIT_TYPEDEF_P (decl)
5782 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
5783 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
5784 || (VAR_P (decl)
5785 && DECL_LANG_SPECIFIC (decl)
5786 && DECL_TEMPLATE_SPECIALIZATION (decl)
5787 && TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl))));
5789 /* No surprising friend functions. */
5790 gcc_checking_assert (is_friend
5791 || !(TREE_CODE (decl) == FUNCTION_DECL
5792 && DECL_UNIQUE_FRIEND_P (decl)));
5794 tree ctx;
5795 if (is_friend)
5796 /* For a friend, we want the context of the friend, not
5797 the type of which it is a friend. */
5798 ctx = CP_DECL_CONTEXT (decl);
5799 else if (CP_DECL_CONTEXT (decl)
5800 && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
5801 /* In the case of a virtual function, we want the class in which
5802 it is defined. */
5803 ctx = CP_DECL_CONTEXT (decl);
5804 else
5805 /* Otherwise, if we're currently defining some class, the DECL
5806 is assumed to be a member of the class. */
5807 ctx = current_scope ();
5809 if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
5810 ctx = NULL_TREE;
5812 if (!DECL_CONTEXT (decl))
5813 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5815 /* See if this is a primary template. */
5816 bool is_primary = false;
5817 if (is_friend && ctx
5818 && uses_template_parms_level (ctx, current_template_depth))
5819 /* A friend template that specifies a class context, i.e.
5820 template <typename T> friend void A<T>::f();
5821 is not primary. */
5823 else if (TREE_CODE (decl) == TYPE_DECL && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5824 /* Lambdas are not primary. */
5826 else
5827 is_primary = template_parm_scope_p ();
5829 /* True if the template is a member template, in the sense of
5830 [temp.mem]. */
5831 bool member_template_p = false;
5833 if (is_primary)
5835 warning (OPT_Wtemplates, "template %qD declared", decl);
5837 if (DECL_CLASS_SCOPE_P (decl))
5838 member_template_p = true;
5840 if (TREE_CODE (decl) == TYPE_DECL
5841 && IDENTIFIER_ANON_P (DECL_NAME (decl)))
5843 error ("template class without a name");
5844 return error_mark_node;
5846 else if (TREE_CODE (decl) == FUNCTION_DECL)
5848 if (member_template_p)
5850 if (DECL_OVERRIDE_P (decl) || DECL_FINAL_P (decl))
5851 error ("member template %qD may not have virt-specifiers", decl);
5853 if (DECL_DESTRUCTOR_P (decl))
5855 /* [temp.mem]
5857 A destructor shall not be a member template. */
5858 error_at (DECL_SOURCE_LOCATION (decl),
5859 "destructor %qD declared as member template", decl);
5860 return error_mark_node;
5862 if (IDENTIFIER_NEWDEL_OP_P (DECL_NAME (decl))
5863 && (!prototype_p (TREE_TYPE (decl))
5864 || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
5865 || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5866 || (TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5867 == void_list_node)))
5869 /* [basic.stc.dynamic.allocation]
5871 An allocation function can be a function
5872 template. ... Template allocation functions shall
5873 have two or more parameters. */
5874 error ("invalid template declaration of %qD", decl);
5875 return error_mark_node;
5878 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5879 && CLASS_TYPE_P (TREE_TYPE (decl)))
5880 /* Class template. */;
5881 else if (TREE_CODE (decl) == TYPE_DECL
5882 && TYPE_DECL_ALIAS_P (decl))
5883 /* alias-declaration */
5884 gcc_assert (!DECL_ARTIFICIAL (decl));
5885 else if (VAR_P (decl))
5886 /* C++14 variable template. */;
5887 else if (TREE_CODE (decl) == CONCEPT_DECL)
5888 /* C++20 concept definitions. */;
5889 else
5891 error ("template declaration of %q#D", decl);
5892 return error_mark_node;
5896 bool local_p = (!DECL_IMPLICIT_TYPEDEF_P (decl)
5897 && ((ctx && TREE_CODE (ctx) == FUNCTION_DECL)
5898 || (VAR_OR_FUNCTION_DECL_P (decl)
5899 && DECL_LOCAL_DECL_P (decl))));
5901 /* Check to see that the rules regarding the use of default
5902 arguments are not being violated. We check args for a friend
5903 functions when we know whether it's a definition, introducing
5904 declaration or re-declaration. */
5905 if (!local_p && (!is_friend || TREE_CODE (decl) != FUNCTION_DECL))
5906 check_default_tmpl_args (decl, current_template_parms,
5907 is_primary, is_partial, is_friend);
5909 /* Ensure that there are no parameter packs in the type of this
5910 declaration that have not been expanded. */
5911 if (TREE_CODE (decl) == FUNCTION_DECL)
5913 /* Check each of the arguments individually to see if there are
5914 any bare parameter packs. */
5915 tree type = TREE_TYPE (decl);
5916 tree arg = DECL_ARGUMENTS (decl);
5917 tree argtype = TYPE_ARG_TYPES (type);
5919 while (arg && argtype)
5921 if (!DECL_PACK_P (arg)
5922 && check_for_bare_parameter_packs (TREE_TYPE (arg)))
5924 /* This is a PARM_DECL that contains unexpanded parameter
5925 packs. We have already complained about this in the
5926 check_for_bare_parameter_packs call, so just replace
5927 these types with ERROR_MARK_NODE. */
5928 TREE_TYPE (arg) = error_mark_node;
5929 TREE_VALUE (argtype) = error_mark_node;
5932 arg = DECL_CHAIN (arg);
5933 argtype = TREE_CHAIN (argtype);
5936 /* Check for bare parameter packs in the return type and the
5937 exception specifiers. */
5938 if (check_for_bare_parameter_packs (TREE_TYPE (type)))
5939 /* Errors were already issued, set return type to int
5940 as the frontend doesn't expect error_mark_node as
5941 the return type. */
5942 TREE_TYPE (type) = integer_type_node;
5943 if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
5944 TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
5946 else
5948 if (check_for_bare_parameter_packs (is_typedef_decl (decl)
5949 ? DECL_ORIGINAL_TYPE (decl)
5950 : TREE_TYPE (decl)))
5952 TREE_TYPE (decl) = error_mark_node;
5953 return error_mark_node;
5956 if (is_partial && VAR_P (decl)
5957 && check_for_bare_parameter_packs (DECL_TI_ARGS (decl)))
5958 return error_mark_node;
5961 if (is_partial)
5962 return process_partial_specialization (decl);
5964 tree args = current_template_args ();
5965 tree tmpl = NULL_TREE;
5966 bool new_template_p = false;
5967 if (local_p)
5969 /* Does not get a template head. */
5970 tmpl = NULL_TREE;
5971 gcc_checking_assert (!is_primary);
5973 else if (!ctx
5974 || TREE_CODE (ctx) == FUNCTION_DECL
5975 || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
5976 || (TREE_CODE (decl) == TYPE_DECL && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5977 || (is_friend && !(DECL_LANG_SPECIFIC (decl)
5978 && DECL_TEMPLATE_INFO (decl))))
5980 if (DECL_LANG_SPECIFIC (decl)
5981 && DECL_TEMPLATE_INFO (decl)
5982 && DECL_TI_TEMPLATE (decl))
5983 tmpl = DECL_TI_TEMPLATE (decl);
5984 /* If DECL is a TYPE_DECL for a class-template, then there won't
5985 be DECL_LANG_SPECIFIC. The information equivalent to
5986 DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead. */
5987 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5988 && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
5989 && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
5991 /* Since a template declaration already existed for this
5992 class-type, we must be redeclaring it here. Make sure
5993 that the redeclaration is valid. */
5994 redeclare_class_template (TREE_TYPE (decl),
5995 current_template_parms,
5996 current_template_constraints ());
5997 /* We don't need to create a new TEMPLATE_DECL; just use the
5998 one we already had. */
5999 tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
6001 else
6003 tmpl = build_template_decl (decl, current_template_parms,
6004 member_template_p);
6005 new_template_p = true;
6007 if (DECL_LANG_SPECIFIC (decl)
6008 && DECL_TEMPLATE_SPECIALIZATION (decl))
6010 /* A specialization of a member template of a template
6011 class. */
6012 SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
6013 DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
6014 DECL_TEMPLATE_INFO (decl) = NULL_TREE;
6018 else
6020 tree a, t, current, parms;
6021 int i;
6022 tree tinfo = get_template_info (decl);
6024 if (!tinfo)
6026 error ("template definition of non-template %q#D", decl);
6027 return error_mark_node;
6030 tmpl = TI_TEMPLATE (tinfo);
6032 if (DECL_FUNCTION_TEMPLATE_P (tmpl)
6033 && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
6034 && DECL_TEMPLATE_SPECIALIZATION (decl)
6035 && DECL_MEMBER_TEMPLATE_P (tmpl))
6037 /* The declaration is a specialization of a member
6038 template, declared outside the class. Therefore, the
6039 innermost template arguments will be NULL, so we
6040 replace them with the arguments determined by the
6041 earlier call to check_explicit_specialization. */
6042 args = DECL_TI_ARGS (decl);
6044 tree new_tmpl
6045 = build_template_decl (decl, current_template_parms,
6046 member_template_p);
6047 DECL_TI_TEMPLATE (decl) = new_tmpl;
6048 SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
6049 DECL_TEMPLATE_INFO (new_tmpl)
6050 = build_template_info (tmpl, args);
6052 register_specialization (new_tmpl,
6053 most_general_template (tmpl),
6054 args,
6055 is_friend, 0);
6056 return decl;
6059 /* Make sure the template headers we got make sense. */
6061 parms = DECL_TEMPLATE_PARMS (tmpl);
6062 i = TMPL_PARMS_DEPTH (parms);
6063 if (TMPL_ARGS_DEPTH (args) != i)
6065 error ("expected %d levels of template parms for %q#D, got %d",
6066 i, decl, TMPL_ARGS_DEPTH (args));
6067 DECL_INTERFACE_KNOWN (decl) = 1;
6068 return error_mark_node;
6070 else
6071 for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
6073 a = TMPL_ARGS_LEVEL (args, i);
6074 t = INNERMOST_TEMPLATE_PARMS (parms);
6076 if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
6078 if (current == decl)
6079 error ("got %d template parameters for %q#D",
6080 TREE_VEC_LENGTH (a), decl);
6081 else
6082 error ("got %d template parameters for %q#T",
6083 TREE_VEC_LENGTH (a), current);
6084 error (" but %d required", TREE_VEC_LENGTH (t));
6085 /* Avoid crash in import_export_decl. */
6086 DECL_INTERFACE_KNOWN (decl) = 1;
6087 return error_mark_node;
6090 if (current == decl)
6091 current = ctx;
6092 else if (current == NULL_TREE)
6093 /* Can happen in erroneous input. */
6094 break;
6095 else
6096 current = get_containing_scope (current);
6099 /* Check that the parms are used in the appropriate qualifying scopes
6100 in the declarator. */
6101 if (!comp_template_args
6102 (TI_ARGS (tinfo),
6103 TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
6105 error ("template arguments to %qD do not match original "
6106 "template %qD", decl, DECL_TEMPLATE_RESULT (tmpl));
6107 if (!uses_template_parms (TI_ARGS (tinfo)))
6108 inform (input_location, "use %<template<>%> for"
6109 " an explicit specialization");
6110 /* Avoid crash in import_export_decl. */
6111 DECL_INTERFACE_KNOWN (decl) = 1;
6112 return error_mark_node;
6116 gcc_checking_assert (!tmpl || DECL_TEMPLATE_RESULT (tmpl) == decl);
6118 if (new_template_p)
6120 /* Push template declarations for global functions and types.
6121 Note that we do not try to push a global template friend
6122 declared in a template class; such a thing may well depend on
6123 the template parameters of the class and we'll push it when
6124 instantiating the befriending class. */
6125 if (!ctx
6126 && !(is_friend && template_class_depth (current_class_type) > 0))
6128 tree pushed = pushdecl_namespace_level (tmpl, /*hiding=*/is_friend);
6129 if (pushed == error_mark_node)
6130 return error_mark_node;
6132 /* pushdecl may have found an existing template. */
6133 if (pushed != tmpl)
6135 decl = DECL_TEMPLATE_RESULT (pushed);
6136 tmpl = NULL_TREE;
6139 else if (is_friend)
6141 /* Record this decl as belonging to the current class. It's
6142 not chained onto anything else. */
6143 DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (tmpl) = true;
6144 gcc_checking_assert (!DECL_CHAIN (tmpl));
6145 DECL_CHAIN (tmpl) = current_scope ();
6148 else if (tmpl)
6149 /* The type may have been completed, or (erroneously) changed. */
6150 TREE_TYPE (tmpl) = TREE_TYPE (decl);
6152 if (tmpl)
6154 if (is_primary)
6156 tree parms = DECL_TEMPLATE_PARMS (tmpl);
6158 DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
6160 /* Give template template parms a DECL_CONTEXT of the template
6161 for which they are a parameter. */
6162 parms = INNERMOST_TEMPLATE_PARMS (parms);
6163 for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
6165 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
6166 if (TREE_CODE (parm) == TEMPLATE_DECL)
6167 DECL_CONTEXT (parm) = tmpl;
6170 if (TREE_CODE (decl) == TYPE_DECL
6171 && TYPE_DECL_ALIAS_P (decl))
6173 if (tree constr
6174 = TEMPLATE_PARMS_CONSTRAINTS (DECL_TEMPLATE_PARMS (tmpl)))
6176 /* ??? Why don't we do this here for all templates? */
6177 constr = build_constraints (constr, NULL_TREE);
6178 set_constraints (decl, constr);
6180 if (complex_alias_template_p (tmpl))
6181 TEMPLATE_DECL_COMPLEX_ALIAS_P (tmpl) = true;
6185 /* The DECL_TI_ARGS of DECL contains full set of arguments
6186 referring wback to its most general template. If TMPL is a
6187 specialization, ARGS may only have the innermost set of
6188 arguments. Add the missing argument levels if necessary. */
6189 if (DECL_TEMPLATE_INFO (tmpl))
6190 args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
6192 tree info = build_template_info (tmpl, args);
6194 if (DECL_IMPLICIT_TYPEDEF_P (decl))
6195 SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
6196 else
6198 retrofit_lang_decl (decl);
6199 DECL_TEMPLATE_INFO (decl) = info;
6203 if (flag_implicit_templates
6204 && !is_friend
6205 && TREE_PUBLIC (decl)
6206 && VAR_OR_FUNCTION_DECL_P (decl))
6207 /* Set DECL_COMDAT on template instantiations; if we force
6208 them to be emitted by explicit instantiation,
6209 mark_needed will tell cgraph to do the right thing. */
6210 DECL_COMDAT (decl) = true;
6212 gcc_checking_assert (!tmpl || DECL_TEMPLATE_RESULT (tmpl) == decl);
6214 return decl;
6217 /* FN is an inheriting constructor that inherits from the constructor
6218 template INHERITED; turn FN into a constructor template with a matching
6219 template header. */
6221 tree
6222 add_inherited_template_parms (tree fn, tree inherited)
6224 tree inner_parms
6225 = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (inherited));
6226 inner_parms = copy_node (inner_parms);
6227 tree parms
6228 = tree_cons (size_int (current_template_depth + 1),
6229 inner_parms, current_template_parms);
6230 tree tmpl = build_template_decl (fn, parms, /*member*/true);
6231 tree args = template_parms_to_args (parms);
6232 DECL_TEMPLATE_INFO (fn) = build_template_info (tmpl, args);
6233 DECL_ARTIFICIAL (tmpl) = true;
6234 DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
6235 return tmpl;
6238 /* Called when a class template TYPE is redeclared with the indicated
6239 template PARMS, e.g.:
6241 template <class T> struct S;
6242 template <class T> struct S {}; */
6244 bool
6245 redeclare_class_template (tree type, tree parms, tree cons)
6247 tree tmpl;
6248 tree tmpl_parms;
6249 int i;
6251 if (!TYPE_TEMPLATE_INFO (type))
6253 error ("%qT is not a template type", type);
6254 return false;
6257 tmpl = TYPE_TI_TEMPLATE (type);
6258 if (!PRIMARY_TEMPLATE_P (tmpl))
6259 /* The type is nested in some template class. Nothing to worry
6260 about here; there are no new template parameters for the nested
6261 type. */
6262 return true;
6264 if (!parms)
6266 error ("template specifiers not specified in declaration of %qD",
6267 tmpl);
6268 return false;
6271 parms = INNERMOST_TEMPLATE_PARMS (parms);
6272 tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
6274 if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
6276 error_n (input_location, TREE_VEC_LENGTH (parms),
6277 "redeclared with %d template parameter",
6278 "redeclared with %d template parameters",
6279 TREE_VEC_LENGTH (parms));
6280 inform_n (DECL_SOURCE_LOCATION (tmpl), TREE_VEC_LENGTH (tmpl_parms),
6281 "previous declaration %qD used %d template parameter",
6282 "previous declaration %qD used %d template parameters",
6283 tmpl, TREE_VEC_LENGTH (tmpl_parms));
6284 return false;
6287 for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
6289 tree tmpl_parm;
6290 tree parm;
6292 if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
6293 || TREE_VEC_ELT (parms, i) == error_mark_node)
6294 continue;
6296 tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
6297 if (error_operand_p (tmpl_parm))
6298 return false;
6300 parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
6302 /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
6303 TEMPLATE_DECL. */
6304 if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
6305 || (TREE_CODE (tmpl_parm) != TYPE_DECL
6306 && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
6307 || (TREE_CODE (tmpl_parm) != PARM_DECL
6308 && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
6309 != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
6310 || (TREE_CODE (tmpl_parm) == PARM_DECL
6311 && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
6312 != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
6314 auto_diagnostic_group d;
6315 error ("template parameter %q+#D", tmpl_parm);
6316 if (DECL_P (parm))
6317 inform (DECL_SOURCE_LOCATION (parm), "redeclared here as %q#D", parm);
6318 else
6319 inform (input_location, "redeclared here");
6320 return false;
6323 /* The parameters can be declared to introduce different
6324 constraints. */
6325 tree p1 = TREE_VEC_ELT (tmpl_parms, i);
6326 tree p2 = TREE_VEC_ELT (parms, i);
6327 if (!template_parameter_constraints_equivalent_p (p1, p2))
6329 auto_diagnostic_group d;
6330 error ("declaration of template parameter %q+#D with different "
6331 "constraints", parm);
6332 inform (DECL_SOURCE_LOCATION (tmpl_parm),
6333 "original declaration appeared here");
6334 return false;
6337 /* Give each template template parm in this redeclaration a
6338 DECL_CONTEXT of the template for which they are a parameter. */
6339 if (TREE_CODE (parm) == TEMPLATE_DECL)
6341 gcc_assert (DECL_CONTEXT (parm) == NULL_TREE);
6342 DECL_CONTEXT (parm) = tmpl;
6346 if (!merge_default_template_args (parms, tmpl_parms, /*class_p=*/true))
6347 return false;
6349 tree ci = get_constraints (tmpl);
6350 tree req1 = ci ? CI_TEMPLATE_REQS (ci) : NULL_TREE;
6351 tree req2 = cons ? CI_TEMPLATE_REQS (cons) : NULL_TREE;
6353 /* Two classes with different constraints declare different entities. */
6354 if (!cp_tree_equal (req1, req2))
6356 auto_diagnostic_group d;
6357 error_at (input_location, "redeclaration %q#D with different "
6358 "constraints", tmpl);
6359 inform (DECL_SOURCE_LOCATION (tmpl),
6360 "original declaration appeared here");
6361 return false;
6364 return true;
6367 /* The actual substitution part of instantiate_non_dependent_expr,
6368 to be used when the caller has already checked
6369 !instantiation_dependent_uneval_expression_p (expr)
6370 and cleared processing_template_decl. */
6372 tree
6373 instantiate_non_dependent_expr_internal (tree expr, tsubst_flags_t complain)
6375 return tsubst_copy_and_build (expr,
6376 /*args=*/NULL_TREE,
6377 complain,
6378 /*in_decl=*/NULL_TREE);
6381 /* Instantiate the non-dependent expression EXPR. */
6383 tree
6384 instantiate_non_dependent_expr (tree expr,
6385 tsubst_flags_t complain /* = tf_error */)
6387 if (expr == NULL_TREE)
6388 return NULL_TREE;
6390 if (processing_template_decl)
6392 /* The caller should have checked this already. */
6393 gcc_checking_assert (!instantiation_dependent_uneval_expression_p (expr));
6394 processing_template_decl_sentinel s;
6395 expr = instantiate_non_dependent_expr_internal (expr, complain);
6397 return expr;
6400 /* Like instantiate_non_dependent_expr, but return NULL_TREE if the
6401 expression is dependent or non-constant. */
6403 tree
6404 instantiate_non_dependent_or_null (tree expr)
6406 if (expr == NULL_TREE)
6407 return NULL_TREE;
6408 if (processing_template_decl)
6410 if (!is_nondependent_constant_expression (expr))
6411 expr = NULL_TREE;
6412 else
6414 processing_template_decl_sentinel s;
6415 expr = instantiate_non_dependent_expr_internal (expr, tf_error);
6418 return expr;
6421 /* True iff T is a specialization of a variable template. */
6423 bool
6424 variable_template_specialization_p (tree t)
6426 if (!VAR_P (t) || !DECL_LANG_SPECIFIC (t) || !DECL_TEMPLATE_INFO (t))
6427 return false;
6428 tree tmpl = DECL_TI_TEMPLATE (t);
6429 return variable_template_p (tmpl);
6432 /* Return TRUE iff T is a type alias, a TEMPLATE_DECL for an alias
6433 template declaration, or a TYPE_DECL for an alias declaration. */
6435 bool
6436 alias_type_or_template_p (tree t)
6438 if (t == NULL_TREE)
6439 return false;
6440 return ((TREE_CODE (t) == TYPE_DECL && TYPE_DECL_ALIAS_P (t))
6441 || (TYPE_P (t)
6442 && TYPE_NAME (t)
6443 && TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
6444 || DECL_ALIAS_TEMPLATE_P (t));
6447 /* If T is a specialization of an alias template, return it; otherwise return
6448 NULL_TREE. If TRANSPARENT_TYPEDEFS is true, look through other aliases. */
6450 tree
6451 alias_template_specialization_p (const_tree t,
6452 bool transparent_typedefs)
6454 if (!TYPE_P (t))
6455 return NULL_TREE;
6457 /* It's an alias template specialization if it's an alias and its
6458 TYPE_NAME is a specialization of a primary template. */
6459 if (typedef_variant_p (t))
6461 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
6462 if (PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo)))
6463 return CONST_CAST_TREE (t);
6464 if (transparent_typedefs)
6465 return alias_template_specialization_p (DECL_ORIGINAL_TYPE
6466 (TYPE_NAME (t)),
6467 transparent_typedefs);
6470 return NULL_TREE;
6473 /* Data structure for complex_alias_template_*. */
6475 struct uses_all_template_parms_data
6477 int level;
6478 bool *seen;
6481 /* walk_tree callback for complex_alias_template_p. */
6483 static tree
6484 complex_alias_template_r (tree *tp, int *walk_subtrees, void *data_)
6486 tree t = *tp;
6487 auto &data = *(struct uses_all_template_parms_data*)data_;
6489 switch (TREE_CODE (t))
6491 case TEMPLATE_TYPE_PARM:
6492 case TEMPLATE_PARM_INDEX:
6493 case TEMPLATE_TEMPLATE_PARM:
6494 case BOUND_TEMPLATE_TEMPLATE_PARM:
6496 tree idx = get_template_parm_index (t);
6497 if (TEMPLATE_PARM_LEVEL (idx) == data.level)
6498 data.seen[TEMPLATE_PARM_IDX (idx)] = true;
6501 default:;
6504 if (!PACK_EXPANSION_P (t))
6505 return 0;
6507 /* An alias template with a pack expansion that expands a pack from the
6508 enclosing class needs to be considered complex, to avoid confusion with
6509 the same pack being used as an argument to the alias's own template
6510 parameter (91966). */
6511 for (tree pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
6512 pack = TREE_CHAIN (pack))
6514 tree parm_pack = TREE_VALUE (pack);
6515 if (!TEMPLATE_PARM_P (parm_pack))
6516 continue;
6517 int idx, level;
6518 template_parm_level_and_index (parm_pack, &level, &idx);
6519 if (level < data.level)
6520 return t;
6522 /* Consider the expanded packs to be used outside the expansion... */
6523 data.seen[idx] = true;
6526 /* ...but don't walk into the pattern. Consider PR104008:
6528 template <typename T, typename... Ts>
6529 using IsOneOf = disjunction<is_same<T, Ts>...>;
6531 where IsOneOf seemingly uses all of its template parameters in its
6532 expansion (and does not expand a pack from the enclosing class), so the
6533 alias was not marked as complex. However, if it is used like
6534 "IsOneOf<T>", the empty pack for Ts means that T no longer appears in the
6535 expansion. So only Ts is considered used by the pack expansion. */
6536 *walk_subtrees = false;
6538 return 0;
6541 /* An alias template is complex from a SFINAE perspective if a template-id
6542 using that alias can be ill-formed when the expansion is not, as with
6543 the void_t template.
6545 Returns 1 if always complex, 0 if not complex, -1 if complex iff any of the
6546 template arguments are empty packs. */
6548 static bool
6549 complex_alias_template_p (const_tree tmpl)
6551 /* A renaming alias isn't complex. */
6552 if (get_underlying_template (CONST_CAST_TREE (tmpl)) != tmpl)
6553 return false;
6555 /* Any other constrained alias is complex. */
6556 if (get_constraints (tmpl))
6557 return true;
6559 struct uses_all_template_parms_data data;
6560 tree pat = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6561 tree parms = DECL_TEMPLATE_PARMS (tmpl);
6562 data.level = TMPL_PARMS_DEPTH (parms);
6563 int len = TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS (parms));
6564 data.seen = XALLOCAVEC (bool, len);
6565 for (int i = 0; i < len; ++i)
6566 data.seen[i] = false;
6568 if (cp_walk_tree_without_duplicates (&pat, complex_alias_template_r, &data))
6569 return true;
6570 for (int i = 0; i < len; ++i)
6571 if (!data.seen[i])
6572 return true;
6573 return false;
6576 /* If T is a specialization of a complex alias template with dependent
6577 template-arguments, return it; otherwise return NULL_TREE. If T is a
6578 typedef to such a specialization, return the specialization. */
6580 tree
6581 dependent_alias_template_spec_p (const_tree t, bool transparent_typedefs)
6583 if (t == error_mark_node)
6584 return NULL_TREE;
6585 gcc_assert (TYPE_P (t));
6587 if (!typedef_variant_p (t))
6588 return NULL_TREE;
6590 tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t);
6591 if (tinfo
6592 && TEMPLATE_DECL_COMPLEX_ALIAS_P (TI_TEMPLATE (tinfo))
6593 && (any_dependent_template_arguments_p
6594 (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)))))
6595 return CONST_CAST_TREE (t);
6597 if (transparent_typedefs)
6599 tree utype = DECL_ORIGINAL_TYPE (TYPE_NAME (t));
6600 return dependent_alias_template_spec_p (utype, transparent_typedefs);
6603 return NULL_TREE;
6606 /* Return the number of innermost template parameters in TMPL. */
6608 static int
6609 num_innermost_template_parms (const_tree tmpl)
6611 tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
6612 return TREE_VEC_LENGTH (parms);
6615 /* Return either TMPL or another template that it is equivalent to under DR
6616 1286: An alias that just changes the name of a template is equivalent to
6617 the other template. */
6619 static tree
6620 get_underlying_template (tree tmpl)
6622 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
6623 while (DECL_ALIAS_TEMPLATE_P (tmpl))
6625 /* Determine if the alias is equivalent to an underlying template. */
6626 tree orig_type = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6627 /* The underlying type may have been ill-formed. Don't proceed. */
6628 if (!orig_type)
6629 break;
6630 tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (orig_type);
6631 if (!tinfo)
6632 break;
6634 tree underlying = TI_TEMPLATE (tinfo);
6635 if (!PRIMARY_TEMPLATE_P (underlying)
6636 || (num_innermost_template_parms (tmpl)
6637 != num_innermost_template_parms (underlying)))
6638 break;
6640 /* Does the alias add cv-quals? */
6641 if (TYPE_QUALS (TREE_TYPE (underlying)) != TYPE_QUALS (TREE_TYPE (tmpl)))
6642 break;
6644 tree alias_args = INNERMOST_TEMPLATE_ARGS (generic_targs_for (tmpl));
6645 if (!comp_template_args (TI_ARGS (tinfo), alias_args))
6646 break;
6648 /* Are any default template arguments equivalent? */
6649 tree aparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
6650 tree uparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (underlying));
6651 const int nparms = TREE_VEC_LENGTH (aparms);
6652 for (int i = 0; i < nparms; ++i)
6654 tree adefarg = TREE_PURPOSE (TREE_VEC_ELT (aparms, i));
6655 tree udefarg = TREE_PURPOSE (TREE_VEC_ELT (uparms, i));
6656 if (!template_args_equal (adefarg, udefarg))
6657 goto top_break;
6660 /* If TMPL adds or changes any constraints, it isn't equivalent. I think
6661 it's appropriate to treat a less-constrained alias as equivalent. */
6662 if (!at_least_as_constrained (underlying, tmpl))
6663 break;
6665 /* Alias is equivalent. Strip it and repeat. */
6666 tmpl = underlying;
6668 top_break:;
6670 return tmpl;
6673 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
6674 must be a reference-to-function or a pointer-to-function type, as specified
6675 in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
6676 and check that the resulting function has external linkage. */
6678 static tree
6679 convert_nontype_argument_function (tree type, tree expr,
6680 tsubst_flags_t complain)
6682 tree fns = expr;
6683 tree fn, fn_no_ptr;
6684 linkage_kind linkage;
6686 fn = instantiate_type (type, fns, tf_none);
6687 if (fn == error_mark_node)
6688 return error_mark_node;
6690 if (value_dependent_expression_p (fn))
6691 goto accept;
6693 fn_no_ptr = fn;
6694 if (REFERENCE_REF_P (fn_no_ptr))
6695 fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
6696 fn_no_ptr = strip_fnptr_conv (fn_no_ptr);
6697 if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
6698 fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
6699 if (BASELINK_P (fn_no_ptr))
6700 fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
6702 /* [temp.arg.nontype]/1
6704 A template-argument for a non-type, non-template template-parameter
6705 shall be one of:
6706 [...]
6707 -- the address of an object or function with external [C++11: or
6708 internal] linkage. */
6710 STRIP_ANY_LOCATION_WRAPPER (fn_no_ptr);
6711 if (TREE_CODE (fn_no_ptr) != FUNCTION_DECL)
6713 if (complain & tf_error)
6715 location_t loc = cp_expr_loc_or_input_loc (expr);
6716 error_at (loc, "%qE is not a valid template argument for type %qT",
6717 expr, type);
6718 if (TYPE_PTR_P (type))
6719 inform (loc, "it must be the address of a function "
6720 "with external linkage");
6721 else
6722 inform (loc, "it must be the name of a function with "
6723 "external linkage");
6725 return NULL_TREE;
6728 linkage = decl_linkage (fn_no_ptr);
6729 if (cxx_dialect >= cxx11 ? linkage == lk_none : linkage != lk_external)
6731 if (complain & tf_error)
6733 location_t loc = cp_expr_loc_or_input_loc (expr);
6734 if (cxx_dialect >= cxx11)
6735 error_at (loc, "%qE is not a valid template argument for type "
6736 "%qT because %qD has no linkage",
6737 expr, type, fn_no_ptr);
6738 else
6739 error_at (loc, "%qE is not a valid template argument for type "
6740 "%qT because %qD does not have external linkage",
6741 expr, type, fn_no_ptr);
6743 return NULL_TREE;
6746 accept:
6747 if (TYPE_REF_P (type))
6749 if (REFERENCE_REF_P (fn))
6750 fn = TREE_OPERAND (fn, 0);
6751 else
6752 fn = build_address (fn);
6754 if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (fn)))
6755 fn = build_nop (type, fn);
6757 return fn;
6760 /* Subroutine of convert_nontype_argument.
6761 Check if EXPR of type TYPE is a valid pointer-to-member constant.
6762 Emit an error otherwise. */
6764 static bool
6765 check_valid_ptrmem_cst_expr (tree type, tree expr,
6766 tsubst_flags_t complain)
6768 tree orig_expr = expr;
6769 STRIP_NOPS (expr);
6770 if (null_ptr_cst_p (expr))
6771 return true;
6772 if (TREE_CODE (expr) == PTRMEM_CST
6773 && same_type_p (TYPE_PTRMEM_CLASS_TYPE (type),
6774 PTRMEM_CST_CLASS (expr)))
6775 return true;
6776 if (cxx_dialect >= cxx11 && null_member_pointer_value_p (expr))
6777 return true;
6778 if (processing_template_decl
6779 && TREE_CODE (expr) == ADDR_EXPR
6780 && TREE_CODE (TREE_OPERAND (expr, 0)) == OFFSET_REF)
6781 return true;
6782 if (complain & tf_error)
6784 location_t loc = cp_expr_loc_or_input_loc (orig_expr);
6785 error_at (loc, "%qE is not a valid template argument for type %qT",
6786 orig_expr, type);
6787 if (TREE_CODE (expr) != PTRMEM_CST)
6788 inform (loc, "it must be a pointer-to-member of the form %<&X::Y%>");
6789 else
6790 inform (loc, "because it is a member of %qT", PTRMEM_CST_CLASS (expr));
6792 return false;
6795 /* Returns TRUE iff the address of OP is value-dependent.
6797 14.6.2.4 [temp.dep.temp]:
6798 A non-integral non-type template-argument is dependent if its type is
6799 dependent or it has either of the following forms
6800 qualified-id
6801 & qualified-id
6802 and contains a nested-name-specifier which specifies a class-name that
6803 names a dependent type.
6805 We generalize this to just say that the address of a member of a
6806 dependent class is value-dependent; the above doesn't cover the
6807 address of a static data member named with an unqualified-id. */
6809 static bool
6810 has_value_dependent_address (tree op)
6812 STRIP_ANY_LOCATION_WRAPPER (op);
6814 /* We could use get_inner_reference here, but there's no need;
6815 this is only relevant for template non-type arguments, which
6816 can only be expressed as &id-expression. */
6817 if (DECL_P (op))
6819 tree ctx = CP_DECL_CONTEXT (op);
6821 if (TYPE_P (ctx) && dependent_type_p (ctx))
6822 return true;
6824 if (VAR_P (op)
6825 && TREE_STATIC (op)
6826 && TREE_CODE (ctx) == FUNCTION_DECL
6827 && type_dependent_expression_p (ctx))
6828 return true;
6831 return false;
6834 /* The next set of functions are used for providing helpful explanatory
6835 diagnostics for failed overload resolution. Their messages should be
6836 indented by two spaces for consistency with the messages in
6837 call.cc */
6839 static int
6840 unify_success (bool /*explain_p*/)
6842 return 0;
6845 /* Other failure functions should call this one, to provide a single function
6846 for setting a breakpoint on. */
6848 static int
6849 unify_invalid (bool /*explain_p*/)
6851 return 1;
6854 static int
6855 unify_parameter_deduction_failure (bool explain_p, tree parm)
6857 if (explain_p)
6858 inform (input_location,
6859 " couldn%'t deduce template parameter %qD", parm);
6860 return unify_invalid (explain_p);
6863 static int
6864 unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
6866 if (explain_p)
6867 inform (input_location,
6868 " types %qT and %qT have incompatible cv-qualifiers",
6869 parm, arg);
6870 return unify_invalid (explain_p);
6873 static int
6874 unify_type_mismatch (bool explain_p, tree parm, tree arg)
6876 if (explain_p)
6877 inform (input_location, " mismatched types %qT and %qT", parm, arg);
6878 return unify_invalid (explain_p);
6881 static int
6882 unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
6884 if (explain_p)
6885 inform (input_location,
6886 " template parameter %qD is not a parameter pack, but "
6887 "argument %qD is",
6888 parm, arg);
6889 return unify_invalid (explain_p);
6892 static int
6893 unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
6895 if (explain_p)
6896 inform (input_location,
6897 " template argument %qE does not match "
6898 "pointer-to-member constant %qE",
6899 arg, parm);
6900 return unify_invalid (explain_p);
6903 static int
6904 unify_expression_unequal (bool explain_p, tree parm, tree arg)
6906 if (explain_p)
6907 inform (input_location, " %qE is not equivalent to %qE", parm, arg);
6908 return unify_invalid (explain_p);
6911 static int
6912 unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
6914 if (explain_p)
6915 inform (input_location,
6916 " inconsistent parameter pack deduction with %qT and %qT",
6917 old_arg, new_arg);
6918 return unify_invalid (explain_p);
6921 static int
6922 unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
6924 if (explain_p)
6926 if (TYPE_P (parm))
6927 inform (input_location,
6928 " deduced conflicting types for parameter %qT (%qT and %qT)",
6929 parm, first, second);
6930 else
6931 inform (input_location,
6932 " deduced conflicting values for non-type parameter "
6933 "%qE (%qE and %qE)", parm, first, second);
6935 return unify_invalid (explain_p);
6938 static int
6939 unify_vla_arg (bool explain_p, tree arg)
6941 if (explain_p)
6942 inform (input_location,
6943 " variable-sized array type %qT is not "
6944 "a valid template argument",
6945 arg);
6946 return unify_invalid (explain_p);
6949 static int
6950 unify_method_type_error (bool explain_p, tree arg)
6952 if (explain_p)
6953 inform (input_location,
6954 " member function type %qT is not a valid template argument",
6955 arg);
6956 return unify_invalid (explain_p);
6959 static int
6960 unify_arity (bool explain_p, int have, int wanted, bool least_p = false)
6962 if (explain_p)
6964 if (least_p)
6965 inform_n (input_location, wanted,
6966 " candidate expects at least %d argument, %d provided",
6967 " candidate expects at least %d arguments, %d provided",
6968 wanted, have);
6969 else
6970 inform_n (input_location, wanted,
6971 " candidate expects %d argument, %d provided",
6972 " candidate expects %d arguments, %d provided",
6973 wanted, have);
6975 return unify_invalid (explain_p);
6978 static int
6979 unify_too_many_arguments (bool explain_p, int have, int wanted)
6981 return unify_arity (explain_p, have, wanted);
6984 static int
6985 unify_too_few_arguments (bool explain_p, int have, int wanted,
6986 bool least_p = false)
6988 return unify_arity (explain_p, have, wanted, least_p);
6991 static int
6992 unify_arg_conversion (bool explain_p, tree to_type,
6993 tree from_type, tree arg)
6995 if (explain_p)
6996 inform (cp_expr_loc_or_input_loc (arg),
6997 " cannot convert %qE (type %qT) to type %qT",
6998 arg, from_type, to_type);
6999 return unify_invalid (explain_p);
7002 static int
7003 unify_no_common_base (bool explain_p, enum template_base_result r,
7004 tree parm, tree arg)
7006 if (explain_p)
7007 switch (r)
7009 case tbr_ambiguous_baseclass:
7010 inform (input_location, " %qT is an ambiguous base class of %qT",
7011 parm, arg);
7012 break;
7013 default:
7014 inform (input_location, " %qT is not derived from %qT", arg, parm);
7015 break;
7017 return unify_invalid (explain_p);
7020 static int
7021 unify_inconsistent_template_template_parameters (bool explain_p)
7023 if (explain_p)
7024 inform (input_location,
7025 " template parameters of a template template argument are "
7026 "inconsistent with other deduced template arguments");
7027 return unify_invalid (explain_p);
7030 static int
7031 unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
7033 if (explain_p)
7034 inform (input_location,
7035 " cannot deduce a template for %qT from non-template type %qT",
7036 parm, arg);
7037 return unify_invalid (explain_p);
7040 static int
7041 unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
7043 if (explain_p)
7044 inform (input_location,
7045 " template argument %qE does not match %qE", arg, parm);
7046 return unify_invalid (explain_p);
7049 /* Subroutine of convert_nontype_argument, to check whether EXPR, as an
7050 argument for TYPE, points to an unsuitable object.
7052 Also adjust the type of the index in C++20 array subobject references. */
7054 static bool
7055 invalid_tparm_referent_p (tree type, tree expr, tsubst_flags_t complain)
7057 switch (TREE_CODE (expr))
7059 CASE_CONVERT:
7060 return invalid_tparm_referent_p (type, TREE_OPERAND (expr, 0),
7061 complain);
7063 case TARGET_EXPR:
7064 return invalid_tparm_referent_p (type, TARGET_EXPR_INITIAL (expr),
7065 complain);
7067 case CONSTRUCTOR:
7069 for (auto &e: CONSTRUCTOR_ELTS (expr))
7070 if (invalid_tparm_referent_p (TREE_TYPE (e.value), e.value, complain))
7071 return true;
7073 break;
7075 case ADDR_EXPR:
7077 tree decl = TREE_OPERAND (expr, 0);
7079 if (cxx_dialect >= cxx20)
7080 while (TREE_CODE (decl) == COMPONENT_REF
7081 || TREE_CODE (decl) == ARRAY_REF)
7083 tree &op = TREE_OPERAND (decl, 1);
7084 if (TREE_CODE (decl) == ARRAY_REF
7085 && TREE_CODE (op) == INTEGER_CST)
7086 /* Canonicalize array offsets to ptrdiff_t; how they were
7087 written doesn't matter for subobject identity. */
7088 op = fold_convert (ptrdiff_type_node, op);
7089 decl = TREE_OPERAND (decl, 0);
7092 if (!VAR_P (decl))
7094 if (complain & tf_error)
7095 error_at (cp_expr_loc_or_input_loc (expr),
7096 "%qE is not a valid template argument of type %qT "
7097 "because %qE is not a variable", expr, type, decl);
7098 return true;
7100 else if (cxx_dialect < cxx11 && !DECL_EXTERNAL_LINKAGE_P (decl))
7102 if (complain & tf_error)
7103 error_at (cp_expr_loc_or_input_loc (expr),
7104 "%qE is not a valid template argument of type %qT "
7105 "in C++98 because %qD does not have external linkage",
7106 expr, type, decl);
7107 return true;
7109 else if ((cxx_dialect >= cxx11 && cxx_dialect < cxx17)
7110 && decl_linkage (decl) == lk_none)
7112 if (complain & tf_error)
7113 error_at (cp_expr_loc_or_input_loc (expr),
7114 "%qE is not a valid template argument of type %qT "
7115 "because %qD has no linkage", expr, type, decl);
7116 return true;
7118 /* C++17: For a non-type template-parameter of reference or pointer
7119 type, the value of the constant expression shall not refer to (or
7120 for a pointer type, shall not be the address of):
7121 * a subobject (4.5),
7122 * a temporary object (15.2),
7123 * a string literal (5.13.5),
7124 * the result of a typeid expression (8.2.8), or
7125 * a predefined __func__ variable (11.4.1). */
7126 else if (DECL_ARTIFICIAL (decl))
7128 if (complain & tf_error)
7129 error ("the address of %qD is not a valid template argument",
7130 decl);
7131 return true;
7133 else if (cxx_dialect < cxx20
7134 && !(same_type_ignoring_top_level_qualifiers_p
7135 (strip_array_types (TREE_TYPE (type)),
7136 strip_array_types (TREE_TYPE (decl)))))
7138 if (complain & tf_error)
7139 error ("the address of the %qT subobject of %qD is not a "
7140 "valid template argument", TREE_TYPE (type), decl);
7141 return true;
7143 else if (!TREE_STATIC (decl) && !DECL_EXTERNAL (decl))
7145 if (complain & tf_error)
7146 error ("the address of %qD is not a valid template argument "
7147 "because it does not have static storage duration",
7148 decl);
7149 return true;
7152 break;
7154 default:
7155 if (!INDIRECT_TYPE_P (type))
7156 /* We're only concerned about pointers and references here. */;
7157 else if (cxx_dialect >= cxx11 && integer_zerop (expr))
7158 /* Null pointer values are OK in C++11. */;
7159 else
7161 if (VAR_P (expr))
7163 if (complain & tf_error)
7164 error ("%qD is not a valid template argument "
7165 "because %qD is a variable, not the address of "
7166 "a variable", expr, expr);
7167 return true;
7169 else
7171 if (complain & tf_error)
7172 error ("%qE is not a valid template argument for %qT "
7173 "because it is not the address of a variable",
7174 expr, type);
7175 return true;
7179 return false;
7183 /* Return a VAR_DECL for the C++20 template parameter object corresponding to
7184 template argument EXPR. */
7186 static tree
7187 create_template_parm_object (tree expr, tsubst_flags_t complain)
7189 if (TREE_CODE (expr) == TARGET_EXPR)
7190 expr = TARGET_EXPR_INITIAL (expr);
7192 if (!TREE_CONSTANT (expr))
7194 if ((complain & tf_error)
7195 && require_rvalue_constant_expression (expr))
7196 cxx_constant_value (expr);
7197 return error_mark_node;
7199 if (invalid_tparm_referent_p (TREE_TYPE (expr), expr, complain))
7200 return error_mark_node;
7202 /* This is no longer a compound literal. */
7203 gcc_assert (!TREE_HAS_CONSTRUCTOR (expr));
7205 return get_template_parm_object (expr, mangle_template_parm_object (expr));
7208 /* The template arguments corresponding to template parameter objects of types
7209 that contain pointers to members. */
7211 static GTY(()) hash_map<tree, tree> *tparm_obj_values;
7213 /* Find or build an nttp object for (already-validated) EXPR with name
7214 NAME. */
7216 tree
7217 get_template_parm_object (tree expr, tree name)
7219 tree decl = get_global_binding (name);
7220 if (decl)
7221 return decl;
7223 tree type = cp_build_qualified_type (TREE_TYPE (expr), TYPE_QUAL_CONST);
7224 decl = create_temporary_var (type);
7225 DECL_NTTP_OBJECT_P (decl) = true;
7226 DECL_CONTEXT (decl) = NULL_TREE;
7227 TREE_STATIC (decl) = true;
7228 DECL_DECLARED_CONSTEXPR_P (decl) = true;
7229 TREE_READONLY (decl) = true;
7230 DECL_NAME (decl) = name;
7231 SET_DECL_ASSEMBLER_NAME (decl, name);
7232 comdat_linkage (decl);
7234 if (!zero_init_p (type))
7236 /* If EXPR contains any PTRMEM_CST, they will get clobbered by
7237 lower_var_init before we're done mangling. So store the original
7238 value elsewhere. */
7239 tree copy = unshare_constructor (expr);
7240 hash_map_safe_put<hm_ggc> (tparm_obj_values, decl, copy);
7243 pushdecl_top_level_and_finish (decl, expr);
7245 return decl;
7248 /* Return the actual template argument corresponding to template parameter
7249 object VAR. */
7251 tree
7252 tparm_object_argument (tree var)
7254 if (zero_init_p (TREE_TYPE (var)))
7255 return DECL_INITIAL (var);
7256 return *(tparm_obj_values->get (var));
7259 /* Attempt to convert the non-type template parameter EXPR to the
7260 indicated TYPE. If the conversion is successful, return the
7261 converted value. If the conversion is unsuccessful, return
7262 NULL_TREE if we issued an error message, or error_mark_node if we
7263 did not. We issue error messages for out-and-out bad template
7264 parameters, but not simply because the conversion failed, since we
7265 might be just trying to do argument deduction. Both TYPE and EXPR
7266 must be non-dependent.
7268 The conversion follows the special rules described in
7269 [temp.arg.nontype], and it is much more strict than an implicit
7270 conversion.
7272 This function is called twice for each template argument (see
7273 lookup_template_class for a more accurate description of this
7274 problem). This means that we need to handle expressions which
7275 are not valid in a C++ source, but can be created from the
7276 first call (for instance, casts to perform conversions). These
7277 hacks can go away after we fix the double coercion problem. */
7279 static tree
7280 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
7282 tree expr_type;
7283 location_t loc = cp_expr_loc_or_input_loc (expr);
7285 /* Detect immediately string literals as invalid non-type argument.
7286 This special-case is not needed for correctness (we would easily
7287 catch this later), but only to provide better diagnostic for this
7288 common user mistake. As suggested by DR 100, we do not mention
7289 linkage issues in the diagnostic as this is not the point. */
7290 if (TREE_CODE (expr) == STRING_CST && !CLASS_TYPE_P (type))
7292 if (complain & tf_error)
7293 error ("%qE is not a valid template argument for type %qT "
7294 "because string literals can never be used in this context",
7295 expr, type);
7296 return NULL_TREE;
7299 /* Add the ADDR_EXPR now for the benefit of
7300 value_dependent_expression_p. */
7301 if (TYPE_PTROBV_P (type)
7302 && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
7304 expr = decay_conversion (expr, complain);
7305 if (expr == error_mark_node)
7306 return error_mark_node;
7309 /* If we are in a template, EXPR may be non-dependent, but still
7310 have a syntactic, rather than semantic, form. For example, EXPR
7311 might be a SCOPE_REF, rather than the VAR_DECL to which the
7312 SCOPE_REF refers. Preserving the qualifying scope is necessary
7313 so that access checking can be performed when the template is
7314 instantiated -- but here we need the resolved form so that we can
7315 convert the argument. */
7316 bool non_dep = false;
7317 if (TYPE_REF_OBJ_P (type)
7318 && has_value_dependent_address (expr))
7319 /* If we want the address and it's value-dependent, don't fold. */;
7320 else if (processing_template_decl
7321 && is_nondependent_constant_expression (expr))
7322 non_dep = true;
7323 if (error_operand_p (expr))
7324 return error_mark_node;
7325 expr_type = TREE_TYPE (expr);
7327 /* If the argument is non-dependent, perform any conversions in
7328 non-dependent context as well. */
7329 processing_template_decl_sentinel s (non_dep);
7330 if (non_dep)
7331 expr = instantiate_non_dependent_expr_internal (expr, complain);
7333 bool val_dep_p = value_dependent_expression_p (expr);
7334 if (val_dep_p)
7335 expr = canonicalize_expr_argument (expr, complain);
7336 else
7337 STRIP_ANY_LOCATION_WRAPPER (expr);
7339 /* 14.3.2/5: The null pointer{,-to-member} conversion is applied
7340 to a non-type argument of "nullptr". */
7341 if (NULLPTR_TYPE_P (expr_type) && TYPE_PTR_OR_PTRMEM_P (type))
7342 expr = fold_simple (convert (type, expr));
7344 /* In C++11, integral or enumeration non-type template arguments can be
7345 arbitrary constant expressions. Pointer and pointer to
7346 member arguments can be general constant expressions that evaluate
7347 to a null value, but otherwise still need to be of a specific form. */
7348 if (cxx_dialect >= cxx11)
7350 if (TREE_CODE (expr) == PTRMEM_CST && TYPE_PTRMEM_P (type))
7351 /* A PTRMEM_CST is already constant, and a valid template
7352 argument for a parameter of pointer to member type, we just want
7353 to leave it in that form rather than lower it to a
7354 CONSTRUCTOR. */;
7355 else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
7356 || cxx_dialect >= cxx17)
7358 /* C++17: A template-argument for a non-type template-parameter shall
7359 be a converted constant expression (8.20) of the type of the
7360 template-parameter. */
7361 expr = build_converted_constant_expr (type, expr, complain);
7362 if (expr == error_mark_node)
7363 /* Make sure we return NULL_TREE only if we have really issued
7364 an error, as described above. */
7365 return (complain & tf_error) ? NULL_TREE : error_mark_node;
7366 else if (TREE_CODE (expr) == IMPLICIT_CONV_EXPR)
7368 IMPLICIT_CONV_EXPR_NONTYPE_ARG (expr) = true;
7369 return expr;
7371 expr = maybe_constant_value (expr, NULL_TREE,
7372 /*manifestly_const_eval=*/true);
7373 expr = convert_from_reference (expr);
7374 /* EXPR may have become value-dependent. */
7375 val_dep_p = value_dependent_expression_p (expr);
7377 else if (TYPE_PTR_OR_PTRMEM_P (type))
7379 tree folded = maybe_constant_value (expr, NULL_TREE,
7380 /*manifestly_const_eval=*/true);
7381 if (TYPE_PTR_P (type) ? integer_zerop (folded)
7382 : null_member_pointer_value_p (folded))
7383 expr = folded;
7387 if (TYPE_REF_P (type))
7388 expr = mark_lvalue_use (expr);
7389 else
7390 expr = mark_rvalue_use (expr);
7392 /* HACK: Due to double coercion, we can get a
7393 NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
7394 which is the tree that we built on the first call (see
7395 below when coercing to reference to object or to reference to
7396 function). We just strip everything and get to the arg.
7397 See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
7398 for examples. */
7399 if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
7401 /* Check this before we strip *& to avoid redundancy. */
7402 if (!mark_single_function (expr, complain))
7403 return error_mark_node;
7405 tree probe_type, probe = expr;
7406 if (REFERENCE_REF_P (probe))
7407 probe = TREE_OPERAND (probe, 0);
7408 probe_type = TREE_TYPE (probe);
7409 if (TREE_CODE (probe) == NOP_EXPR)
7411 /* ??? Maybe we could use convert_from_reference here, but we
7412 would need to relax its constraints because the NOP_EXPR
7413 could actually change the type to something more cv-qualified,
7414 and this is not folded by convert_from_reference. */
7415 tree addr = TREE_OPERAND (probe, 0);
7416 if (TYPE_REF_P (probe_type)
7417 && TREE_CODE (addr) == ADDR_EXPR
7418 && TYPE_PTR_P (TREE_TYPE (addr))
7419 && (same_type_ignoring_top_level_qualifiers_p
7420 (TREE_TYPE (probe_type),
7421 TREE_TYPE (TREE_TYPE (addr)))))
7423 expr = TREE_OPERAND (addr, 0);
7424 expr_type = TREE_TYPE (probe_type);
7429 /* [temp.arg.nontype]/5, bullet 1
7431 For a non-type template-parameter of integral or enumeration type,
7432 integral promotions (_conv.prom_) and integral conversions
7433 (_conv.integral_) are applied. */
7434 if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
7435 || TREE_CODE (type) == REAL_TYPE)
7437 if (cxx_dialect < cxx11)
7439 tree t = build_converted_constant_expr (type, expr, complain);
7440 t = maybe_constant_value (t);
7441 if (t != error_mark_node)
7442 expr = t;
7445 if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
7446 return error_mark_node;
7448 /* Notice that there are constant expressions like '4 % 0' which
7449 do not fold into integer constants. */
7450 if (!CONSTANT_CLASS_P (expr) && !val_dep_p)
7452 if (complain & tf_error)
7454 int errs = errorcount, warns = warningcount + werrorcount;
7455 if (!require_potential_constant_expression (expr))
7456 expr = error_mark_node;
7457 else
7458 expr = cxx_constant_value (expr);
7459 if (errorcount > errs || warningcount + werrorcount > warns)
7460 inform (loc, "in template argument for type %qT", type);
7461 if (expr == error_mark_node)
7462 return NULL_TREE;
7463 /* else cxx_constant_value complained but gave us
7464 a real constant, so go ahead. */
7465 if (!CONSTANT_CLASS_P (expr))
7467 /* Some assemble time constant expressions like
7468 (intptr_t)&&lab1 - (intptr_t)&&lab2 or
7469 4 + (intptr_t)&&var satisfy reduced_constant_expression_p
7470 as we can emit them into .rodata initializers of
7471 variables, yet they can't fold into an INTEGER_CST at
7472 compile time. Refuse them here. */
7473 gcc_checking_assert (reduced_constant_expression_p (expr));
7474 error_at (loc, "template argument %qE for type %qT not "
7475 "a compile-time constant", expr, type);
7476 return NULL_TREE;
7479 else
7480 return NULL_TREE;
7483 /* Avoid typedef problems. */
7484 if (TREE_TYPE (expr) != type)
7485 expr = fold_convert (type, expr);
7487 /* [temp.arg.nontype]/5, bullet 2
7489 For a non-type template-parameter of type pointer to object,
7490 qualification conversions (_conv.qual_) and the array-to-pointer
7491 conversion (_conv.array_) are applied. */
7492 else if (TYPE_PTROBV_P (type))
7494 tree decayed = expr;
7496 /* Look through any NOP_EXPRs around an ADDR_EXPR, whether they come from
7497 decay_conversion or an explicit cast. If it's a problematic cast,
7498 we'll complain about it below. */
7499 if (TREE_CODE (expr) == NOP_EXPR)
7501 tree probe = expr;
7502 STRIP_NOPS (probe);
7503 if (TREE_CODE (probe) == ADDR_EXPR
7504 && TYPE_PTR_P (TREE_TYPE (probe)))
7506 expr = probe;
7507 expr_type = TREE_TYPE (expr);
7511 /* [temp.arg.nontype]/1 (TC1 version, DR 49):
7513 A template-argument for a non-type, non-template template-parameter
7514 shall be one of: [...]
7516 -- the name of a non-type template-parameter;
7517 -- the address of an object or function with external linkage, [...]
7518 expressed as "& id-expression" where the & is optional if the name
7519 refers to a function or array, or if the corresponding
7520 template-parameter is a reference.
7522 Here, we do not care about functions, as they are invalid anyway
7523 for a parameter of type pointer-to-object. */
7525 if (val_dep_p)
7526 /* Non-type template parameters are OK. */
7528 else if (cxx_dialect >= cxx11 && integer_zerop (expr))
7529 /* Null pointer values are OK in C++11. */;
7530 else if (TREE_CODE (expr) != ADDR_EXPR
7531 && !INDIRECT_TYPE_P (expr_type))
7532 /* Other values, like integer constants, might be valid
7533 non-type arguments of some other type. */
7534 return error_mark_node;
7535 else if (invalid_tparm_referent_p (type, expr, complain))
7536 return NULL_TREE;
7538 expr = decayed;
7540 expr = perform_qualification_conversions (type, expr);
7541 if (expr == error_mark_node)
7542 return error_mark_node;
7544 /* [temp.arg.nontype]/5, bullet 3
7546 For a non-type template-parameter of type reference to object, no
7547 conversions apply. The type referred to by the reference may be more
7548 cv-qualified than the (otherwise identical) type of the
7549 template-argument. The template-parameter is bound directly to the
7550 template-argument, which must be an lvalue. */
7551 else if (TYPE_REF_OBJ_P (type))
7553 if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
7554 expr_type))
7555 return error_mark_node;
7557 if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
7559 if (complain & tf_error)
7560 error ("%qE is not a valid template argument for type %qT "
7561 "because of conflicts in cv-qualification", expr, type);
7562 return NULL_TREE;
7565 if (!lvalue_p (expr))
7567 if (complain & tf_error)
7568 error ("%qE is not a valid template argument for type %qT "
7569 "because it is not an lvalue", expr, type);
7570 return NULL_TREE;
7573 /* [temp.arg.nontype]/1
7575 A template-argument for a non-type, non-template template-parameter
7576 shall be one of: [...]
7578 -- the address of an object or function with external linkage. */
7579 if (INDIRECT_REF_P (expr)
7580 && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
7582 expr = TREE_OPERAND (expr, 0);
7583 if (DECL_P (expr))
7585 if (complain & tf_error)
7586 error ("%q#D is not a valid template argument for type %qT "
7587 "because a reference variable does not have a constant "
7588 "address", expr, type);
7589 return NULL_TREE;
7593 if (TYPE_REF_OBJ_P (TREE_TYPE (expr)) && val_dep_p)
7594 /* OK, dependent reference. We don't want to ask whether a DECL is
7595 itself value-dependent, since what we want here is its address. */;
7596 else
7598 expr = build_address (expr);
7600 if (invalid_tparm_referent_p (type, expr, complain))
7601 return NULL_TREE;
7604 if (!same_type_p (type, TREE_TYPE (expr)))
7605 expr = build_nop (type, expr);
7607 /* [temp.arg.nontype]/5, bullet 4
7609 For a non-type template-parameter of type pointer to function, only
7610 the function-to-pointer conversion (_conv.func_) is applied. If the
7611 template-argument represents a set of overloaded functions (or a
7612 pointer to such), the matching function is selected from the set
7613 (_over.over_). */
7614 else if (TYPE_PTRFN_P (type))
7616 /* If the argument is a template-id, we might not have enough
7617 context information to decay the pointer. */
7618 if (!type_unknown_p (expr_type))
7620 expr = decay_conversion (expr, complain);
7621 if (expr == error_mark_node)
7622 return error_mark_node;
7625 if (cxx_dialect >= cxx11 && integer_zerop (expr))
7626 /* Null pointer values are OK in C++11. */
7627 return perform_qualification_conversions (type, expr);
7629 expr = convert_nontype_argument_function (type, expr, complain);
7630 if (!expr || expr == error_mark_node)
7631 return expr;
7633 /* [temp.arg.nontype]/5, bullet 5
7635 For a non-type template-parameter of type reference to function, no
7636 conversions apply. If the template-argument represents a set of
7637 overloaded functions, the matching function is selected from the set
7638 (_over.over_). */
7639 else if (TYPE_REFFN_P (type))
7641 if (TREE_CODE (expr) == ADDR_EXPR)
7643 if (complain & tf_error)
7645 error ("%qE is not a valid template argument for type %qT "
7646 "because it is a pointer", expr, type);
7647 inform (input_location, "try using %qE instead",
7648 TREE_OPERAND (expr, 0));
7650 return NULL_TREE;
7653 expr = convert_nontype_argument_function (type, expr, complain);
7654 if (!expr || expr == error_mark_node)
7655 return expr;
7657 /* [temp.arg.nontype]/5, bullet 6
7659 For a non-type template-parameter of type pointer to member function,
7660 no conversions apply. If the template-argument represents a set of
7661 overloaded member functions, the matching member function is selected
7662 from the set (_over.over_). */
7663 else if (TYPE_PTRMEMFUNC_P (type))
7665 expr = instantiate_type (type, expr, tf_none);
7666 if (expr == error_mark_node)
7667 return error_mark_node;
7669 /* [temp.arg.nontype] bullet 1 says the pointer to member
7670 expression must be a pointer-to-member constant. */
7671 if (!val_dep_p
7672 && !check_valid_ptrmem_cst_expr (type, expr, complain))
7673 return NULL_TREE;
7675 /* Repeated conversion can't deal with a conversion that turns PTRMEM_CST
7676 into a CONSTRUCTOR, so build up a new PTRMEM_CST instead. */
7677 if (fnptr_conv_p (type, TREE_TYPE (expr)))
7678 expr = make_ptrmem_cst (type, PTRMEM_CST_MEMBER (expr));
7680 /* [temp.arg.nontype]/5, bullet 7
7682 For a non-type template-parameter of type pointer to data member,
7683 qualification conversions (_conv.qual_) are applied. */
7684 else if (TYPE_PTRDATAMEM_P (type))
7686 /* [temp.arg.nontype] bullet 1 says the pointer to member
7687 expression must be a pointer-to-member constant. */
7688 if (!val_dep_p
7689 && !check_valid_ptrmem_cst_expr (type, expr, complain))
7690 return NULL_TREE;
7692 expr = perform_qualification_conversions (type, expr);
7693 if (expr == error_mark_node)
7694 return expr;
7696 else if (NULLPTR_TYPE_P (type))
7698 if (!NULLPTR_TYPE_P (TREE_TYPE (expr)))
7700 if (complain & tf_error)
7701 error ("%qE is not a valid template argument for type %qT "
7702 "because it is of type %qT", expr, type, TREE_TYPE (expr));
7703 return NULL_TREE;
7705 return expr;
7707 else if (CLASS_TYPE_P (type))
7709 /* Replace the argument with a reference to the corresponding template
7710 parameter object. */
7711 if (!val_dep_p)
7712 expr = create_template_parm_object (expr, complain);
7713 if (expr == error_mark_node)
7714 return NULL_TREE;
7716 /* A template non-type parameter must be one of the above. */
7717 else
7718 gcc_unreachable ();
7720 /* Sanity check: did we actually convert the argument to the
7721 right type? */
7722 gcc_assert (same_type_ignoring_top_level_qualifiers_p
7723 (type, TREE_TYPE (expr)));
7724 return convert_from_reference (expr);
7727 /* Subroutine of coerce_template_template_parms, which returns 1 if
7728 PARM_PARM and ARG_PARM match using the rule for the template
7729 parameters of template template parameters. Both PARM and ARG are
7730 template parameters; the rest of the arguments are the same as for
7731 coerce_template_template_parms.
7733 static int
7734 coerce_template_template_parm (tree parm,
7735 tree arg,
7736 tsubst_flags_t complain,
7737 tree in_decl,
7738 tree outer_args)
7740 if (arg == NULL_TREE || error_operand_p (arg)
7741 || parm == NULL_TREE || error_operand_p (parm))
7742 return 0;
7744 if (TREE_CODE (arg) != TREE_CODE (parm))
7745 return 0;
7747 switch (TREE_CODE (parm))
7749 case TEMPLATE_DECL:
7750 /* We encounter instantiations of templates like
7751 template <template <template <class> class> class TT>
7752 class C; */
7754 tree parmparm = DECL_TEMPLATE_PARMS (parm);
7755 tree argparm = DECL_TEMPLATE_PARMS (arg);
7757 if (!coerce_template_template_parms
7758 (parmparm, argparm, complain, in_decl, outer_args))
7759 return 0;
7761 /* Fall through. */
7763 case TYPE_DECL:
7764 if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
7765 && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
7766 /* Argument is a parameter pack but parameter is not. */
7767 return 0;
7768 break;
7770 case PARM_DECL:
7771 /* The tsubst call is used to handle cases such as
7773 template <int> class C {};
7774 template <class T, template <T> class TT> class D {};
7775 D<int, C> d;
7777 i.e. the parameter list of TT depends on earlier parameters. */
7778 if (!uses_template_parms (TREE_TYPE (arg)))
7780 tree t = tsubst (TREE_TYPE (parm), outer_args, complain, in_decl);
7781 if (!uses_template_parms (t)
7782 && !same_type_p (t, TREE_TYPE (arg)))
7783 return 0;
7786 if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
7787 && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
7788 /* Argument is a parameter pack but parameter is not. */
7789 return 0;
7791 break;
7793 default:
7794 gcc_unreachable ();
7797 return 1;
7800 /* Coerce template argument list ARGLIST for use with template
7801 template-parameter TEMPL. */
7803 static tree
7804 coerce_template_args_for_ttp (tree templ, tree arglist,
7805 tsubst_flags_t complain)
7807 /* Consider an example where a template template parameter declared as
7809 template <class T, class U = std::allocator<T> > class TT
7811 The template parameter level of T and U are one level larger than
7812 of TT. To proper process the default argument of U, say when an
7813 instantiation `TT<int>' is seen, we need to build the full
7814 arguments containing {int} as the innermost level. Outer levels,
7815 available when not appearing as default template argument, can be
7816 obtained from the arguments of the enclosing template.
7818 Suppose that TT is later substituted with std::vector. The above
7819 instantiation is `TT<int, std::allocator<T> >' with TT at
7820 level 1, and T at level 2, while the template arguments at level 1
7821 becomes {std::vector} and the inner level 2 is {int}. */
7823 tree outer = DECL_CONTEXT (templ);
7824 if (outer)
7825 outer = generic_targs_for (outer);
7826 else if (current_template_parms)
7828 /* This is an argument of the current template, so we haven't set
7829 DECL_CONTEXT yet. */
7830 tree relevant_template_parms;
7832 /* Parameter levels that are greater than the level of the given
7833 template template parm are irrelevant. */
7834 relevant_template_parms = current_template_parms;
7835 while (TMPL_PARMS_DEPTH (relevant_template_parms)
7836 != TEMPLATE_TYPE_LEVEL (TREE_TYPE (templ)))
7837 relevant_template_parms = TREE_CHAIN (relevant_template_parms);
7839 outer = template_parms_to_args (relevant_template_parms);
7842 if (outer)
7843 arglist = add_to_template_args (outer, arglist);
7845 tree parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
7846 return coerce_template_parms (parmlist, arglist, templ, complain);
7849 /* A cache of template template parameters with match-all default
7850 arguments. */
7851 static GTY((deletable)) hash_map<tree,tree> *defaulted_ttp_cache;
7853 /* T is a bound template template-parameter. Copy its arguments into default
7854 arguments of the template template-parameter's template parameters. */
7856 static tree
7857 add_defaults_to_ttp (tree otmpl)
7859 if (tree *c = hash_map_safe_get (defaulted_ttp_cache, otmpl))
7860 return *c;
7862 tree ntmpl = copy_node (otmpl);
7864 tree ntype = copy_node (TREE_TYPE (otmpl));
7865 TYPE_STUB_DECL (ntype) = TYPE_NAME (ntype) = ntmpl;
7866 TYPE_MAIN_VARIANT (ntype) = ntype;
7867 TYPE_POINTER_TO (ntype) = TYPE_REFERENCE_TO (ntype) = NULL_TREE;
7868 TYPE_NAME (ntype) = ntmpl;
7869 SET_TYPE_STRUCTURAL_EQUALITY (ntype);
7871 tree idx = TEMPLATE_TYPE_PARM_INDEX (ntype)
7872 = copy_node (TEMPLATE_TYPE_PARM_INDEX (ntype));
7873 TEMPLATE_PARM_DECL (idx) = ntmpl;
7874 TREE_TYPE (ntmpl) = TREE_TYPE (idx) = ntype;
7876 tree oparms = DECL_TEMPLATE_PARMS (otmpl);
7877 tree parms = DECL_TEMPLATE_PARMS (ntmpl) = copy_node (oparms);
7878 TREE_CHAIN (parms) = TREE_CHAIN (oparms);
7879 tree vec = TREE_VALUE (parms) = copy_node (TREE_VALUE (parms));
7880 for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
7882 tree o = TREE_VEC_ELT (vec, i);
7883 if (!template_parameter_pack_p (TREE_VALUE (o)))
7885 tree n = TREE_VEC_ELT (vec, i) = copy_node (o);
7886 TREE_PURPOSE (n) = any_targ_node;
7890 hash_map_safe_put<hm_ggc> (defaulted_ttp_cache, otmpl, ntmpl);
7891 return ntmpl;
7894 /* ARG is a bound potential template template-argument, and PARGS is a list
7895 of arguments for the corresponding template template-parameter. Adjust
7896 PARGS as appropriate for application to ARG's template, and if ARG is a
7897 BOUND_TEMPLATE_TEMPLATE_PARM, possibly adjust it to add default template
7898 arguments to the template template parameter. */
7900 static tree
7901 coerce_ttp_args_for_tta (tree& arg, tree pargs, tsubst_flags_t complain)
7903 ++processing_template_decl;
7904 tree arg_tmpl = TYPE_TI_TEMPLATE (arg);
7905 if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
7907 /* When comparing two template template-parameters in partial ordering,
7908 rewrite the one currently being used as an argument to have default
7909 arguments for all parameters. */
7910 arg_tmpl = add_defaults_to_ttp (arg_tmpl);
7911 pargs = coerce_template_args_for_ttp (arg_tmpl, pargs, complain);
7912 if (pargs != error_mark_node)
7913 arg = bind_template_template_parm (TREE_TYPE (arg_tmpl),
7914 TYPE_TI_ARGS (arg));
7916 else
7918 tree aparms
7919 = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (arg_tmpl));
7920 pargs = coerce_template_parms (aparms, pargs, arg_tmpl, complain);
7922 --processing_template_decl;
7923 return pargs;
7926 /* Subroutine of unify for the case when PARM is a
7927 BOUND_TEMPLATE_TEMPLATE_PARM. */
7929 static int
7930 unify_bound_ttp_args (tree tparms, tree targs, tree parm, tree& arg,
7931 bool explain_p)
7933 tree parmvec = TYPE_TI_ARGS (parm);
7934 tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
7936 /* The template template parm might be variadic and the argument
7937 not, so flatten both argument lists. */
7938 parmvec = expand_template_argument_pack (parmvec);
7939 argvec = expand_template_argument_pack (argvec);
7941 if (flag_new_ttp)
7943 /* In keeping with P0522R0, adjust P's template arguments
7944 to apply to A's template; then flatten it again. */
7945 tree nparmvec = coerce_ttp_args_for_tta (arg, parmvec, tf_none);
7946 nparmvec = expand_template_argument_pack (nparmvec);
7948 if (unify (tparms, targs, nparmvec, argvec,
7949 UNIFY_ALLOW_NONE, explain_p))
7950 return 1;
7952 /* If the P0522 adjustment eliminated a pack expansion, deduce
7953 empty packs. */
7954 if (flag_new_ttp
7955 && TREE_VEC_LENGTH (nparmvec) < TREE_VEC_LENGTH (parmvec)
7956 && unify_pack_expansion (tparms, targs, parmvec, argvec,
7957 DEDUCE_EXACT, /*sub*/true, explain_p))
7958 return 1;
7960 else
7962 /* Deduce arguments T, i from TT<T> or TT<i>.
7963 We check each element of PARMVEC and ARGVEC individually
7964 rather than the whole TREE_VEC since they can have
7965 different number of elements, which is allowed under N2555. */
7967 int len = TREE_VEC_LENGTH (parmvec);
7969 /* Check if the parameters end in a pack, making them
7970 variadic. */
7971 int parm_variadic_p = 0;
7972 if (len > 0
7973 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
7974 parm_variadic_p = 1;
7976 for (int i = 0; i < len - parm_variadic_p; ++i)
7977 /* If the template argument list of P contains a pack
7978 expansion that is not the last template argument, the
7979 entire template argument list is a non-deduced
7980 context. */
7981 if (PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, i)))
7982 return unify_success (explain_p);
7984 if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
7985 return unify_too_few_arguments (explain_p,
7986 TREE_VEC_LENGTH (argvec), len);
7988 for (int i = 0; i < len - parm_variadic_p; ++i)
7989 if (unify (tparms, targs,
7990 TREE_VEC_ELT (parmvec, i),
7991 TREE_VEC_ELT (argvec, i),
7992 UNIFY_ALLOW_NONE, explain_p))
7993 return 1;
7995 if (parm_variadic_p
7996 && unify_pack_expansion (tparms, targs,
7997 parmvec, argvec,
7998 DEDUCE_EXACT,
7999 /*subr=*/true, explain_p))
8000 return 1;
8003 return 0;
8006 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
8007 template template parameters. Both PARM_PARMS and ARG_PARMS are
8008 vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
8009 or PARM_DECL.
8011 Consider the example:
8012 template <class T> class A;
8013 template<template <class U> class TT> class B;
8015 For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
8016 the parameters to A, and OUTER_ARGS contains A. */
8018 static int
8019 coerce_template_template_parms (tree parm_parms_full,
8020 tree arg_parms_full,
8021 tsubst_flags_t complain,
8022 tree in_decl,
8023 tree outer_args)
8025 int nparms, nargs, i;
8026 tree parm, arg;
8027 int variadic_p = 0;
8029 tree parm_parms = INNERMOST_TEMPLATE_PARMS (parm_parms_full);
8030 tree arg_parms = INNERMOST_TEMPLATE_PARMS (arg_parms_full);
8032 gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
8033 gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
8035 nparms = TREE_VEC_LENGTH (parm_parms);
8036 nargs = TREE_VEC_LENGTH (arg_parms);
8038 if (flag_new_ttp)
8040 /* P0522R0: A template template-parameter P is at least as specialized as
8041 a template template-argument A if, given the following rewrite to two
8042 function templates, the function template corresponding to P is at
8043 least as specialized as the function template corresponding to A
8044 according to the partial ordering rules for function templates
8045 ([temp.func.order]). Given an invented class template X with the
8046 template parameter list of A (including default arguments):
8048 * Each of the two function templates has the same template parameters,
8049 respectively, as P or A.
8051 * Each function template has a single function parameter whose type is
8052 a specialization of X with template arguments corresponding to the
8053 template parameters from the respective function template where, for
8054 each template parameter PP in the template parameter list of the
8055 function template, a corresponding template argument AA is formed. If
8056 PP declares a parameter pack, then AA is the pack expansion
8057 PP... ([temp.variadic]); otherwise, AA is the id-expression PP.
8059 If the rewrite produces an invalid type, then P is not at least as
8060 specialized as A. */
8062 /* So coerce P's args to apply to A's parms, and then deduce between A's
8063 args and the converted args. If that succeeds, A is at least as
8064 specialized as P, so they match.*/
8065 processing_template_decl_sentinel ptds (/*reset*/false);
8066 ++processing_template_decl;
8068 tree pargs = template_parms_level_to_args (parm_parms);
8070 /* PARM, and thus the context in which we are passing ARG to it, may be
8071 at a deeper level than ARG; when trying to coerce to ARG_PARMS, we
8072 want to provide the right number of levels, so we reduce the number of
8073 levels in OUTER_ARGS before prepending them. This is most important
8074 when ARG is a namespace-scope template, as in alias-decl-ttp2.C.
8076 ARG might also be deeper than PARM (ttp23). In that case, we include
8077 all of OUTER_ARGS. The missing levels seem potentially problematic,
8078 but I can't come up with a testcase that breaks. */
8079 if (int arg_outer_levs = TMPL_PARMS_DEPTH (arg_parms_full) - 1)
8081 auto x = make_temp_override (TREE_VEC_LENGTH (outer_args));
8082 if (TMPL_ARGS_DEPTH (outer_args) > arg_outer_levs)
8083 TREE_VEC_LENGTH (outer_args) = arg_outer_levs;
8084 pargs = add_to_template_args (outer_args, pargs);
8087 pargs = coerce_template_parms (arg_parms, pargs, NULL_TREE, tf_none);
8088 if (pargs != error_mark_node)
8090 tree targs = make_tree_vec (nargs);
8091 tree aargs = template_parms_level_to_args (arg_parms);
8092 if (!unify (arg_parms, targs, aargs, pargs, UNIFY_ALLOW_NONE,
8093 /*explain*/false))
8094 return 1;
8098 /* Determine whether we have a parameter pack at the end of the
8099 template template parameter's template parameter list. */
8100 if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
8102 parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
8104 if (error_operand_p (parm))
8105 return 0;
8107 switch (TREE_CODE (parm))
8109 case TEMPLATE_DECL:
8110 case TYPE_DECL:
8111 if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
8112 variadic_p = 1;
8113 break;
8115 case PARM_DECL:
8116 if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
8117 variadic_p = 1;
8118 break;
8120 default:
8121 gcc_unreachable ();
8125 if (nargs != nparms
8126 && !(variadic_p && nargs >= nparms - 1))
8127 return 0;
8129 /* Check all of the template parameters except the parameter pack at
8130 the end (if any). */
8131 for (i = 0; i < nparms - variadic_p; ++i)
8133 if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
8134 || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
8135 continue;
8137 parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
8138 arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
8140 if (!coerce_template_template_parm (parm, arg, complain, in_decl,
8141 outer_args))
8142 return 0;
8146 if (variadic_p)
8148 /* Check each of the template parameters in the template
8149 argument against the template parameter pack at the end of
8150 the template template parameter. */
8151 if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
8152 return 0;
8154 parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
8156 for (; i < nargs; ++i)
8158 if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
8159 continue;
8161 arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
8163 if (!coerce_template_template_parm (parm, arg, complain, in_decl,
8164 outer_args))
8165 return 0;
8169 return 1;
8172 /* Verifies that the deduced template arguments (in TARGS) for the
8173 template template parameters (in TPARMS) represent valid bindings,
8174 by comparing the template parameter list of each template argument
8175 to the template parameter list of its corresponding template
8176 template parameter, in accordance with DR150. This
8177 routine can only be called after all template arguments have been
8178 deduced. It will return TRUE if all of the template template
8179 parameter bindings are okay, FALSE otherwise. */
8180 bool
8181 template_template_parm_bindings_ok_p (tree tparms, tree targs)
8183 int i, ntparms = TREE_VEC_LENGTH (tparms);
8184 bool ret = true;
8186 /* We're dealing with template parms in this process. */
8187 ++processing_template_decl;
8189 targs = INNERMOST_TEMPLATE_ARGS (targs);
8191 for (i = 0; i < ntparms; ++i)
8193 tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
8194 tree targ = TREE_VEC_ELT (targs, i);
8196 if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
8198 tree packed_args = NULL_TREE;
8199 int idx, len = 1;
8201 if (ARGUMENT_PACK_P (targ))
8203 /* Look inside the argument pack. */
8204 packed_args = ARGUMENT_PACK_ARGS (targ);
8205 len = TREE_VEC_LENGTH (packed_args);
8208 for (idx = 0; idx < len; ++idx)
8210 tree targ_parms = NULL_TREE;
8212 if (packed_args)
8213 /* Extract the next argument from the argument
8214 pack. */
8215 targ = TREE_VEC_ELT (packed_args, idx);
8217 if (PACK_EXPANSION_P (targ))
8218 /* Look at the pattern of the pack expansion. */
8219 targ = PACK_EXPANSION_PATTERN (targ);
8221 /* Extract the template parameters from the template
8222 argument. */
8223 if (TREE_CODE (targ) == TEMPLATE_DECL)
8224 targ_parms = DECL_TEMPLATE_PARMS (targ);
8225 else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
8226 targ_parms = DECL_TEMPLATE_PARMS (TYPE_NAME (targ));
8228 /* Verify that we can coerce the template template
8229 parameters from the template argument to the template
8230 parameter. This requires an exact match. */
8231 if (targ_parms
8232 && !coerce_template_template_parms
8233 (DECL_TEMPLATE_PARMS (tparm),
8234 targ_parms,
8235 tf_none,
8236 tparm,
8237 targs))
8239 ret = false;
8240 goto out;
8246 out:
8248 --processing_template_decl;
8249 return ret;
8252 /* Since type attributes aren't mangled, we need to strip them from
8253 template type arguments. */
8255 tree
8256 canonicalize_type_argument (tree arg, tsubst_flags_t complain)
8258 if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
8259 return arg;
8260 bool removed_attributes = false;
8261 tree canon = strip_typedefs (arg, &removed_attributes);
8262 if (removed_attributes
8263 && (complain & tf_warning))
8264 warning (OPT_Wignored_attributes,
8265 "ignoring attributes on template argument %qT", arg);
8266 return canon;
8269 /* And from inside dependent non-type arguments like sizeof(Type). */
8271 static tree
8272 canonicalize_expr_argument (tree arg, tsubst_flags_t complain)
8274 if (!arg || arg == error_mark_node)
8275 return arg;
8276 bool removed_attributes = false;
8277 tree canon = strip_typedefs_expr (arg, &removed_attributes);
8278 if (removed_attributes
8279 && (complain & tf_warning))
8280 warning (OPT_Wignored_attributes,
8281 "ignoring attributes in template argument %qE", arg);
8282 return canon;
8285 /* A template declaration can be substituted for a constrained
8286 template template parameter only when the argument is no more
8287 constrained than the parameter. */
8289 static bool
8290 is_compatible_template_arg (tree parm, tree arg)
8292 tree parm_cons = get_constraints (parm);
8294 /* For now, allow constrained template template arguments
8295 and unconstrained template template parameters. */
8296 if (parm_cons == NULL_TREE)
8297 return true;
8299 /* If the template parameter is constrained, we need to rewrite its
8300 constraints in terms of the ARG's template parameters. This ensures
8301 that all of the template parameter types will have the same depth.
8303 Note that this is only valid when coerce_template_template_parm is
8304 true for the innermost template parameters of PARM and ARG. In other
8305 words, because coercion is successful, this conversion will be valid. */
8306 tree new_args = NULL_TREE;
8307 if (parm_cons)
8309 tree aparms = DECL_INNERMOST_TEMPLATE_PARMS (arg);
8310 new_args = template_parms_level_to_args (aparms);
8311 ++processing_template_decl;
8312 parm_cons = tsubst_constraint_info (parm_cons, new_args,
8313 tf_none, NULL_TREE);
8314 --processing_template_decl;
8315 if (parm_cons == error_mark_node)
8316 return false;
8319 return weakly_subsumes (parm_cons, arg);
8322 // Convert a placeholder argument into a binding to the original
8323 // parameter. The original parameter is saved as the TREE_TYPE of
8324 // ARG.
8325 static inline tree
8326 convert_wildcard_argument (tree parm, tree arg)
8328 TREE_TYPE (arg) = parm;
8329 return arg;
8332 /* We can't fully resolve ARG given as a non-type template argument to TYPE,
8333 because one of them is dependent. But we need to represent the
8334 conversion for the benefit of cp_tree_equal. */
8336 static tree
8337 maybe_convert_nontype_argument (tree type, tree arg)
8339 /* Auto parms get no conversion. */
8340 if (type_uses_auto (type))
8341 return arg;
8342 /* We don't need or want to add this conversion now if we're going to use the
8343 argument for deduction. */
8344 if (value_dependent_expression_p (arg))
8345 return arg;
8347 type = cv_unqualified (type);
8348 tree argtype = TREE_TYPE (arg);
8349 if (same_type_p (type, argtype))
8350 return arg;
8352 arg = build1 (IMPLICIT_CONV_EXPR, type, arg);
8353 IMPLICIT_CONV_EXPR_NONTYPE_ARG (arg) = true;
8354 return arg;
8357 /* Convert the indicated template ARG as necessary to match the
8358 indicated template PARM. Returns the converted ARG, or
8359 error_mark_node if the conversion was unsuccessful. Error and
8360 warning messages are issued under control of COMPLAIN. This
8361 conversion is for the Ith parameter in the parameter list. ARGS is
8362 the full set of template arguments deduced so far. */
8364 static tree
8365 convert_template_argument (tree parm,
8366 tree arg,
8367 tree args,
8368 tsubst_flags_t complain,
8369 int i,
8370 tree in_decl)
8372 tree orig_arg;
8373 tree val;
8374 int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
8376 if (parm == error_mark_node || error_operand_p (arg))
8377 return error_mark_node;
8379 /* Trivially convert placeholders. */
8380 if (TREE_CODE (arg) == WILDCARD_DECL)
8381 return convert_wildcard_argument (parm, arg);
8383 if (arg == any_targ_node)
8384 return arg;
8386 if (TREE_CODE (arg) == TREE_LIST
8387 && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
8389 /* The template argument was the name of some
8390 member function. That's usually
8391 invalid, but static members are OK. In any
8392 case, grab the underlying fields/functions
8393 and issue an error later if required. */
8394 TREE_TYPE (arg) = unknown_type_node;
8397 orig_arg = arg;
8399 requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
8400 requires_type = (TREE_CODE (parm) == TYPE_DECL
8401 || requires_tmpl_type);
8403 /* When determining whether an argument pack expansion is a template,
8404 look at the pattern. */
8405 if (PACK_EXPANSION_P (arg))
8406 arg = PACK_EXPANSION_PATTERN (arg);
8408 /* Deal with an injected-class-name used as a template template arg. */
8409 if (requires_tmpl_type && CLASS_TYPE_P (arg))
8411 tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
8412 if (TREE_CODE (t) == TEMPLATE_DECL)
8414 if (cxx_dialect >= cxx11)
8415 /* OK under DR 1004. */;
8416 else if (complain & tf_warning_or_error)
8417 pedwarn (input_location, OPT_Wpedantic, "injected-class-name %qD"
8418 " used as template template argument", TYPE_NAME (arg));
8419 else if (flag_pedantic_errors)
8420 t = arg;
8422 arg = t;
8426 is_tmpl_type =
8427 ((TREE_CODE (arg) == TEMPLATE_DECL
8428 && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
8429 || (requires_tmpl_type && TREE_CODE (arg) == TYPE_ARGUMENT_PACK)
8430 || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
8431 || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
8433 if (is_tmpl_type
8434 && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
8435 || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
8436 arg = TYPE_STUB_DECL (arg);
8438 is_type = TYPE_P (arg) || is_tmpl_type;
8440 if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
8441 && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
8443 if (TREE_CODE (TREE_OPERAND (arg, 1)) == BIT_NOT_EXPR)
8445 if (complain & tf_error)
8446 error ("invalid use of destructor %qE as a type", orig_arg);
8447 return error_mark_node;
8450 permerror (input_location,
8451 "to refer to a type member of a template parameter, "
8452 "use %<typename %E%>", orig_arg);
8454 orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
8455 TREE_OPERAND (arg, 1),
8456 typename_type,
8457 complain);
8458 arg = orig_arg;
8459 is_type = 1;
8461 if (is_type != requires_type)
8463 if (in_decl)
8465 if (complain & tf_error)
8467 error ("type/value mismatch at argument %d in template "
8468 "parameter list for %qD",
8469 i + 1, in_decl);
8470 if (is_type)
8472 /* The template argument is a type, but we're expecting
8473 an expression. */
8474 inform (input_location,
8475 " expected a constant of type %qT, got %qT",
8476 TREE_TYPE (parm),
8477 (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
8478 /* [temp.arg]/2: "In a template-argument, an ambiguity
8479 between a type-id and an expression is resolved to a
8480 type-id, regardless of the form of the corresponding
8481 template-parameter." So give the user a clue. */
8482 if (TREE_CODE (arg) == FUNCTION_TYPE)
8483 inform (input_location, " ambiguous template argument "
8484 "for non-type template parameter is treated as "
8485 "function type");
8487 else if (requires_tmpl_type)
8488 inform (input_location,
8489 " expected a class template, got %qE", orig_arg);
8490 else
8491 inform (input_location,
8492 " expected a type, got %qE", orig_arg);
8495 return error_mark_node;
8497 if (is_tmpl_type ^ requires_tmpl_type)
8499 if (in_decl && (complain & tf_error))
8501 error ("type/value mismatch at argument %d in template "
8502 "parameter list for %qD",
8503 i + 1, in_decl);
8504 if (is_tmpl_type)
8505 inform (input_location,
8506 " expected a type, got %qT", DECL_NAME (arg));
8507 else
8508 inform (input_location,
8509 " expected a class template, got %qT", orig_arg);
8511 return error_mark_node;
8514 if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
8515 /* We already did the appropriate conversion when packing args. */
8516 val = orig_arg;
8517 else if (is_type)
8519 if (requires_tmpl_type)
8521 if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
8522 /* The number of argument required is not known yet.
8523 Just accept it for now. */
8524 val = orig_arg;
8525 else
8527 tree parmparm = DECL_TEMPLATE_PARMS (parm);
8528 tree argparm;
8530 /* Strip alias templates that are equivalent to another
8531 template. */
8532 arg = get_underlying_template (arg);
8533 argparm = DECL_TEMPLATE_PARMS (arg);
8535 if (coerce_template_template_parms (parmparm, argparm,
8536 complain, in_decl,
8537 args))
8539 val = arg;
8541 /* TEMPLATE_TEMPLATE_PARM node is preferred over
8542 TEMPLATE_DECL. */
8543 if (val != error_mark_node)
8545 if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
8546 val = TREE_TYPE (val);
8547 if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
8548 val = make_pack_expansion (val, complain);
8551 else
8553 if (in_decl && (complain & tf_error))
8555 error ("type/value mismatch at argument %d in "
8556 "template parameter list for %qD",
8557 i + 1, in_decl);
8558 inform (input_location,
8559 " expected a template of type %qD, got %qT",
8560 parm, orig_arg);
8563 val = error_mark_node;
8566 // Check that the constraints are compatible before allowing the
8567 // substitution.
8568 if (val != error_mark_node)
8569 if (!is_compatible_template_arg (parm, arg))
8571 if (in_decl && (complain & tf_error))
8573 error ("constraint mismatch at argument %d in "
8574 "template parameter list for %qD",
8575 i + 1, in_decl);
8576 inform (input_location, " expected %qD but got %qD",
8577 parm, arg);
8579 val = error_mark_node;
8583 else
8584 val = orig_arg;
8585 /* We only form one instance of each template specialization.
8586 Therefore, if we use a non-canonical variant (i.e., a
8587 typedef), any future messages referring to the type will use
8588 the typedef, which is confusing if those future uses do not
8589 themselves also use the typedef. */
8590 if (TYPE_P (val))
8591 val = canonicalize_type_argument (val, complain);
8593 else
8595 tree t = TREE_TYPE (parm);
8597 if (TEMPLATE_PARM_LEVEL (get_template_parm_index (parm))
8598 > TMPL_ARGS_DEPTH (args))
8599 /* We don't have enough levels of args to do any substitution. This
8600 can happen in the context of -fnew-ttp-matching. */;
8601 else if (tree a = type_uses_auto (t))
8603 t = do_auto_deduction (t, arg, a, complain, adc_unify, args,
8604 LOOKUP_IMPLICIT);
8605 if (t == error_mark_node)
8606 return error_mark_node;
8608 else
8609 t = tsubst (t, args, complain, in_decl);
8611 /* Perform array-to-pointer and function-to-pointer conversion
8612 as per [temp.param]/10. */
8613 t = type_decays_to (t);
8615 if (invalid_nontype_parm_type_p (t, complain))
8616 return error_mark_node;
8618 /* Drop top-level cv-qualifiers on the substituted/deduced type of
8619 this non-type template parameter, as per [temp.param]/6. */
8620 t = cv_unqualified (t);
8622 if (t != TREE_TYPE (parm))
8623 t = canonicalize_type_argument (t, complain);
8625 if (!type_dependent_expression_p (orig_arg)
8626 && !uses_template_parms (t))
8627 /* We used to call digest_init here. However, digest_init
8628 will report errors, which we don't want when complain
8629 is zero. More importantly, digest_init will try too
8630 hard to convert things: for example, `0' should not be
8631 converted to pointer type at this point according to
8632 the standard. Accepting this is not merely an
8633 extension, since deciding whether or not these
8634 conversions can occur is part of determining which
8635 function template to call, or whether a given explicit
8636 argument specification is valid. */
8637 val = convert_nontype_argument (t, orig_arg, complain);
8638 else
8640 val = canonicalize_expr_argument (orig_arg, complain);
8641 val = maybe_convert_nontype_argument (t, val);
8645 if (val == NULL_TREE)
8646 val = error_mark_node;
8647 else if (val == error_mark_node && (complain & tf_error))
8648 error_at (cp_expr_loc_or_input_loc (orig_arg),
8649 "could not convert template argument %qE from %qT to %qT",
8650 orig_arg, TREE_TYPE (orig_arg), t);
8652 if (INDIRECT_REF_P (val))
8654 /* Reject template arguments that are references to built-in
8655 functions with no library fallbacks. */
8656 const_tree inner = TREE_OPERAND (val, 0);
8657 const_tree innertype = TREE_TYPE (inner);
8658 if (innertype
8659 && TYPE_REF_P (innertype)
8660 && TREE_CODE (TREE_TYPE (innertype)) == FUNCTION_TYPE
8661 && TREE_OPERAND_LENGTH (inner) > 0
8662 && reject_gcc_builtin (TREE_OPERAND (inner, 0)))
8663 return error_mark_node;
8666 if (TREE_CODE (val) == SCOPE_REF)
8668 /* Strip typedefs from the SCOPE_REF. */
8669 tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
8670 tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
8671 complain);
8672 val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
8673 QUALIFIED_NAME_IS_TEMPLATE (val));
8677 return val;
8680 /* Coerces the remaining template arguments in INNER_ARGS (from
8681 ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
8682 Returns the coerced argument pack. PARM_IDX is the position of this
8683 parameter in the template parameter list. ARGS is the original
8684 template argument list. */
8685 static tree
8686 coerce_template_parameter_pack (tree parms,
8687 int parm_idx,
8688 tree args,
8689 tree inner_args,
8690 int arg_idx,
8691 tree new_args,
8692 int* lost,
8693 tree in_decl,
8694 tsubst_flags_t complain)
8696 tree parm = TREE_VEC_ELT (parms, parm_idx);
8697 int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8698 tree packed_args;
8699 tree argument_pack;
8700 tree packed_parms = NULL_TREE;
8702 if (arg_idx > nargs)
8703 arg_idx = nargs;
8705 if (tree packs = fixed_parameter_pack_p (TREE_VALUE (parm)))
8707 /* When the template parameter is a non-type template parameter pack
8708 or template template parameter pack whose type or template
8709 parameters use parameter packs, we know exactly how many arguments
8710 we are looking for. Build a vector of the instantiated decls for
8711 these template parameters in PACKED_PARMS. */
8712 /* We can't use make_pack_expansion here because it would interpret a
8713 _DECL as a use rather than a declaration. */
8714 tree decl = TREE_VALUE (parm);
8715 tree exp = cxx_make_type (TYPE_PACK_EXPANSION);
8716 PACK_EXPANSION_PATTERN (exp) = decl;
8717 PACK_EXPANSION_PARAMETER_PACKS (exp) = packs;
8718 SET_TYPE_STRUCTURAL_EQUALITY (exp);
8720 TREE_VEC_LENGTH (args)--;
8721 packed_parms = tsubst_pack_expansion (exp, args, complain, decl);
8722 TREE_VEC_LENGTH (args)++;
8724 if (packed_parms == error_mark_node)
8725 return error_mark_node;
8727 /* If we're doing a partial instantiation of a member template,
8728 verify that all of the types used for the non-type
8729 template parameter pack are, in fact, valid for non-type
8730 template parameters. */
8731 if (arg_idx < nargs
8732 && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
8734 int j, len = TREE_VEC_LENGTH (packed_parms);
8735 for (j = 0; j < len; ++j)
8737 tree t = TREE_VEC_ELT (packed_parms, j);
8738 if (TREE_CODE (t) == PARM_DECL
8739 && invalid_nontype_parm_type_p (TREE_TYPE (t), complain))
8740 return error_mark_node;
8742 /* We don't know how many args we have yet, just
8743 use the unconverted ones for now. */
8744 return NULL_TREE;
8747 packed_args = make_tree_vec (TREE_VEC_LENGTH (packed_parms));
8749 /* Check if we have a placeholder pack, which indicates we're
8750 in the context of a introduction list. In that case we want
8751 to match this pack to the single placeholder. */
8752 else if (arg_idx < nargs
8753 && TREE_CODE (TREE_VEC_ELT (inner_args, arg_idx)) == WILDCARD_DECL
8754 && WILDCARD_PACK_P (TREE_VEC_ELT (inner_args, arg_idx)))
8756 nargs = arg_idx + 1;
8757 packed_args = make_tree_vec (1);
8759 else
8760 packed_args = make_tree_vec (nargs - arg_idx);
8762 /* Convert the remaining arguments, which will be a part of the
8763 parameter pack "parm". */
8764 int first_pack_arg = arg_idx;
8765 for (; arg_idx < nargs; ++arg_idx)
8767 tree arg = TREE_VEC_ELT (inner_args, arg_idx);
8768 tree actual_parm = TREE_VALUE (parm);
8769 int pack_idx = arg_idx - first_pack_arg;
8771 if (packed_parms)
8773 /* Once we've packed as many args as we have types, stop. */
8774 if (pack_idx >= TREE_VEC_LENGTH (packed_parms))
8775 break;
8776 else if (PACK_EXPANSION_P (arg))
8777 /* We don't know how many args we have yet, just
8778 use the unconverted ones for now. */
8779 return NULL_TREE;
8780 else
8781 actual_parm = TREE_VEC_ELT (packed_parms, pack_idx);
8784 if (arg == error_mark_node)
8786 if (complain & tf_error)
8787 error ("template argument %d is invalid", arg_idx + 1);
8789 else
8790 arg = convert_template_argument (actual_parm,
8791 arg, new_args, complain, parm_idx,
8792 in_decl);
8793 if (arg == error_mark_node)
8794 (*lost)++;
8795 TREE_VEC_ELT (packed_args, pack_idx) = arg;
8798 if (arg_idx - first_pack_arg < TREE_VEC_LENGTH (packed_args)
8799 && TREE_VEC_LENGTH (packed_args) > 0)
8801 if (complain & tf_error)
8802 error ("wrong number of template arguments (%d, should be %d)",
8803 arg_idx - first_pack_arg, TREE_VEC_LENGTH (packed_args));
8804 return error_mark_node;
8807 if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
8808 || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
8809 argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
8810 else
8812 argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
8813 TREE_CONSTANT (argument_pack) = 1;
8816 ARGUMENT_PACK_ARGS (argument_pack) = packed_args;
8817 if (CHECKING_P)
8818 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
8819 TREE_VEC_LENGTH (packed_args));
8820 return argument_pack;
8823 /* Returns the number of pack expansions in the template argument vector
8824 ARGS. */
8826 static int
8827 pack_expansion_args_count (tree args)
8829 int i;
8830 int count = 0;
8831 if (args)
8832 for (i = 0; i < TREE_VEC_LENGTH (args); ++i)
8834 tree elt = TREE_VEC_ELT (args, i);
8835 if (elt && PACK_EXPANSION_P (elt))
8836 ++count;
8838 return count;
8841 /* Convert all template arguments to their appropriate types, and
8842 return a vector containing the innermost resulting template
8843 arguments. If any error occurs, return error_mark_node. Error and
8844 warning messages are issued under control of COMPLAIN.
8846 If PARMS represents all template parameters levels, this function
8847 returns a vector of vectors representing all the resulting argument
8848 levels. Note that in this case, only the innermost arguments are
8849 coerced because the outermost ones are supposed to have been coerced
8850 already. Otherwise, if PARMS represents only (the innermost) vector
8851 of parameters, this function returns a vector containing just the
8852 innermost resulting arguments.
8854 If REQUIRE_ALL_ARGS is false, argument deduction will be performed
8855 for arguments not specified in ARGS. If REQUIRE_ALL_ARGS is true,
8856 arguments not specified in ARGS must have default arguments which
8857 we'll use to fill in ARGS. */
8859 tree
8860 coerce_template_parms (tree parms,
8861 tree args,
8862 tree in_decl,
8863 tsubst_flags_t complain,
8864 bool require_all_args /* = true */)
8866 int nparms, nargs, parm_idx, arg_idx, lost = 0;
8867 tree orig_inner_args;
8868 tree inner_args;
8870 /* When used as a boolean value, indicates whether this is a
8871 variadic template parameter list. Since it's an int, we can also
8872 subtract it from nparms to get the number of non-variadic
8873 parameters. */
8874 int variadic_p = 0;
8875 int variadic_args_p = 0;
8876 int post_variadic_parms = 0;
8878 /* Adjustment to nparms for fixed parameter packs. */
8879 int fixed_pack_adjust = 0;
8880 int fixed_packs = 0;
8881 int missing = 0;
8883 /* Likewise for parameters with default arguments. */
8884 int default_p = 0;
8886 if (args == error_mark_node)
8887 return error_mark_node;
8889 bool return_full_args = false;
8890 if (TREE_CODE (parms) == TREE_LIST)
8892 if (TMPL_PARMS_DEPTH (parms) > 1)
8894 gcc_assert (TMPL_PARMS_DEPTH (parms) == TMPL_ARGS_DEPTH (args));
8895 return_full_args = true;
8897 parms = INNERMOST_TEMPLATE_PARMS (parms);
8900 nparms = TREE_VEC_LENGTH (parms);
8902 /* Determine if there are any parameter packs or default arguments. */
8903 for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
8905 tree parm = TREE_VEC_ELT (parms, parm_idx);
8906 if (variadic_p)
8907 ++post_variadic_parms;
8908 if (template_parameter_pack_p (TREE_VALUE (parm)))
8909 ++variadic_p;
8910 if (TREE_PURPOSE (parm))
8911 ++default_p;
8914 inner_args = orig_inner_args = INNERMOST_TEMPLATE_ARGS (args);
8915 /* If there are no parameters that follow a parameter pack, we need to
8916 expand any argument packs so that we can deduce a parameter pack from
8917 some non-packed args followed by an argument pack, as in variadic85.C.
8918 If there are such parameters, we need to leave argument packs intact
8919 so the arguments are assigned properly. This can happen when dealing
8920 with a nested class inside a partial specialization of a class
8921 template, as in variadic92.C, or when deducing a template parameter pack
8922 from a sub-declarator, as in variadic114.C. */
8923 if (!post_variadic_parms)
8924 inner_args = expand_template_argument_pack (inner_args);
8926 /* Count any pack expansion args. */
8927 variadic_args_p = pack_expansion_args_count (inner_args);
8929 nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8930 if ((nargs - variadic_args_p > nparms && !variadic_p)
8931 || (nargs < nparms - variadic_p
8932 && require_all_args
8933 && !variadic_args_p
8934 && (TREE_VEC_ELT (parms, nargs) != error_mark_node
8935 && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs)))))
8937 bad_nargs:
8938 if (complain & tf_error)
8940 if (variadic_p || default_p)
8942 nparms -= variadic_p + default_p;
8943 error ("wrong number of template arguments "
8944 "(%d, should be at least %d)", nargs, nparms);
8946 else
8947 error ("wrong number of template arguments "
8948 "(%d, should be %d)", nargs, nparms);
8950 if (in_decl)
8951 inform (DECL_SOURCE_LOCATION (in_decl),
8952 "provided for %qD", in_decl);
8955 return error_mark_node;
8957 /* We can't pass a pack expansion to a non-pack parameter of an alias
8958 template (DR 1430). */
8959 else if (in_decl
8960 && (DECL_ALIAS_TEMPLATE_P (in_decl)
8961 || concept_definition_p (in_decl))
8962 && variadic_args_p
8963 && nargs - variadic_args_p < nparms - variadic_p)
8965 if (complain & tf_error)
8967 for (int i = 0; i < TREE_VEC_LENGTH (inner_args); ++i)
8969 tree arg = TREE_VEC_ELT (inner_args, i);
8970 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
8972 if (PACK_EXPANSION_P (arg)
8973 && !template_parameter_pack_p (parm))
8975 if (DECL_ALIAS_TEMPLATE_P (in_decl))
8976 error_at (location_of (arg),
8977 "pack expansion argument for non-pack parameter "
8978 "%qD of alias template %qD", parm, in_decl);
8979 else
8980 error_at (location_of (arg),
8981 "pack expansion argument for non-pack parameter "
8982 "%qD of concept %qD", parm, in_decl);
8983 inform (DECL_SOURCE_LOCATION (parm), "declared here");
8984 goto found;
8987 gcc_unreachable ();
8988 found:;
8990 return error_mark_node;
8993 /* We need to evaluate the template arguments, even though this
8994 template-id may be nested within a "sizeof". */
8995 cp_evaluated ev;
8997 tree new_args = add_outermost_template_args (args, make_tree_vec (nparms));
8998 tree& new_inner_args = TMPL_ARGS_LEVEL (new_args, TMPL_ARGS_DEPTH (new_args));
8999 int pack_adjust = 0;
9000 for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
9002 tree arg;
9003 tree parm;
9005 /* Get the Ith template parameter. */
9006 parm = TREE_VEC_ELT (parms, parm_idx);
9008 if (parm == error_mark_node)
9010 TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
9011 continue;
9014 /* Calculate the next argument. */
9015 if (arg_idx < nargs)
9016 arg = TREE_VEC_ELT (inner_args, arg_idx);
9017 else
9018 arg = NULL_TREE;
9020 if (template_parameter_pack_p (TREE_VALUE (parm))
9021 && (arg || require_all_args || !(complain & tf_partial))
9022 && !(arg && ARGUMENT_PACK_P (arg)))
9024 /* Some arguments will be placed in the
9025 template parameter pack PARM. */
9026 arg = coerce_template_parameter_pack (parms, parm_idx, args,
9027 inner_args, arg_idx,
9028 new_args, &lost,
9029 in_decl, complain);
9031 if (arg == NULL_TREE)
9033 /* We don't know how many args we have yet, just use the
9034 unconverted (and still packed) ones for now. */
9035 new_inner_args = orig_inner_args;
9036 arg_idx = nargs;
9037 break;
9040 TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
9042 /* Store this argument. */
9043 if (arg == error_mark_node)
9045 lost++;
9046 /* We are done with all of the arguments. */
9047 arg_idx = nargs;
9048 break;
9050 else
9052 pack_adjust = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg)) - 1;
9053 arg_idx += pack_adjust;
9054 if (fixed_parameter_pack_p (TREE_VALUE (parm)))
9056 ++fixed_packs;
9057 fixed_pack_adjust += pack_adjust;
9061 continue;
9063 else if (arg)
9065 if (PACK_EXPANSION_P (arg))
9067 /* "If every valid specialization of a variadic template
9068 requires an empty template parameter pack, the template is
9069 ill-formed, no diagnostic required." So check that the
9070 pattern works with this parameter. */
9071 tree pattern = PACK_EXPANSION_PATTERN (arg);
9072 tree conv = convert_template_argument (TREE_VALUE (parm),
9073 pattern, new_args,
9074 complain, parm_idx,
9075 in_decl);
9076 if (conv == error_mark_node)
9078 if (complain & tf_error)
9079 inform (input_location, "so any instantiation with a "
9080 "non-empty parameter pack would be ill-formed");
9081 ++lost;
9083 else if (TYPE_P (conv) && !TYPE_P (pattern))
9084 /* Recover from missing typename. */
9085 TREE_VEC_ELT (inner_args, arg_idx)
9086 = make_pack_expansion (conv, complain);
9088 /* We don't know how many args we have yet, just
9089 use the unconverted ones for now. */
9090 new_inner_args = inner_args;
9091 arg_idx = nargs;
9092 break;
9095 else if (require_all_args)
9097 /* There must be a default arg in this case. */
9098 arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
9099 complain, in_decl);
9100 /* The position of the first default template argument,
9101 is also the number of non-defaulted arguments in NEW_INNER_ARGS.
9102 Record that. */
9103 if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
9104 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
9105 arg_idx - pack_adjust);
9107 else
9108 break;
9110 if (arg == error_mark_node)
9112 if (complain & tf_error)
9113 error ("template argument %d is invalid", arg_idx + 1);
9115 else if (!arg)
9117 /* This can occur if there was an error in the template
9118 parameter list itself (which we would already have
9119 reported) that we are trying to recover from, e.g., a class
9120 template with a parameter list such as
9121 template<typename..., typename> (cpp0x/variadic150.C). */
9122 ++lost;
9124 /* This can also happen with a fixed parameter pack (71834). */
9125 if (arg_idx >= nargs)
9126 ++missing;
9128 else
9129 arg = convert_template_argument (TREE_VALUE (parm),
9130 arg, new_args, complain,
9131 parm_idx, in_decl);
9133 if (arg == error_mark_node)
9134 lost++;
9136 TREE_VEC_ELT (new_inner_args, arg_idx - pack_adjust) = arg;
9139 if (missing || arg_idx < nargs - variadic_args_p)
9141 /* If we had fixed parameter packs, we didn't know how many arguments we
9142 actually needed earlier; now we do. */
9143 nparms += fixed_pack_adjust;
9144 variadic_p -= fixed_packs;
9145 goto bad_nargs;
9148 if (arg_idx < nargs)
9150 /* We had some pack expansion arguments that will only work if the packs
9151 are empty, but wait until instantiation time to complain.
9152 See variadic-ttp3.C. */
9154 /* Except that we can't provide empty packs to alias templates or
9155 concepts when there are no corresponding parameters. Basically,
9156 we can get here with this:
9158 template<typename T> concept C = true;
9160 template<typename... Args>
9161 requires C<Args...>
9162 void f();
9164 When parsing C<Args...>, we try to form a concept check of
9165 C<?, Args...>. Without the extra check for substituting an empty
9166 pack past the last parameter, we can accept the check as valid.
9168 FIXME: This may be valid for alias templates (but I doubt it).
9170 FIXME: The error could be better also. */
9171 if (in_decl && concept_definition_p (in_decl))
9173 if (complain & tf_error)
9174 error_at (location_of (TREE_VEC_ELT (args, arg_idx)),
9175 "too many arguments");
9176 return error_mark_node;
9179 int len = nparms + (nargs - arg_idx);
9180 tree args = make_tree_vec (len);
9181 int i = 0;
9182 for (; i < nparms; ++i)
9183 TREE_VEC_ELT (args, i) = TREE_VEC_ELT (new_inner_args, i);
9184 for (; i < len; ++i, ++arg_idx)
9185 TREE_VEC_ELT (args, i) = TREE_VEC_ELT (inner_args,
9186 arg_idx - pack_adjust);
9187 new_inner_args = args;
9190 if (lost)
9192 gcc_assert (!(complain & tf_error) || seen_error ());
9193 return error_mark_node;
9196 if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
9197 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
9198 TREE_VEC_LENGTH (new_inner_args));
9200 return return_full_args ? new_args : new_inner_args;
9203 /* Returns true if T is a wrapper to make a C++20 template parameter
9204 object const. */
9206 static bool
9207 class_nttp_const_wrapper_p (tree t)
9209 if (cxx_dialect < cxx20)
9210 return false;
9211 return (TREE_CODE (t) == VIEW_CONVERT_EXPR
9212 && CP_TYPE_CONST_P (TREE_TYPE (t))
9213 && TREE_CODE (TREE_OPERAND (t, 0)) == TEMPLATE_PARM_INDEX);
9216 /* Returns 1 if template args OT and NT are equivalent. */
9219 template_args_equal (tree ot, tree nt, bool partial_order /* = false */)
9221 if (nt == ot)
9222 return 1;
9223 if (nt == NULL_TREE || ot == NULL_TREE)
9224 return false;
9225 if (nt == any_targ_node || ot == any_targ_node)
9226 return true;
9228 if (class_nttp_const_wrapper_p (nt))
9229 nt = TREE_OPERAND (nt, 0);
9230 if (class_nttp_const_wrapper_p (ot))
9231 ot = TREE_OPERAND (ot, 0);
9233 /* DR 1558: Don't treat an alias template specialization with dependent
9234 arguments as equivalent to its underlying type when used as a template
9235 argument; we need them to be distinct so that we substitute into the
9236 specialization arguments at instantiation time. And aliases can't be
9237 equivalent without being ==, so we don't need to look any deeper.
9239 During partial ordering, however, we need to treat them normally so we can
9240 order uses of the same alias with different cv-qualification (79960). */
9241 auto cso = make_temp_override (comparing_dependent_aliases);
9242 if (!partial_order)
9243 ++comparing_dependent_aliases;
9245 if (TREE_CODE (nt) == TREE_VEC || TREE_CODE (ot) == TREE_VEC)
9246 /* For member templates */
9247 return TREE_CODE (ot) == TREE_CODE (nt) && comp_template_args (ot, nt);
9248 else if (PACK_EXPANSION_P (ot) || PACK_EXPANSION_P (nt))
9249 return (PACK_EXPANSION_P (ot) && PACK_EXPANSION_P (nt)
9250 && template_args_equal (PACK_EXPANSION_PATTERN (ot),
9251 PACK_EXPANSION_PATTERN (nt))
9252 && template_args_equal (PACK_EXPANSION_EXTRA_ARGS (ot),
9253 PACK_EXPANSION_EXTRA_ARGS (nt)));
9254 else if (ARGUMENT_PACK_P (ot) || ARGUMENT_PACK_P (nt))
9255 return cp_tree_equal (ot, nt);
9256 else if (TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
9257 gcc_unreachable ();
9258 else if (TYPE_P (nt) || TYPE_P (ot))
9260 if (!(TYPE_P (nt) && TYPE_P (ot)))
9261 return false;
9262 return same_type_p (ot, nt);
9264 else
9266 /* Try to treat a template non-type argument that has been converted
9267 to the parameter type as equivalent to one that hasn't yet. */
9268 for (enum tree_code code1 = TREE_CODE (ot);
9269 CONVERT_EXPR_CODE_P (code1)
9270 || code1 == NON_LVALUE_EXPR;
9271 code1 = TREE_CODE (ot))
9272 ot = TREE_OPERAND (ot, 0);
9274 for (enum tree_code code2 = TREE_CODE (nt);
9275 CONVERT_EXPR_CODE_P (code2)
9276 || code2 == NON_LVALUE_EXPR;
9277 code2 = TREE_CODE (nt))
9278 nt = TREE_OPERAND (nt, 0);
9280 return cp_tree_equal (ot, nt);
9284 /* Returns true iff the OLDARGS and NEWARGS are in fact identical sets of
9285 template arguments. Returns false otherwise, and updates OLDARG_PTR and
9286 NEWARG_PTR with the offending arguments if they are non-NULL. */
9288 bool
9289 comp_template_args (tree oldargs, tree newargs,
9290 tree *oldarg_ptr /* = NULL */, tree *newarg_ptr /* = NULL */,
9291 bool partial_order /* = false */)
9293 if (oldargs == newargs)
9294 return true;
9296 if (!oldargs || !newargs)
9297 return false;
9299 if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
9300 return false;
9302 for (int i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
9304 tree nt = TREE_VEC_ELT (newargs, i);
9305 tree ot = TREE_VEC_ELT (oldargs, i);
9307 if (! template_args_equal (ot, nt, partial_order))
9309 if (oldarg_ptr != NULL)
9310 *oldarg_ptr = ot;
9311 if (newarg_ptr != NULL)
9312 *newarg_ptr = nt;
9313 return false;
9316 return true;
9319 inline bool
9320 comp_template_args_porder (tree oargs, tree nargs)
9322 return comp_template_args (oargs, nargs, NULL, NULL, true);
9325 /* Implement a freelist interface for objects of type T.
9327 Head is a separate object, rather than a regular member, so that we
9328 can define it as a GTY deletable pointer, which is highly
9329 desirable. A data member could be declared that way, but then the
9330 containing object would implicitly get GTY((user)), which would
9331 prevent us from instantiating freelists as global objects.
9332 Although this way we can create freelist global objects, they're
9333 such thin wrappers that instantiating temporaries at every use
9334 loses nothing and saves permanent storage for the freelist object.
9336 Member functions next, anew, poison and reinit have default
9337 implementations that work for most of the types we're interested
9338 in, but if they don't work for some type, they should be explicitly
9339 specialized. See the comments before them for requirements, and
9340 the example specializations for the tree_list_freelist. */
9341 template <typename T>
9342 class freelist
9344 /* Return the next object in a chain. We could just do type
9345 punning, but if we access the object with its underlying type, we
9346 avoid strict-aliasing trouble. This needs only work between
9347 poison and reinit. */
9348 static T *&next (T *obj) { return obj->next; }
9350 /* Return a newly allocated, uninitialized or minimally-initialized
9351 object of type T. Any initialization performed by anew should
9352 either remain across the life of the object and the execution of
9353 poison, or be redone by reinit. */
9354 static T *anew () { return ggc_alloc<T> (); }
9356 /* Optionally scribble all over the bits holding the object, so that
9357 they become (mostly?) uninitialized memory. This is called while
9358 preparing to make the object part of the free list. */
9359 static void poison (T *obj) {
9360 T *p ATTRIBUTE_UNUSED = obj;
9361 T **q ATTRIBUTE_UNUSED = &next (obj);
9363 #ifdef ENABLE_GC_CHECKING
9364 /* Poison the data, to indicate the data is garbage. */
9365 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, sizeof (*p)));
9366 memset (p, 0xa5, sizeof (*p));
9367 #endif
9368 /* Let valgrind know the object is free. */
9369 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, sizeof (*p)));
9371 /* Let valgrind know the next portion of the object is available,
9372 but uninitialized. */
9373 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
9376 /* Bring an object that underwent at least one lifecycle after anew
9377 and before the most recent free and poison, back to a usable
9378 state, reinitializing whatever is needed for it to be
9379 functionally equivalent to an object just allocated and returned
9380 by anew. This may poison or clear the next field, used by
9381 freelist housekeeping after poison was called. */
9382 static void reinit (T *obj) {
9383 T **q ATTRIBUTE_UNUSED = &next (obj);
9385 #ifdef ENABLE_GC_CHECKING
9386 memset (q, 0xa5, sizeof (*q));
9387 #endif
9388 /* Let valgrind know the entire object is available, but
9389 uninitialized. */
9390 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (*obj)));
9393 /* Reference a GTY-deletable pointer that points to the first object
9394 in the free list proper. */
9395 T *&head;
9396 public:
9397 /* Construct a freelist object chaining objects off of HEAD. */
9398 freelist (T *&head) : head(head) {}
9400 /* Add OBJ to the free object list. The former head becomes OBJ's
9401 successor. */
9402 void free (T *obj)
9404 poison (obj);
9405 next (obj) = head;
9406 head = obj;
9409 /* Take an object from the free list, if one is available, or
9410 allocate a new one. Objects taken from the free list should be
9411 regarded as filled with garbage, except for bits that are
9412 configured to be preserved across free and alloc. */
9413 T *alloc ()
9415 if (head)
9417 T *obj = head;
9418 head = next (head);
9419 reinit (obj);
9420 return obj;
9422 else
9423 return anew ();
9427 /* Explicitly specialize the interfaces for freelist<tree_node>: we
9428 want to allocate a TREE_LIST using the usual interface, and ensure
9429 TREE_CHAIN remains functional. Alas, we have to duplicate a bit of
9430 build_tree_list logic in reinit, so this could go out of sync. */
9431 template <>
9432 inline tree &
9433 freelist<tree_node>::next (tree obj)
9435 return TREE_CHAIN (obj);
9437 template <>
9438 inline tree
9439 freelist<tree_node>::anew ()
9441 return build_tree_list (NULL, NULL);
9443 template <>
9444 inline void
9445 freelist<tree_node>::poison (tree obj ATTRIBUTE_UNUSED)
9447 int size ATTRIBUTE_UNUSED = sizeof (tree_list);
9448 tree p ATTRIBUTE_UNUSED = obj;
9449 tree_base *b ATTRIBUTE_UNUSED = &obj->base;
9450 tree *q ATTRIBUTE_UNUSED = &next (obj);
9452 #ifdef ENABLE_GC_CHECKING
9453 gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
9455 /* Poison the data, to indicate the data is garbage. */
9456 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, size));
9457 memset (p, 0xa5, size);
9458 #endif
9459 /* Let valgrind know the object is free. */
9460 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, size));
9461 /* But we still want to use the TREE_CODE and TREE_CHAIN parts. */
9462 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9463 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
9465 #ifdef ENABLE_GC_CHECKING
9466 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (b, sizeof (*b)));
9467 /* Keep TREE_CHAIN functional. */
9468 TREE_SET_CODE (obj, TREE_LIST);
9469 #else
9470 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9471 #endif
9473 template <>
9474 inline void
9475 freelist<tree_node>::reinit (tree obj ATTRIBUTE_UNUSED)
9477 tree_base *b ATTRIBUTE_UNUSED = &obj->base;
9479 #ifdef ENABLE_GC_CHECKING
9480 gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
9481 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
9482 memset (obj, 0, sizeof (tree_list));
9483 #endif
9485 /* Let valgrind know the entire object is available, but
9486 uninitialized. */
9487 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
9489 #ifdef ENABLE_GC_CHECKING
9490 TREE_SET_CODE (obj, TREE_LIST);
9491 #else
9492 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9493 #endif
9496 /* Point to the first object in the TREE_LIST freelist. */
9497 static GTY((deletable)) tree tree_list_freelist_head;
9498 /* Return the/an actual TREE_LIST freelist. */
9499 static inline freelist<tree_node>
9500 tree_list_freelist ()
9502 return tree_list_freelist_head;
9505 /* Point to the first object in the tinst_level freelist. */
9506 static GTY((deletable)) tinst_level *tinst_level_freelist_head;
9507 /* Return the/an actual tinst_level freelist. */
9508 static inline freelist<tinst_level>
9509 tinst_level_freelist ()
9511 return tinst_level_freelist_head;
9514 /* Point to the first object in the pending_template freelist. */
9515 static GTY((deletable)) pending_template *pending_template_freelist_head;
9516 /* Return the/an actual pending_template freelist. */
9517 static inline freelist<pending_template>
9518 pending_template_freelist ()
9520 return pending_template_freelist_head;
9523 /* Build the TREE_LIST object out of a split list, store it
9524 permanently, and return it. */
9525 tree
9526 tinst_level::to_list ()
9528 gcc_assert (split_list_p ());
9529 tree ret = tree_list_freelist ().alloc ();
9530 TREE_PURPOSE (ret) = tldcl;
9531 TREE_VALUE (ret) = targs;
9532 tldcl = ret;
9533 targs = NULL;
9534 gcc_assert (tree_list_p ());
9535 return ret;
9538 const unsigned short tinst_level::refcount_infinity;
9540 /* Increment OBJ's refcount unless it is already infinite. */
9541 static tinst_level *
9542 inc_refcount_use (tinst_level *obj)
9544 if (obj && obj->refcount != tinst_level::refcount_infinity)
9545 ++obj->refcount;
9546 return obj;
9549 /* Release storage for OBJ and node, if it's a TREE_LIST. */
9550 void
9551 tinst_level::free (tinst_level *obj)
9553 if (obj->tree_list_p ())
9554 tree_list_freelist ().free (obj->get_node ());
9555 tinst_level_freelist ().free (obj);
9558 /* Decrement OBJ's refcount if not infinite. If it reaches zero, release
9559 OBJ's DECL and OBJ, and start over with the tinst_level object that
9560 used to be referenced by OBJ's NEXT. */
9561 static void
9562 dec_refcount_use (tinst_level *obj)
9564 while (obj
9565 && obj->refcount != tinst_level::refcount_infinity
9566 && !--obj->refcount)
9568 tinst_level *next = obj->next;
9569 tinst_level::free (obj);
9570 obj = next;
9574 /* Modify PTR so that it points to OBJ, adjusting the refcounts of OBJ
9575 and of the former PTR. Omitting the second argument is equivalent
9576 to passing (T*)NULL; this is allowed because passing the
9577 zero-valued integral constant NULL confuses type deduction and/or
9578 overload resolution. */
9579 template <typename T>
9580 static void
9581 set_refcount_ptr (T *& ptr, T *obj = NULL)
9583 T *save = ptr;
9584 ptr = inc_refcount_use (obj);
9585 dec_refcount_use (save);
9588 static void
9589 add_pending_template (tree d)
9591 tree ti = (TYPE_P (d)
9592 ? CLASSTYPE_TEMPLATE_INFO (d)
9593 : DECL_TEMPLATE_INFO (d));
9594 struct pending_template *pt;
9595 int level;
9597 if (TI_PENDING_TEMPLATE_FLAG (ti))
9598 return;
9600 /* We are called both from instantiate_decl, where we've already had a
9601 tinst_level pushed, and instantiate_template, where we haven't.
9602 Compensate. */
9603 gcc_assert (TREE_CODE (d) != TREE_LIST);
9604 level = !current_tinst_level
9605 || current_tinst_level->maybe_get_node () != d;
9607 if (level)
9608 push_tinst_level (d);
9610 pt = pending_template_freelist ().alloc ();
9611 pt->next = NULL;
9612 pt->tinst = NULL;
9613 set_refcount_ptr (pt->tinst, current_tinst_level);
9614 if (last_pending_template)
9615 last_pending_template->next = pt;
9616 else
9617 pending_templates = pt;
9619 last_pending_template = pt;
9621 TI_PENDING_TEMPLATE_FLAG (ti) = 1;
9623 if (level)
9624 pop_tinst_level ();
9628 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
9629 ARGLIST. Valid choices for FNS are given in the cp-tree.def
9630 documentation for TEMPLATE_ID_EXPR. */
9632 tree
9633 lookup_template_function (tree fns, tree arglist)
9635 if (fns == error_mark_node || arglist == error_mark_node)
9636 return error_mark_node;
9638 gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
9640 if (!is_overloaded_fn (fns) && !identifier_p (fns))
9642 error ("%q#D is not a function template", fns);
9643 return error_mark_node;
9646 if (BASELINK_P (fns))
9648 fns = copy_node (fns);
9649 BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
9650 unknown_type_node,
9651 BASELINK_FUNCTIONS (fns),
9652 arglist);
9653 return fns;
9656 return build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, arglist);
9659 /* Within the scope of a template class S<T>, the name S gets bound
9660 (in build_self_reference) to a TYPE_DECL for the class, not a
9661 TEMPLATE_DECL. If DECL is a TYPE_DECL for current_class_type,
9662 or one of its enclosing classes, and that type is a template,
9663 return the associated TEMPLATE_DECL. Otherwise, the original
9664 DECL is returned.
9666 Also handle the case when DECL is a TREE_LIST of ambiguous
9667 injected-class-names from different bases. */
9669 tree
9670 maybe_get_template_decl_from_type_decl (tree decl)
9672 if (decl == NULL_TREE)
9673 return decl;
9675 /* DR 176: A lookup that finds an injected-class-name (10.2
9676 [class.member.lookup]) can result in an ambiguity in certain cases
9677 (for example, if it is found in more than one base class). If all of
9678 the injected-class-names that are found refer to specializations of
9679 the same class template, and if the name is followed by a
9680 template-argument-list, the reference refers to the class template
9681 itself and not a specialization thereof, and is not ambiguous. */
9682 if (TREE_CODE (decl) == TREE_LIST)
9684 tree t, tmpl = NULL_TREE;
9685 for (t = decl; t; t = TREE_CHAIN (t))
9687 tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
9688 if (!tmpl)
9689 tmpl = elt;
9690 else if (tmpl != elt)
9691 break;
9693 if (tmpl && t == NULL_TREE)
9694 return tmpl;
9695 else
9696 return decl;
9699 return (decl != NULL_TREE
9700 && DECL_SELF_REFERENCE_P (decl)
9701 && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
9702 ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
9705 /* Given an IDENTIFIER_NODE (or type TEMPLATE_DECL) and a chain of
9706 parameters, find the desired type.
9708 D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
9710 IN_DECL, if non-NULL, is the template declaration we are trying to
9711 instantiate.
9713 If ENTERING_SCOPE is nonzero, we are about to enter the scope of
9714 the class we are looking up.
9716 Issue error and warning messages under control of COMPLAIN.
9718 If the template class is really a local class in a template
9719 function, then the FUNCTION_CONTEXT is the function in which it is
9720 being instantiated.
9722 ??? Note that this function is currently called *twice* for each
9723 template-id: the first time from the parser, while creating the
9724 incomplete type (finish_template_type), and the second type during the
9725 real instantiation (instantiate_template_class). This is surely something
9726 that we want to avoid. It also causes some problems with argument
9727 coercion (see convert_nontype_argument for more information on this). */
9729 tree
9730 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
9731 int entering_scope, tsubst_flags_t complain)
9733 auto_timevar tv (TV_TEMPLATE_INST);
9735 tree templ = NULL_TREE, parmlist;
9736 tree t;
9737 spec_entry **slot;
9738 spec_entry *entry;
9739 spec_entry elt;
9740 hashval_t hash;
9742 if (identifier_p (d1))
9744 tree value = innermost_non_namespace_value (d1);
9745 if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
9746 templ = value;
9747 else
9749 if (context)
9750 push_decl_namespace (context);
9751 templ = lookup_name (d1);
9752 templ = maybe_get_template_decl_from_type_decl (templ);
9753 if (context)
9754 pop_decl_namespace ();
9757 else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
9759 tree type = TREE_TYPE (d1);
9761 /* If we are declaring a constructor, say A<T>::A<T>, we will get
9762 an implicit typename for the second A. Deal with it. */
9763 if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
9764 type = TREE_TYPE (type);
9766 if (CLASSTYPE_TEMPLATE_INFO (type))
9768 templ = CLASSTYPE_TI_TEMPLATE (type);
9769 d1 = DECL_NAME (templ);
9772 else if (TREE_CODE (d1) == ENUMERAL_TYPE
9773 || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
9775 templ = TYPE_TI_TEMPLATE (d1);
9776 d1 = DECL_NAME (templ);
9778 else if (DECL_TYPE_TEMPLATE_P (d1))
9780 templ = d1;
9781 d1 = DECL_NAME (templ);
9783 else if (DECL_TEMPLATE_TEMPLATE_PARM_P (d1))
9785 templ = d1;
9786 d1 = DECL_NAME (templ);
9789 /* Issue an error message if we didn't find a template. */
9790 if (! templ)
9792 if (complain & tf_error)
9793 error ("%qT is not a template", d1);
9794 return error_mark_node;
9797 if (TREE_CODE (templ) != TEMPLATE_DECL
9798 /* Make sure it's a user visible template, if it was named by
9799 the user. */
9800 || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
9801 && !PRIMARY_TEMPLATE_P (templ)))
9803 if (complain & tf_error)
9805 error ("non-template type %qT used as a template", d1);
9806 if (in_decl)
9807 error ("for template declaration %q+D", in_decl);
9809 return error_mark_node;
9812 complain &= ~tf_user;
9814 /* An alias that just changes the name of a template is equivalent to the
9815 other template, so if any of the arguments are pack expansions, strip
9816 the alias to avoid problems with a pack expansion passed to a non-pack
9817 alias template parameter (DR 1430). */
9818 if (pack_expansion_args_count (INNERMOST_TEMPLATE_ARGS (arglist)))
9819 templ = get_underlying_template (templ);
9821 if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
9823 tree parm;
9824 tree arglist2 = coerce_template_args_for_ttp (templ, arglist, complain);
9825 if (arglist2 == error_mark_node
9826 || (!uses_template_parms (arglist2)
9827 && check_instantiated_args (templ, arglist2, complain)))
9828 return error_mark_node;
9830 parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
9831 return parm;
9833 else
9835 tree template_type = TREE_TYPE (templ);
9836 tree gen_tmpl;
9837 tree type_decl;
9838 tree found = NULL_TREE;
9839 int arg_depth;
9840 int parm_depth;
9841 int is_dependent_type;
9842 int use_partial_inst_tmpl = false;
9844 if (template_type == error_mark_node)
9845 /* An error occurred while building the template TEMPL, and a
9846 diagnostic has most certainly been emitted for that
9847 already. Let's propagate that error. */
9848 return error_mark_node;
9850 gen_tmpl = most_general_template (templ);
9851 if (modules_p ())
9852 lazy_load_pendings (gen_tmpl);
9854 parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
9855 parm_depth = TMPL_PARMS_DEPTH (parmlist);
9856 arg_depth = TMPL_ARGS_DEPTH (arglist);
9858 if (arg_depth == 1 && parm_depth > 1)
9860 /* We've been given an incomplete set of template arguments.
9861 For example, given:
9863 template <class T> struct S1 {
9864 template <class U> struct S2 {};
9865 template <class U> struct S2<U*> {};
9868 we will be called with an ARGLIST of `U*', but the
9869 TEMPLATE will be `template <class T> template
9870 <class U> struct S1<T>::S2'. We must fill in the missing
9871 arguments. */
9872 tree ti = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (templ));
9873 arglist = add_outermost_template_args (TI_ARGS (ti), arglist);
9874 arg_depth = TMPL_ARGS_DEPTH (arglist);
9877 /* Now we should have enough arguments. */
9878 gcc_assert (parm_depth == arg_depth);
9880 /* From here on, we're only interested in the most general
9881 template. */
9883 /* Shortcut looking up the current class scope again. */
9884 if (current_class_type)
9885 if (tree ti = CLASSTYPE_TEMPLATE_INFO (current_class_type))
9886 if (gen_tmpl == most_general_template (TI_TEMPLATE (ti))
9887 && comp_template_args (arglist, TI_ARGS (ti)))
9888 return current_class_type;
9890 /* Calculate the BOUND_ARGS. These will be the args that are
9891 actually tsubst'd into the definition to create the
9892 instantiation. */
9893 arglist = coerce_template_parms (parmlist, arglist, gen_tmpl, complain);
9895 if (arglist == error_mark_node)
9896 /* We were unable to bind the arguments. */
9897 return error_mark_node;
9899 /* In the scope of a template class, explicit references to the
9900 template class refer to the type of the template, not any
9901 instantiation of it. For example, in:
9903 template <class T> class C { void f(C<T>); }
9905 the `C<T>' is just the same as `C'. Outside of the
9906 class, however, such a reference is an instantiation. */
9907 if (entering_scope
9908 || !PRIMARY_TEMPLATE_P (gen_tmpl)
9909 || currently_open_class (template_type))
9911 tree tinfo = TYPE_TEMPLATE_INFO (template_type);
9913 if (tinfo && comp_template_args (TI_ARGS (tinfo), arglist))
9914 return template_type;
9917 /* If we already have this specialization, return it. */
9918 elt.tmpl = gen_tmpl;
9919 elt.args = arglist;
9920 elt.spec = NULL_TREE;
9921 hash = spec_hasher::hash (&elt);
9922 entry = type_specializations->find_with_hash (&elt, hash);
9924 if (entry)
9925 return entry->spec;
9927 /* If the template's constraints are not satisfied,
9928 then we cannot form a valid type.
9930 Note that the check is deferred until after the hash
9931 lookup. This prevents redundant checks on previously
9932 instantiated specializations. */
9933 if (flag_concepts
9934 && !DECL_ALIAS_TEMPLATE_P (gen_tmpl)
9935 && !constraints_satisfied_p (gen_tmpl, arglist))
9937 if (complain & tf_error)
9939 auto_diagnostic_group d;
9940 error ("template constraint failure for %qD", gen_tmpl);
9941 diagnose_constraints (input_location, gen_tmpl, arglist);
9943 return error_mark_node;
9946 is_dependent_type = uses_template_parms (arglist);
9948 /* If the deduced arguments are invalid, then the binding
9949 failed. */
9950 if (!is_dependent_type
9951 && check_instantiated_args (gen_tmpl,
9952 INNERMOST_TEMPLATE_ARGS (arglist),
9953 complain))
9954 return error_mark_node;
9956 if (!is_dependent_type
9957 && !PRIMARY_TEMPLATE_P (gen_tmpl)
9958 && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
9959 && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
9960 /* This occurs when the user has tried to define a tagged type
9961 in a scope that forbids it. We emitted an error during the
9962 parse. We didn't complete the bail out then, so here we
9963 are. */
9964 return error_mark_node;
9966 context = DECL_CONTEXT (gen_tmpl);
9967 if (context && TYPE_P (context))
9969 if (!uses_template_parms (DECL_CONTEXT (templ)))
9970 /* If the context of the partially instantiated template is
9971 already non-dependent, then we might as well use it. */
9972 context = DECL_CONTEXT (templ);
9973 else
9975 context = tsubst_aggr_type (context, arglist,
9976 complain, in_decl, true);
9977 /* Try completing the enclosing context if it's not already so. */
9978 if (context != error_mark_node
9979 && !COMPLETE_TYPE_P (context))
9981 context = complete_type (context);
9982 if (COMPLETE_TYPE_P (context))
9984 /* Completion could have caused us to register the desired
9985 specialization already, so check the table again. */
9986 entry = type_specializations->find_with_hash (&elt, hash);
9987 if (entry)
9988 return entry->spec;
9993 else
9994 context = tsubst (context, arglist, complain, in_decl);
9996 if (context == error_mark_node)
9997 return error_mark_node;
9999 if (!context)
10000 context = global_namespace;
10002 /* Create the type. */
10003 if (DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10005 /* The user referred to a specialization of an alias
10006 template represented by GEN_TMPL.
10008 [temp.alias]/2 says:
10010 When a template-id refers to the specialization of an
10011 alias template, it is equivalent to the associated
10012 type obtained by substitution of its
10013 template-arguments for the template-parameters in the
10014 type-id of the alias template. */
10016 t = tsubst (TREE_TYPE (gen_tmpl), arglist, complain, in_decl);
10017 /* Note that the call above (by indirectly calling
10018 register_specialization in tsubst_decl) registers the
10019 TYPE_DECL representing the specialization of the alias
10020 template. So next time someone substitutes ARGLIST for
10021 the template parms into the alias template (GEN_TMPL),
10022 she'll get that TYPE_DECL back. */
10024 if (t == error_mark_node)
10025 return t;
10027 else if (TREE_CODE (template_type) == ENUMERAL_TYPE)
10029 if (!is_dependent_type)
10031 set_current_access_from_decl (TYPE_NAME (template_type));
10032 t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
10033 tsubst (ENUM_UNDERLYING_TYPE (template_type),
10034 arglist, complain, in_decl),
10035 tsubst_attributes (TYPE_ATTRIBUTES (template_type),
10036 arglist, complain, in_decl),
10037 SCOPED_ENUM_P (template_type), NULL);
10039 if (t == error_mark_node)
10040 return t;
10042 else
10044 /* We don't want to call start_enum for this type, since
10045 the values for the enumeration constants may involve
10046 template parameters. And, no one should be interested
10047 in the enumeration constants for such a type. */
10048 t = cxx_make_type (ENUMERAL_TYPE);
10049 SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
10051 SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
10052 ENUM_FIXED_UNDERLYING_TYPE_P (t)
10053 = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
10055 else if (CLASS_TYPE_P (template_type))
10057 /* Lambda closures are regenerated in tsubst_lambda_expr, not
10058 instantiated here. */
10059 gcc_assert (!LAMBDA_TYPE_P (template_type));
10061 t = make_class_type (TREE_CODE (template_type));
10062 CLASSTYPE_DECLARED_CLASS (t)
10063 = CLASSTYPE_DECLARED_CLASS (template_type);
10064 SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
10066 /* A local class. Make sure the decl gets registered properly. */
10067 if (context == current_function_decl)
10068 if (pushtag (DECL_NAME (gen_tmpl), t)
10069 == error_mark_node)
10070 return error_mark_node;
10072 if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
10073 /* This instantiation is another name for the primary
10074 template type. Set the TYPE_CANONICAL field
10075 appropriately. */
10076 TYPE_CANONICAL (t) = template_type;
10077 else if (any_template_arguments_need_structural_equality_p (arglist))
10078 SET_TYPE_STRUCTURAL_EQUALITY (t);
10080 else
10081 gcc_unreachable ();
10083 /* If we called start_enum or pushtag above, this information
10084 will already be set up. */
10085 type_decl = TYPE_NAME (t);
10086 if (!type_decl)
10088 TYPE_CONTEXT (t) = FROB_CONTEXT (context);
10090 type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
10091 DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
10092 DECL_SOURCE_LOCATION (type_decl)
10093 = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
10096 set_instantiating_module (type_decl);
10097 /* Although GEN_TMPL is the TEMPLATE_DECL, it has the same value
10098 of export flag. We want to propagate this because it might
10099 be a friend declaration that pushes a new hidden binding. */
10100 DECL_MODULE_EXPORT_P (type_decl) = DECL_MODULE_EXPORT_P (gen_tmpl);
10102 if (CLASS_TYPE_P (template_type))
10104 TREE_PRIVATE (type_decl)
10105 = TREE_PRIVATE (TYPE_MAIN_DECL (template_type));
10106 TREE_PROTECTED (type_decl)
10107 = TREE_PROTECTED (TYPE_MAIN_DECL (template_type));
10108 if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
10110 DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
10111 DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
10115 if (OVERLOAD_TYPE_P (t)
10116 && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10118 static const char *tags[] = {"abi_tag", "may_alias"};
10120 for (unsigned ix = 0; ix != 2; ix++)
10122 tree attributes
10123 = lookup_attribute (tags[ix], TYPE_ATTRIBUTES (template_type));
10125 if (attributes)
10126 TYPE_ATTRIBUTES (t)
10127 = tree_cons (TREE_PURPOSE (attributes),
10128 TREE_VALUE (attributes),
10129 TYPE_ATTRIBUTES (t));
10133 /* Let's consider the explicit specialization of a member
10134 of a class template specialization that is implicitly instantiated,
10135 e.g.:
10136 template<class T>
10137 struct S
10139 template<class U> struct M {}; //#0
10142 template<>
10143 template<>
10144 struct S<int>::M<char> //#1
10146 int i;
10148 [temp.expl.spec]/4 says this is valid.
10150 In this case, when we write:
10151 S<int>::M<char> m;
10153 M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
10154 the one of #0.
10156 When we encounter #1, we want to store the partial instantiation
10157 of M (template<class T> S<int>::M<T>) in its CLASSTYPE_TI_TEMPLATE.
10159 For all cases other than this "explicit specialization of member of a
10160 class template", we just want to store the most general template into
10161 the CLASSTYPE_TI_TEMPLATE of M.
10163 This case of "explicit specialization of member of a class template"
10164 only happens when:
10165 1/ the enclosing class is an instantiation of, and therefore not
10166 the same as, the context of the most general template, and
10167 2/ we aren't looking at the partial instantiation itself, i.e.
10168 the innermost arguments are not the same as the innermost parms of
10169 the most general template.
10171 So it's only when 1/ and 2/ happens that we want to use the partial
10172 instantiation of the member template in lieu of its most general
10173 template. */
10175 if (PRIMARY_TEMPLATE_P (gen_tmpl)
10176 && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
10177 /* the enclosing class must be an instantiation... */
10178 && CLASS_TYPE_P (context)
10179 && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
10181 TREE_VEC_LENGTH (arglist)--;
10182 ++processing_template_decl;
10183 tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (gen_tmpl));
10184 tree partial_inst_args =
10185 tsubst (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)),
10186 arglist, complain, NULL_TREE);
10187 --processing_template_decl;
10188 TREE_VEC_LENGTH (arglist)++;
10189 if (partial_inst_args == error_mark_node)
10190 return error_mark_node;
10191 use_partial_inst_tmpl =
10192 /*...and we must not be looking at the partial instantiation
10193 itself. */
10194 !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
10195 partial_inst_args);
10198 if (!use_partial_inst_tmpl)
10199 /* This case is easy; there are no member templates involved. */
10200 found = gen_tmpl;
10201 else
10203 /* This is a full instantiation of a member template. Find
10204 the partial instantiation of which this is an instance. */
10206 /* Temporarily reduce by one the number of levels in the ARGLIST
10207 so as to avoid comparing the last set of arguments. */
10208 TREE_VEC_LENGTH (arglist)--;
10209 /* We don't use COMPLAIN in the following call because this isn't
10210 the immediate context of deduction. For instance, tf_partial
10211 could be set here as we might be at the beginning of template
10212 argument deduction when any explicitly specified template
10213 arguments are substituted into the function type. tf_partial
10214 could lead into trouble because we wouldn't find the partial
10215 instantiation that might have been created outside tf_partial
10216 context, because the levels of template parameters wouldn't
10217 match, because in a tf_partial context, tsubst doesn't reduce
10218 TEMPLATE_PARM_LEVEL. */
10219 found = tsubst (gen_tmpl, arglist, tf_none, NULL_TREE);
10220 TREE_VEC_LENGTH (arglist)++;
10221 /* FOUND is either a proper class type, or an alias
10222 template specialization. In the later case, it's a
10223 TYPE_DECL, resulting from the substituting of arguments
10224 for parameters in the TYPE_DECL of the alias template
10225 done earlier. So be careful while getting the template
10226 of FOUND. */
10227 found = (TREE_CODE (found) == TEMPLATE_DECL
10228 ? found
10229 : (TREE_CODE (found) == TYPE_DECL
10230 ? DECL_TI_TEMPLATE (found)
10231 : CLASSTYPE_TI_TEMPLATE (found)));
10233 if (DECL_CLASS_TEMPLATE_P (found)
10234 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (found)))
10236 /* If this partial instantiation is specialized, we want to
10237 use it for hash table lookup. */
10238 elt.tmpl = found;
10239 elt.args = arglist = INNERMOST_TEMPLATE_ARGS (arglist);
10240 hash = spec_hasher::hash (&elt);
10244 /* Build template info for the new specialization. */
10245 SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
10247 elt.spec = t;
10248 slot = type_specializations->find_slot_with_hash (&elt, hash, INSERT);
10249 gcc_checking_assert (*slot == NULL);
10250 entry = ggc_alloc<spec_entry> ();
10251 *entry = elt;
10252 *slot = entry;
10254 /* Note this use of the partial instantiation so we can check it
10255 later in maybe_process_partial_specialization. */
10256 DECL_TEMPLATE_INSTANTIATIONS (found)
10257 = tree_cons (arglist, t,
10258 DECL_TEMPLATE_INSTANTIATIONS (found));
10260 if (TREE_CODE (template_type) == ENUMERAL_TYPE
10261 && !uses_template_parms (current_nonlambda_scope ())
10262 && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10263 /* Now that the type has been registered on the instantiations
10264 list, we set up the enumerators. Because the enumeration
10265 constants may involve the enumeration type itself, we make
10266 sure to register the type first, and then create the
10267 constants. That way, doing tsubst_expr for the enumeration
10268 constants won't result in recursive calls here; we'll find
10269 the instantiation and exit above. */
10270 tsubst_enum (template_type, t, arglist);
10272 if (CLASS_TYPE_P (template_type) && is_dependent_type)
10273 /* If the type makes use of template parameters, the
10274 code that generates debugging information will crash. */
10275 DECL_IGNORED_P (TYPE_MAIN_DECL (t)) = 1;
10277 /* Possibly limit visibility based on template args. */
10278 TREE_PUBLIC (type_decl) = 1;
10279 determine_visibility (type_decl);
10281 inherit_targ_abi_tags (t);
10283 return t;
10287 /* Return a TEMPLATE_ID_EXPR for the given variable template and ARGLIST. */
10289 tree
10290 lookup_template_variable (tree templ, tree arglist)
10292 if (flag_concepts && variable_concept_p (templ))
10293 return build_concept_check (templ, arglist, tf_none);
10295 /* The type of the expression is NULL_TREE since the template-id could refer
10296 to an explicit or partial specialization. */
10297 return build2 (TEMPLATE_ID_EXPR, NULL_TREE, templ, arglist);
10300 /* Instantiate a variable declaration from a TEMPLATE_ID_EXPR for use. */
10302 tree
10303 finish_template_variable (tree var, tsubst_flags_t complain)
10305 tree templ = TREE_OPERAND (var, 0);
10306 tree arglist = TREE_OPERAND (var, 1);
10308 tree parms = DECL_TEMPLATE_PARMS (templ);
10309 arglist = coerce_template_parms (parms, arglist, templ, complain);
10310 if (arglist == error_mark_node)
10311 return error_mark_node;
10313 if (flag_concepts && !constraints_satisfied_p (templ, arglist))
10315 if (complain & tf_error)
10317 auto_diagnostic_group d;
10318 error ("use of invalid variable template %qE", var);
10319 diagnose_constraints (location_of (var), templ, arglist);
10321 return error_mark_node;
10324 return instantiate_template (templ, arglist, complain);
10327 /* Construct a TEMPLATE_ID_EXPR for the given variable template TEMPL having
10328 TARGS template args, and instantiate it if it's not dependent. */
10330 tree
10331 lookup_and_finish_template_variable (tree templ, tree targs,
10332 tsubst_flags_t complain)
10334 tree var = lookup_template_variable (templ, targs);
10335 if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (templ)) == 1
10336 && !any_dependent_template_arguments_p (targs))
10338 var = finish_template_variable (var, complain);
10339 mark_used (var);
10342 return convert_from_reference (var);
10345 /* If the set of template parameters PARMS contains a template parameter
10346 at the given LEVEL and INDEX, then return this parameter. Otherwise
10347 return NULL_TREE. */
10349 static tree
10350 corresponding_template_parameter (tree parms, int level, int index)
10352 while (TMPL_PARMS_DEPTH (parms) > level)
10353 parms = TREE_CHAIN (parms);
10355 if (TMPL_PARMS_DEPTH (parms) != level
10356 || TREE_VEC_LENGTH (TREE_VALUE (parms)) <= index)
10357 return NULL_TREE;
10359 tree t = TREE_VALUE (TREE_VEC_ELT (TREE_VALUE (parms), index));
10360 /* As in template_parm_to_arg. */
10361 if (TREE_CODE (t) == TYPE_DECL || TREE_CODE (t) == TEMPLATE_DECL)
10362 t = TREE_TYPE (t);
10363 else
10364 t = DECL_INITIAL (t);
10366 gcc_assert (TEMPLATE_PARM_P (t));
10367 return t;
10370 /* Return the template parameter from PARMS that positionally corresponds
10371 to the template parameter PARM, or else return NULL_TREE. */
10373 static tree
10374 corresponding_template_parameter (tree parms, tree parm)
10376 int level, index;
10377 template_parm_level_and_index (parm, &level, &index);
10378 return corresponding_template_parameter (parms, level, index);
10382 struct pair_fn_data
10384 tree_fn_t fn;
10385 tree_fn_t any_fn;
10386 void *data;
10387 /* True when we should also visit template parameters that occur in
10388 non-deduced contexts. */
10389 bool include_nondeduced_p;
10390 hash_set<tree> *visited;
10393 /* Called from for_each_template_parm via walk_tree. */
10395 static tree
10396 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
10398 tree t = *tp;
10399 struct pair_fn_data *pfd = (struct pair_fn_data *) d;
10400 tree_fn_t fn = pfd->fn;
10401 void *data = pfd->data;
10402 tree result = NULL_TREE;
10404 #define WALK_SUBTREE(NODE) \
10405 do \
10407 result = for_each_template_parm (NODE, fn, data, pfd->visited, \
10408 pfd->include_nondeduced_p, \
10409 pfd->any_fn); \
10410 if (result) goto out; \
10412 while (0)
10414 if (pfd->any_fn && (*pfd->any_fn)(t, data))
10415 return t;
10417 if (TYPE_P (t)
10418 && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE))
10419 WALK_SUBTREE (TYPE_CONTEXT (t));
10421 switch (TREE_CODE (t))
10423 case RECORD_TYPE:
10424 if (TYPE_PTRMEMFUNC_P (t))
10425 break;
10426 /* Fall through. */
10428 case UNION_TYPE:
10429 case ENUMERAL_TYPE:
10430 if (!TYPE_TEMPLATE_INFO (t))
10431 *walk_subtrees = 0;
10432 else
10433 WALK_SUBTREE (TYPE_TI_ARGS (t));
10434 break;
10436 case INTEGER_TYPE:
10437 WALK_SUBTREE (TYPE_MIN_VALUE (t));
10438 WALK_SUBTREE (TYPE_MAX_VALUE (t));
10439 break;
10441 case METHOD_TYPE:
10442 /* Since we're not going to walk subtrees, we have to do this
10443 explicitly here. */
10444 WALK_SUBTREE (TYPE_METHOD_BASETYPE (t));
10445 /* Fall through. */
10447 case FUNCTION_TYPE:
10448 /* Check the return type. */
10449 WALK_SUBTREE (TREE_TYPE (t));
10451 /* Check the parameter types. Since default arguments are not
10452 instantiated until they are needed, the TYPE_ARG_TYPES may
10453 contain expressions that involve template parameters. But,
10454 no-one should be looking at them yet. And, once they're
10455 instantiated, they don't contain template parameters, so
10456 there's no point in looking at them then, either. */
10458 tree parm;
10460 for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
10461 WALK_SUBTREE (TREE_VALUE (parm));
10463 /* Since we've already handled the TYPE_ARG_TYPES, we don't
10464 want walk_tree walking into them itself. */
10465 *walk_subtrees = 0;
10468 if (flag_noexcept_type)
10470 tree spec = TYPE_RAISES_EXCEPTIONS (t);
10471 if (spec)
10472 WALK_SUBTREE (TREE_PURPOSE (spec));
10474 break;
10476 case TYPEOF_TYPE:
10477 case DECLTYPE_TYPE:
10478 if (pfd->include_nondeduced_p
10479 && for_each_template_parm (TYPE_VALUES_RAW (t), fn, data,
10480 pfd->visited,
10481 pfd->include_nondeduced_p,
10482 pfd->any_fn))
10483 return error_mark_node;
10484 *walk_subtrees = false;
10485 break;
10487 case TRAIT_TYPE:
10488 if (pfd->include_nondeduced_p)
10490 WALK_SUBTREE (TRAIT_TYPE_TYPE1 (t));
10491 WALK_SUBTREE (TRAIT_TYPE_TYPE2 (t));
10493 *walk_subtrees = false;
10494 break;
10496 case FUNCTION_DECL:
10497 case VAR_DECL:
10498 if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10499 WALK_SUBTREE (DECL_TI_ARGS (t));
10500 break;
10502 case PARM_DECL:
10503 WALK_SUBTREE (TREE_TYPE (t));
10504 break;
10506 case CONST_DECL:
10507 if (DECL_TEMPLATE_PARM_P (t))
10508 WALK_SUBTREE (DECL_INITIAL (t));
10509 if (DECL_CONTEXT (t)
10510 && pfd->include_nondeduced_p)
10511 WALK_SUBTREE (DECL_CONTEXT (t));
10512 break;
10514 case BOUND_TEMPLATE_TEMPLATE_PARM:
10515 /* Record template parameters such as `T' inside `TT<T>'. */
10516 WALK_SUBTREE (TYPE_TI_ARGS (t));
10517 /* Fall through. */
10519 case TEMPLATE_TEMPLATE_PARM:
10520 case TEMPLATE_TYPE_PARM:
10521 case TEMPLATE_PARM_INDEX:
10522 if (fn && (*fn)(t, data))
10523 return t;
10524 else if (!fn)
10525 return t;
10526 break;
10528 case TEMPLATE_DECL:
10529 /* A template template parameter is encountered. */
10530 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10531 WALK_SUBTREE (TREE_TYPE (t));
10533 /* Already substituted template template parameter */
10534 *walk_subtrees = 0;
10535 break;
10537 case TYPENAME_TYPE:
10538 /* A template-id in a TYPENAME_TYPE might be a deduced context after
10539 partial instantiation. */
10540 WALK_SUBTREE (TYPENAME_TYPE_FULLNAME (t));
10541 *walk_subtrees = 0;
10542 break;
10544 case INDIRECT_REF:
10545 case COMPONENT_REF:
10546 /* If there's no type, then this thing must be some expression
10547 involving template parameters. */
10548 if (!fn && !TREE_TYPE (t))
10549 return error_mark_node;
10550 break;
10552 case CONSTRUCTOR:
10553 case TRAIT_EXPR:
10554 case PLUS_EXPR:
10555 case MULT_EXPR:
10556 case SCOPE_REF:
10557 /* These are non-deduced contexts. */
10558 if (!pfd->include_nondeduced_p)
10559 *walk_subtrees = 0;
10560 break;
10562 case MODOP_EXPR:
10563 case CAST_EXPR:
10564 case IMPLICIT_CONV_EXPR:
10565 case REINTERPRET_CAST_EXPR:
10566 case CONST_CAST_EXPR:
10567 case STATIC_CAST_EXPR:
10568 case DYNAMIC_CAST_EXPR:
10569 case ARROW_EXPR:
10570 case DOTSTAR_EXPR:
10571 case TYPEID_EXPR:
10572 case PSEUDO_DTOR_EXPR:
10573 if (!fn)
10574 return error_mark_node;
10575 break;
10577 default:
10578 break;
10581 #undef WALK_SUBTREE
10583 /* We didn't find any template parameters we liked. */
10584 out:
10585 return result;
10588 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
10589 BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
10590 call FN with the parameter and the DATA.
10591 If FN returns nonzero, the iteration is terminated, and
10592 for_each_template_parm returns 1. Otherwise, the iteration
10593 continues. If FN never returns a nonzero value, the value
10594 returned by for_each_template_parm is 0. If FN is NULL, it is
10595 considered to be the function which always returns 1.
10597 If INCLUDE_NONDEDUCED_P, then this routine will also visit template
10598 parameters that occur in non-deduced contexts. When false, only
10599 visits those template parameters that can be deduced. */
10601 static tree
10602 for_each_template_parm (tree t, tree_fn_t fn, void* data,
10603 hash_set<tree> *visited,
10604 bool include_nondeduced_p,
10605 tree_fn_t any_fn)
10607 struct pair_fn_data pfd;
10608 tree result;
10610 /* Set up. */
10611 pfd.fn = fn;
10612 pfd.any_fn = any_fn;
10613 pfd.data = data;
10614 pfd.include_nondeduced_p = include_nondeduced_p;
10616 /* Walk the tree. (Conceptually, we would like to walk without
10617 duplicates, but for_each_template_parm_r recursively calls
10618 for_each_template_parm, so we would need to reorganize a fair
10619 bit to use walk_tree_without_duplicates, so we keep our own
10620 visited list.) */
10621 if (visited)
10622 pfd.visited = visited;
10623 else
10624 pfd.visited = new hash_set<tree>;
10625 result = cp_walk_tree (&t,
10626 for_each_template_parm_r,
10627 &pfd,
10628 pfd.visited);
10630 /* Clean up. */
10631 if (!visited)
10633 delete pfd.visited;
10634 pfd.visited = 0;
10637 return result;
10640 struct find_template_parameter_info
10642 explicit find_template_parameter_info (tree ctx_parms)
10643 : parm_list (NULL_TREE),
10644 ctx_parms (ctx_parms),
10645 max_depth (TMPL_PARMS_DEPTH (ctx_parms))
10648 hash_set<tree> visited;
10649 hash_set<tree> parms;
10650 tree parm_list;
10651 tree ctx_parms;
10652 int max_depth;
10655 /* Appends the declaration of T to the list in DATA. */
10657 static int
10658 keep_template_parm (tree t, void* data)
10660 find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
10662 /* Template parameters declared within the expression are not part of
10663 the parameter mapping. For example, in this concept:
10665 template<typename T>
10666 concept C = requires { <expr> } -> same_as<int>;
10668 the return specifier same_as<int> declares a new decltype parameter
10669 that must not be part of the parameter mapping. The same is true
10670 for generic lambda parameters, lambda template parameters, etc. */
10671 int level;
10672 int index;
10673 template_parm_level_and_index (t, &level, &index);
10674 if (level == 0 || level > ftpi->max_depth)
10675 return 0;
10677 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
10678 /* We want the underlying TEMPLATE_TEMPLATE_PARM, not the
10679 BOUND_TEMPLATE_TEMPLATE_PARM itself. */
10680 t = TREE_TYPE (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (t));
10682 /* This template parameter might be an argument to a cached dependent
10683 specalization that was formed earlier inside some other template, in
10684 which case the parameter is not among the ones that are in-scope.
10685 Look in CTX_PARMS to find the corresponding in-scope template
10686 parameter, and use it instead. */
10687 if (tree in_scope = corresponding_template_parameter (ftpi->ctx_parms, t))
10688 t = in_scope;
10690 /* Arguments like const T yield parameters like const T. This means that
10691 a template-id like X<T, const T> would yield two distinct parameters:
10692 T and const T. Adjust types to their unqualified versions. */
10693 if (TYPE_P (t))
10694 t = TYPE_MAIN_VARIANT (t);
10695 if (!ftpi->parms.add (t))
10696 ftpi->parm_list = tree_cons (NULL_TREE, t, ftpi->parm_list);
10698 /* Verify the parameter we found has a valid index. */
10699 if (flag_checking)
10701 tree parms = ftpi->ctx_parms;
10702 while (TMPL_PARMS_DEPTH (parms) > level)
10703 parms = TREE_CHAIN (parms);
10704 if (int len = TREE_VEC_LENGTH (TREE_VALUE (parms)))
10705 gcc_assert (index < len);
10708 return 0;
10711 /* Ensure that we recursively examine certain terms that are not normally
10712 visited in for_each_template_parm_r. */
10714 static int
10715 any_template_parm_r (tree t, void *data)
10717 find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
10719 #define WALK_SUBTREE(NODE) \
10720 do \
10722 for_each_template_parm (NODE, keep_template_parm, data, \
10723 &ftpi->visited, true, \
10724 any_template_parm_r); \
10726 while (0)
10728 /* A mention of a member alias/typedef is a use of all of its template
10729 arguments, including those from the enclosing class, so we don't use
10730 alias_template_specialization_p here. */
10731 if (TYPE_P (t) && typedef_variant_p (t))
10732 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
10733 WALK_SUBTREE (TI_ARGS (tinfo));
10735 switch (TREE_CODE (t))
10737 case TEMPLATE_TYPE_PARM:
10738 /* Type constraints of a placeholder type may contain parameters. */
10739 if (is_auto (t))
10740 if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (t))
10741 WALK_SUBTREE (constr);
10742 break;
10744 case TEMPLATE_ID_EXPR:
10745 /* Search through references to variable templates. */
10746 WALK_SUBTREE (TREE_OPERAND (t, 0));
10747 WALK_SUBTREE (TREE_OPERAND (t, 1));
10748 break;
10750 case TEMPLATE_PARM_INDEX:
10751 WALK_SUBTREE (TREE_TYPE (t));
10752 break;
10754 case TEMPLATE_DECL:
10755 /* If T is a member template that shares template parameters with
10756 ctx_parms, we need to mark all those parameters for mapping.
10757 To that end, it should suffice to just walk the DECL_CONTEXT of
10758 the template (assuming the template is not overly general). */
10759 WALK_SUBTREE (DECL_CONTEXT (t));
10760 break;
10762 case LAMBDA_EXPR:
10764 /* Look in the parms and body. */
10765 tree fn = lambda_function (t);
10766 WALK_SUBTREE (TREE_TYPE (fn));
10767 WALK_SUBTREE (DECL_SAVED_TREE (fn));
10769 break;
10771 case IDENTIFIER_NODE:
10772 if (IDENTIFIER_CONV_OP_P (t))
10773 /* The conversion-type-id of a conversion operator may be dependent. */
10774 WALK_SUBTREE (TREE_TYPE (t));
10775 break;
10777 case CONVERT_EXPR:
10778 if (is_dummy_object (t))
10779 WALK_SUBTREE (TREE_TYPE (t));
10780 break;
10782 default:
10783 break;
10786 /* Keep walking. */
10787 return 0;
10790 /* Returns a list of unique template parameters found within T, where CTX_PARMS
10791 are the template parameters in scope. */
10793 tree
10794 find_template_parameters (tree t, tree ctx_parms)
10796 if (!ctx_parms)
10797 return NULL_TREE;
10799 find_template_parameter_info ftpi (ctx_parms);
10800 for_each_template_parm (t, keep_template_parm, &ftpi, &ftpi.visited,
10801 /*include_nondeduced*/true, any_template_parm_r);
10802 return ftpi.parm_list;
10805 /* Returns true if T depends on any template parameter. */
10807 bool
10808 uses_template_parms (tree t)
10810 if (t == NULL_TREE || t == error_mark_node)
10811 return false;
10813 /* Namespaces can't depend on any template parameters. */
10814 if (TREE_CODE (t) == NAMESPACE_DECL)
10815 return false;
10817 processing_template_decl_sentinel ptds (/*reset*/false);
10818 ++processing_template_decl;
10820 if (TYPE_P (t))
10821 return dependent_type_p (t);
10822 else if (TREE_CODE (t) == TREE_VEC)
10823 return any_dependent_template_arguments_p (t);
10824 else if (TREE_CODE (t) == TREE_LIST)
10825 return (uses_template_parms (TREE_VALUE (t))
10826 || uses_template_parms (TREE_CHAIN (t)));
10827 else if (TREE_CODE (t) == TYPE_DECL)
10828 return dependent_type_p (TREE_TYPE (t));
10829 else
10830 return instantiation_dependent_expression_p (t);
10833 /* Returns true iff we're processing an incompletely instantiated function
10834 template. Useful instead of processing_template_decl because the latter
10835 is set to 0 during instantiate_non_dependent_expr. */
10837 bool
10838 in_template_function (void)
10840 /* Inspect the less volatile cfun->decl instead of current_function_decl;
10841 the latter might get set for e.g. access checking during satisfaction. */
10842 tree fn = cfun ? cfun->decl : NULL_TREE;
10843 bool ret;
10844 ++processing_template_decl;
10845 ret = (fn && DECL_LANG_SPECIFIC (fn)
10846 && DECL_TEMPLATE_INFO (fn)
10847 && any_dependent_template_arguments_p (DECL_TI_ARGS (fn)));
10848 --processing_template_decl;
10849 return ret;
10852 /* Returns true if T depends on any template parameter with level LEVEL. */
10854 bool
10855 uses_template_parms_level (tree t, int level)
10857 return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
10858 /*include_nondeduced_p=*/true);
10861 /* Returns true if the signature of DECL depends on any template parameter from
10862 its enclosing class. */
10864 static bool
10865 uses_outer_template_parms (tree decl)
10867 int depth = template_class_depth (CP_DECL_CONTEXT (decl));
10868 if (depth == 0)
10869 return false;
10870 if (for_each_template_parm (TREE_TYPE (decl), template_parm_outer_level,
10871 &depth, NULL, /*include_nondeduced_p=*/true))
10872 return true;
10873 if (PRIMARY_TEMPLATE_P (decl)
10874 || DECL_TEMPLATE_TEMPLATE_PARM_P (decl))
10876 tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (decl));
10877 for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
10879 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
10880 tree defarg = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
10881 if (TREE_CODE (parm) == PARM_DECL
10882 && for_each_template_parm (TREE_TYPE (parm),
10883 template_parm_outer_level,
10884 &depth, NULL, /*nondeduced*/true))
10885 return true;
10886 if (TREE_CODE (parm) == TEMPLATE_DECL
10887 && uses_outer_template_parms (parm))
10888 return true;
10889 if (defarg
10890 && for_each_template_parm (defarg, template_parm_outer_level,
10891 &depth, NULL, /*nondeduced*/true))
10892 return true;
10895 if (uses_outer_template_parms_in_constraints (decl))
10896 return true;
10897 return false;
10900 /* Returns true if the constraints of DECL depend on any template parameters
10901 from its enclosing scope. */
10903 bool
10904 uses_outer_template_parms_in_constraints (tree decl)
10906 tree ci = get_constraints (decl);
10907 if (ci)
10908 ci = CI_ASSOCIATED_CONSTRAINTS (ci);
10909 if (!ci)
10910 return false;
10911 int depth = template_class_depth (CP_DECL_CONTEXT (decl));
10912 if (depth == 0)
10913 return false;
10914 return for_each_template_parm (ci, template_parm_outer_level,
10915 &depth, NULL, /*nondeduced*/true);
10918 /* Returns TRUE iff INST is an instantiation we don't need to do in an
10919 ill-formed translation unit, i.e. a variable or function that isn't
10920 usable in a constant expression. */
10922 static inline bool
10923 neglectable_inst_p (tree d)
10925 return (d && DECL_P (d)
10926 && !undeduced_auto_decl (d)
10927 && !(TREE_CODE (d) == FUNCTION_DECL
10928 ? FNDECL_MANIFESTLY_CONST_EVALUATED (d)
10929 : decl_maybe_constant_var_p (d)));
10932 /* Returns TRUE iff we should refuse to instantiate DECL because it's
10933 neglectable and instantiated from within an erroneous instantiation. */
10935 static bool
10936 limit_bad_template_recursion (tree decl)
10938 struct tinst_level *lev = current_tinst_level;
10939 int errs = errorcount + sorrycount;
10940 if (errs == 0 || !neglectable_inst_p (decl))
10941 return false;
10943 /* Avoid instantiating members of an ill-formed class. */
10944 bool refuse
10945 = (DECL_CLASS_SCOPE_P (decl)
10946 && CLASSTYPE_ERRONEOUS (DECL_CONTEXT (decl)));
10948 if (!refuse)
10950 for (; lev; lev = lev->next)
10951 if (neglectable_inst_p (lev->maybe_get_node ()))
10952 break;
10953 refuse = (lev && errs > lev->errors);
10956 if (refuse)
10958 /* Don't warn about it not being defined. */
10959 suppress_warning (decl, OPT_Wunused);
10960 tree clone;
10961 FOR_EACH_CLONE (clone, decl)
10962 suppress_warning (clone, OPT_Wunused);
10964 return refuse;
10967 static int tinst_depth;
10968 extern int max_tinst_depth;
10969 int depth_reached;
10971 static GTY(()) struct tinst_level *last_error_tinst_level;
10973 /* We're starting to instantiate D; record the template instantiation context
10974 at LOC for diagnostics and to restore it later. */
10976 bool
10977 push_tinst_level_loc (tree tldcl, tree targs, location_t loc)
10979 struct tinst_level *new_level;
10981 if (tinst_depth >= max_tinst_depth)
10983 /* Tell error.cc not to try to instantiate any templates. */
10984 at_eof = 2;
10985 fatal_error (input_location,
10986 "template instantiation depth exceeds maximum of %d"
10987 " (use %<-ftemplate-depth=%> to increase the maximum)",
10988 max_tinst_depth);
10989 return false;
10992 /* If the current instantiation caused problems, don't let it instantiate
10993 anything else. Do allow deduction substitution and decls usable in
10994 constant expressions. */
10995 if (!targs && limit_bad_template_recursion (tldcl))
10997 /* Avoid no_linkage_errors and unused function (and all other)
10998 warnings for this decl. */
10999 suppress_warning (tldcl);
11000 return false;
11003 /* When not -quiet, dump template instantiations other than functions, since
11004 announce_function will take care of those. */
11005 if (!quiet_flag && !targs
11006 && TREE_CODE (tldcl) != TREE_LIST
11007 && TREE_CODE (tldcl) != FUNCTION_DECL)
11008 fprintf (stderr, " %s", decl_as_string (tldcl, TFF_DECL_SPECIFIERS));
11010 new_level = tinst_level_freelist ().alloc ();
11011 new_level->tldcl = tldcl;
11012 new_level->targs = targs;
11013 new_level->locus = loc;
11014 new_level->errors = errorcount + sorrycount;
11015 new_level->next = NULL;
11016 new_level->refcount = 0;
11017 new_level->path = new_level->visible = nullptr;
11018 set_refcount_ptr (new_level->next, current_tinst_level);
11019 set_refcount_ptr (current_tinst_level, new_level);
11021 ++tinst_depth;
11022 if (GATHER_STATISTICS && (tinst_depth > depth_reached))
11023 depth_reached = tinst_depth;
11025 return true;
11028 /* We're starting substitution of TMPL<ARGS>; record the template
11029 substitution context for diagnostics and to restore it later. */
11031 bool
11032 push_tinst_level (tree tmpl, tree args)
11034 return push_tinst_level_loc (tmpl, args, input_location);
11037 /* We're starting to instantiate D; record INPUT_LOCATION and the
11038 template instantiation context for diagnostics and to restore it
11039 later. */
11041 bool
11042 push_tinst_level (tree d)
11044 return push_tinst_level_loc (d, input_location);
11047 /* Likewise, but record LOC as the program location. */
11049 bool
11050 push_tinst_level_loc (tree d, location_t loc)
11052 gcc_assert (TREE_CODE (d) != TREE_LIST);
11053 return push_tinst_level_loc (d, NULL, loc);
11056 /* We're done instantiating this template; return to the instantiation
11057 context. */
11059 void
11060 pop_tinst_level (void)
11062 /* Restore the filename and line number stashed away when we started
11063 this instantiation. */
11064 input_location = current_tinst_level->locus;
11065 set_refcount_ptr (current_tinst_level, current_tinst_level->next);
11066 --tinst_depth;
11069 /* We're instantiating a deferred template; restore the template
11070 instantiation context in which the instantiation was requested, which
11071 is one step out from LEVEL. Return the corresponding DECL or TYPE. */
11073 static tree
11074 reopen_tinst_level (struct tinst_level *level)
11076 struct tinst_level *t;
11078 tinst_depth = 0;
11079 for (t = level; t; t = t->next)
11080 ++tinst_depth;
11082 set_refcount_ptr (current_tinst_level, level);
11083 pop_tinst_level ();
11084 if (current_tinst_level)
11085 current_tinst_level->errors = errorcount+sorrycount;
11086 return level->maybe_get_node ();
11089 /* Returns the TINST_LEVEL which gives the original instantiation
11090 context. */
11092 struct tinst_level *
11093 outermost_tinst_level (void)
11095 struct tinst_level *level = current_tinst_level;
11096 if (level)
11097 while (level->next)
11098 level = level->next;
11099 return level;
11102 /* True iff T is a friend function declaration that is not itself a template
11103 and is not defined in a class template. */
11105 bool
11106 non_templated_friend_p (tree t)
11108 if (t && TREE_CODE (t) == FUNCTION_DECL
11109 && DECL_UNIQUE_FRIEND_P (t))
11111 tree ti = DECL_TEMPLATE_INFO (t);
11112 if (!ti)
11113 return true;
11114 /* DECL_FRIEND_CONTEXT is set for a friend defined in class. */
11115 if (DECL_FRIEND_CONTEXT (t))
11116 return false;
11117 /* Non-templated friends in a class template are still represented with a
11118 TEMPLATE_DECL; check that its primary template is the befriending
11119 class. Note that DECL_PRIMARY_TEMPLATE is null for
11120 template <class T> friend A<T>::f(); */
11121 tree tmpl = TI_TEMPLATE (ti);
11122 tree primary = DECL_PRIMARY_TEMPLATE (tmpl);
11123 return (primary && primary != tmpl);
11125 else
11126 return false;
11129 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL. ARGS is the
11130 vector of template arguments, as for tsubst.
11132 Returns an appropriate tsubst'd friend declaration. */
11134 static tree
11135 tsubst_friend_function (tree decl, tree args)
11137 tree new_friend;
11139 if (TREE_CODE (decl) == FUNCTION_DECL
11140 && DECL_TEMPLATE_INSTANTIATION (decl)
11141 && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
11142 /* This was a friend declared with an explicit template
11143 argument list, e.g.:
11145 friend void f<>(T);
11147 to indicate that f was a template instantiation, not a new
11148 function declaration. Now, we have to figure out what
11149 instantiation of what template. */
11151 tree template_id, arglist, fns;
11152 tree new_args;
11153 tree tmpl;
11154 tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
11156 /* Friend functions are looked up in the containing namespace scope.
11157 We must enter that scope, to avoid finding member functions of the
11158 current class with same name. */
11159 push_nested_namespace (ns);
11160 fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
11161 tf_warning_or_error, NULL_TREE);
11162 pop_nested_namespace (ns);
11163 arglist = tsubst (DECL_TI_ARGS (decl), args,
11164 tf_warning_or_error, NULL_TREE);
11165 template_id = lookup_template_function (fns, arglist);
11167 new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
11168 tmpl = determine_specialization (template_id, new_friend,
11169 &new_args,
11170 /*need_member_template=*/0,
11171 TREE_VEC_LENGTH (args),
11172 tsk_none);
11173 return instantiate_template (tmpl, new_args, tf_error);
11176 new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
11177 if (new_friend == error_mark_node)
11178 return error_mark_node;
11180 /* The NEW_FRIEND will look like an instantiation, to the
11181 compiler, but is not an instantiation from the point of view of
11182 the language. For example, we might have had:
11184 template <class T> struct S {
11185 template <class U> friend void f(T, U);
11188 Then, in S<int>, template <class U> void f(int, U) is not an
11189 instantiation of anything. */
11191 DECL_USE_TEMPLATE (new_friend) = 0;
11192 if (TREE_CODE (new_friend) == TEMPLATE_DECL)
11194 DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (new_friend) = false;
11195 DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
11196 DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
11197 = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
11199 /* Substitute TEMPLATE_PARMS_CONSTRAINTS so that parameter levels will
11200 match in decls_match. */
11201 tree parms = DECL_TEMPLATE_PARMS (new_friend);
11202 tree treqs = TEMPLATE_PARMS_CONSTRAINTS (parms);
11203 treqs = maybe_substitute_reqs_for (treqs, new_friend);
11204 if (treqs != TEMPLATE_PARMS_CONSTRAINTS (parms))
11206 TEMPLATE_PARMS_CONSTRAINTS (parms) = treqs;
11207 /* As well as each TEMPLATE_PARM_CONSTRAINTS. */
11208 tsubst_each_template_parm_constraints (parms, args,
11209 tf_warning_or_error);
11213 /* The mangled name for the NEW_FRIEND is incorrect. The function
11214 is not a template instantiation and should not be mangled like
11215 one. Therefore, we forget the mangling here; we'll recompute it
11216 later if we need it. */
11217 if (TREE_CODE (new_friend) != TEMPLATE_DECL)
11219 SET_DECL_RTL (new_friend, NULL);
11220 SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
11223 if (DECL_NAMESPACE_SCOPE_P (new_friend))
11225 tree old_decl;
11226 tree ns;
11228 /* We must save some information from NEW_FRIEND before calling
11229 duplicate decls since that function will free NEW_FRIEND if
11230 possible. */
11231 tree new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
11232 tree new_friend_result_template_info = NULL_TREE;
11233 bool new_friend_is_defn =
11234 (new_friend_template_info
11235 && (DECL_INITIAL (DECL_TEMPLATE_RESULT
11236 (template_for_substitution (new_friend)))
11237 != NULL_TREE));
11238 tree not_tmpl = new_friend;
11240 if (TREE_CODE (new_friend) == TEMPLATE_DECL)
11242 /* This declaration is a `primary' template. */
11243 DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
11245 not_tmpl = DECL_TEMPLATE_RESULT (new_friend);
11246 new_friend_result_template_info = DECL_TEMPLATE_INFO (not_tmpl);
11248 else if (!constraints_satisfied_p (new_friend))
11249 /* Only define a constrained hidden friend when satisfied. */
11250 return error_mark_node;
11252 /* Inside pushdecl_namespace_level, we will push into the
11253 current namespace. However, the friend function should go
11254 into the namespace of the template. */
11255 ns = decl_namespace_context (new_friend);
11256 push_nested_namespace (ns);
11257 old_decl = pushdecl_namespace_level (new_friend, /*hiding=*/true);
11258 pop_nested_namespace (ns);
11260 if (old_decl == error_mark_node)
11261 return error_mark_node;
11263 if (old_decl != new_friend)
11265 /* This new friend declaration matched an existing
11266 declaration. For example, given:
11268 template <class T> void f(T);
11269 template <class U> class C {
11270 template <class T> friend void f(T) {}
11273 the friend declaration actually provides the definition
11274 of `f', once C has been instantiated for some type. So,
11275 old_decl will be the out-of-class template declaration,
11276 while new_friend is the in-class definition.
11278 But, if `f' was called before this point, the
11279 instantiation of `f' will have DECL_TI_ARGS corresponding
11280 to `T' but not to `U', references to which might appear
11281 in the definition of `f'. Previously, the most general
11282 template for an instantiation of `f' was the out-of-class
11283 version; now it is the in-class version. Therefore, we
11284 run through all specialization of `f', adding to their
11285 DECL_TI_ARGS appropriately. In particular, they need a
11286 new set of outer arguments, corresponding to the
11287 arguments for this class instantiation.
11289 The same situation can arise with something like this:
11291 friend void f(int);
11292 template <class T> class C {
11293 friend void f(T) {}
11296 when `C<int>' is instantiated. Now, `f(int)' is defined
11297 in the class. */
11299 if (!new_friend_is_defn)
11300 /* On the other hand, if the in-class declaration does
11301 *not* provide a definition, then we don't want to alter
11302 existing definitions. We can just leave everything
11303 alone. */
11305 else
11307 tree new_template = TI_TEMPLATE (new_friend_template_info);
11308 tree new_args = TI_ARGS (new_friend_template_info);
11310 /* Overwrite whatever template info was there before, if
11311 any, with the new template information pertaining to
11312 the declaration. */
11313 DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
11315 if (TREE_CODE (old_decl) != TEMPLATE_DECL)
11317 /* We should have called reregister_specialization in
11318 duplicate_decls. */
11319 gcc_assert (retrieve_specialization (new_template,
11320 new_args, 0)
11321 == old_decl);
11323 /* Instantiate it if the global has already been used. */
11324 if (DECL_ODR_USED (old_decl))
11325 instantiate_decl (old_decl, /*defer_ok=*/true,
11326 /*expl_inst_class_mem_p=*/false);
11328 else
11330 tree t;
11332 /* Indicate that the old function template is a partial
11333 instantiation. */
11334 DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
11335 = new_friend_result_template_info;
11337 gcc_assert (new_template
11338 == most_general_template (new_template));
11339 gcc_assert (new_template != old_decl);
11341 /* Reassign any specializations already in the hash table
11342 to the new more general template, and add the
11343 additional template args. */
11344 for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
11345 t != NULL_TREE;
11346 t = TREE_CHAIN (t))
11348 tree spec = TREE_VALUE (t);
11349 spec_entry elt;
11351 elt.tmpl = old_decl;
11352 elt.args = DECL_TI_ARGS (spec);
11353 elt.spec = NULL_TREE;
11355 decl_specializations->remove_elt (&elt);
11357 DECL_TI_ARGS (spec)
11358 = add_outermost_template_args (new_args,
11359 DECL_TI_ARGS (spec));
11361 register_specialization
11362 (spec, new_template, DECL_TI_ARGS (spec), true, 0);
11365 DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
11369 /* The information from NEW_FRIEND has been merged into OLD_DECL
11370 by duplicate_decls. */
11371 new_friend = old_decl;
11374 /* We've just introduced a namespace-scope function in the purview
11375 without necessarily having opened the enclosing namespace, so
11376 make sure the namespace is in the purview now too. */
11377 if (modules_p ()
11378 && DECL_MODULE_PURVIEW_P (STRIP_TEMPLATE (new_friend))
11379 && TREE_CODE (DECL_CONTEXT (new_friend)) == NAMESPACE_DECL)
11380 DECL_MODULE_PURVIEW_P (DECL_CONTEXT (new_friend)) = true;
11382 else
11384 tree context = DECL_CONTEXT (new_friend);
11385 bool dependent_p;
11387 /* In the code
11388 template <class T> class C {
11389 template <class U> friend void C1<U>::f (); // case 1
11390 friend void C2<T>::f (); // case 2
11392 we only need to make sure CONTEXT is a complete type for
11393 case 2. To distinguish between the two cases, we note that
11394 CONTEXT of case 1 remains dependent type after tsubst while
11395 this isn't true for case 2. */
11396 ++processing_template_decl;
11397 dependent_p = dependent_type_p (context);
11398 --processing_template_decl;
11400 if (!dependent_p
11401 && !complete_type_or_else (context, NULL_TREE))
11402 return error_mark_node;
11404 if (COMPLETE_TYPE_P (context))
11406 tree fn = new_friend;
11407 /* do_friend adds the TEMPLATE_DECL for any member friend
11408 template even if it isn't a member template, i.e.
11409 template <class T> friend A<T>::f();
11410 Look through it in that case. */
11411 if (TREE_CODE (fn) == TEMPLATE_DECL
11412 && !PRIMARY_TEMPLATE_P (fn))
11413 fn = DECL_TEMPLATE_RESULT (fn);
11414 /* Check to see that the declaration is really present, and,
11415 possibly obtain an improved declaration. */
11416 fn = check_classfn (context, fn, NULL_TREE);
11418 if (fn)
11419 new_friend = fn;
11423 return new_friend;
11426 /* FRIEND_TMPL is a friend TEMPLATE_DECL. ARGS is the vector of
11427 template arguments, as for tsubst.
11429 Returns an appropriate tsubst'd friend type or error_mark_node on
11430 failure. */
11432 static tree
11433 tsubst_friend_class (tree friend_tmpl, tree args)
11435 tree tmpl;
11437 if (DECL_TEMPLATE_TEMPLATE_PARM_P (friend_tmpl))
11439 tmpl = tsubst (TREE_TYPE (friend_tmpl), args, tf_none, NULL_TREE);
11440 return TREE_TYPE (tmpl);
11443 tree context = CP_DECL_CONTEXT (friend_tmpl);
11444 if (TREE_CODE (context) == NAMESPACE_DECL)
11445 push_nested_namespace (context);
11446 else
11448 context = tsubst (context, args, tf_error, NULL_TREE);
11449 push_nested_class (context);
11452 tmpl = lookup_name (DECL_NAME (friend_tmpl), LOOK_where::CLASS_NAMESPACE,
11453 LOOK_want::NORMAL | LOOK_want::HIDDEN_FRIEND);
11455 if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
11457 /* The friend template has already been declared. Just
11458 check to see that the declarations match, and install any new
11459 default parameters. We must tsubst the default parameters,
11460 of course. We only need the innermost template parameters
11461 because that is all that redeclare_class_template will look
11462 at. */
11463 if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
11464 > TMPL_ARGS_DEPTH (args))
11466 tree parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
11467 args, tf_warning_or_error);
11468 tsubst_each_template_parm_constraints (parms, args,
11469 tf_warning_or_error);
11470 location_t saved_input_location = input_location;
11471 input_location = DECL_SOURCE_LOCATION (friend_tmpl);
11472 tree cons = get_constraints (tmpl);
11473 redeclare_class_template (TREE_TYPE (tmpl), parms, cons);
11474 input_location = saved_input_location;
11477 else
11479 /* The friend template has not already been declared. In this
11480 case, the instantiation of the template class will cause the
11481 injection of this template into the namespace scope. */
11482 tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
11484 if (tmpl != error_mark_node)
11486 /* The new TMPL is not an instantiation of anything, so we
11487 forget its origins. We don't reset CLASSTYPE_TI_TEMPLATE
11488 for the new type because that is supposed to be the
11489 corresponding template decl, i.e., TMPL. */
11490 DECL_USE_TEMPLATE (tmpl) = 0;
11491 DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
11492 CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
11493 CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
11494 = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
11496 /* Substitute into and set the constraints on the new declaration. */
11497 if (tree ci = get_constraints (friend_tmpl))
11499 ++processing_template_decl;
11500 ci = tsubst_constraint_info (ci, args, tf_warning_or_error,
11501 DECL_FRIEND_CONTEXT (friend_tmpl));
11502 --processing_template_decl;
11503 set_constraints (tmpl, ci);
11504 tsubst_each_template_parm_constraints (DECL_TEMPLATE_PARMS (tmpl),
11505 args, tf_warning_or_error);
11508 /* Inject this template into the enclosing namspace scope. */
11509 tmpl = pushdecl_namespace_level (tmpl, /*hiding=*/true);
11513 if (TREE_CODE (context) == NAMESPACE_DECL)
11514 pop_nested_namespace (context);
11515 else
11516 pop_nested_class ();
11518 return TREE_TYPE (tmpl);
11521 /* Returns zero if TYPE cannot be completed later due to circularity.
11522 Otherwise returns one. */
11524 static int
11525 can_complete_type_without_circularity (tree type)
11527 if (type == NULL_TREE || type == error_mark_node)
11528 return 0;
11529 else if (COMPLETE_TYPE_P (type))
11530 return 1;
11531 else if (TREE_CODE (type) == ARRAY_TYPE)
11532 return can_complete_type_without_circularity (TREE_TYPE (type));
11533 else if (CLASS_TYPE_P (type)
11534 && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
11535 return 0;
11536 else
11537 return 1;
11540 static tree tsubst_omp_clauses (tree, enum c_omp_region_type, tree,
11541 tsubst_flags_t, tree);
11543 /* Instantiate the contract statement. */
11545 static tree
11546 tsubst_contract (tree decl, tree t, tree args, tsubst_flags_t complain,
11547 tree in_decl)
11549 tree type = decl ? TREE_TYPE (TREE_TYPE (decl)) : NULL_TREE;
11550 bool auto_p = type_uses_auto (type);
11552 tree r = copy_node (t);
11554 /* Rebuild the result variable. */
11555 if (type && POSTCONDITION_P (t) && POSTCONDITION_IDENTIFIER (t))
11557 tree oldvar = POSTCONDITION_IDENTIFIER (t);
11559 tree newvar = copy_node (oldvar);
11560 TREE_TYPE (newvar) = type;
11561 DECL_CONTEXT (newvar) = decl;
11562 POSTCONDITION_IDENTIFIER (r) = newvar;
11564 /* Make sure the postcondition is valid. */
11565 location_t loc = DECL_SOURCE_LOCATION (oldvar);
11566 if (!auto_p)
11567 if (!check_postcondition_result (decl, type, loc))
11568 return invalidate_contract (r);
11570 /* Make the variable available for lookup. */
11571 register_local_specialization (newvar, oldvar);
11574 /* Instantiate the condition. If the return type is undeduced, process
11575 the expression as if inside a template to avoid spurious type errors. */
11576 if (auto_p)
11577 ++processing_template_decl;
11578 ++processing_contract_condition;
11579 CONTRACT_CONDITION (r)
11580 = tsubst_expr (CONTRACT_CONDITION (t), args, complain, in_decl);
11581 --processing_contract_condition;
11582 if (auto_p)
11583 --processing_template_decl;
11585 /* And the comment. */
11586 CONTRACT_COMMENT (r)
11587 = tsubst_expr (CONTRACT_COMMENT (r), args, complain, in_decl);
11589 return r;
11592 /* Update T by instantiating its contract attribute. */
11594 static void
11595 tsubst_contract_attribute (tree decl, tree t, tree args,
11596 tsubst_flags_t complain, tree in_decl)
11598 /* For non-specializations, adjust the current declaration to the most general
11599 version of in_decl. Because we defer the instantiation of contracts as long
11600 as possible, they are still written in terms of the parameters (and return
11601 type) of the most general template. */
11602 tree tmpl = DECL_TI_TEMPLATE (in_decl);
11603 if (!DECL_TEMPLATE_SPECIALIZATION (tmpl))
11604 in_decl = DECL_TEMPLATE_RESULT (most_general_template (in_decl));
11605 local_specialization_stack specs (lss_copy);
11606 register_parameter_specializations (in_decl, decl);
11608 /* Get the contract to be instantiated. */
11609 tree contract = CONTRACT_STATEMENT (t);
11611 /* Use the complete set of template arguments for instantiation. The
11612 contract may not have been instantiated and still refer to outer levels
11613 of template parameters. */
11614 args = DECL_TI_ARGS (decl);
11616 /* For member functions, make this available for semantic analysis. */
11617 tree save_ccp = current_class_ptr;
11618 tree save_ccr = current_class_ref;
11619 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
11621 tree arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
11622 tree this_type = TREE_TYPE (TREE_VALUE (arg_types));
11623 inject_this_parameter (this_type, cp_type_quals (this_type));
11626 contract = tsubst_contract (decl, contract, args, complain, in_decl);
11628 current_class_ptr = save_ccp;
11629 current_class_ref = save_ccr;
11631 /* Rebuild the attribute. */
11632 TREE_VALUE (t) = build_tree_list (NULL_TREE, contract);
11635 /* Rebuild the attribute list for DECL, substituting into contracts
11636 as needed. */
11638 void
11639 tsubst_contract_attributes (tree decl, tree args, tsubst_flags_t complain, tree in_decl)
11641 tree list = copy_list (DECL_ATTRIBUTES (decl));
11642 for (tree attr = list; attr; attr = CONTRACT_CHAIN (attr))
11644 if (cxx_contract_attribute_p (attr))
11645 tsubst_contract_attribute (decl, attr, args, complain, in_decl);
11647 DECL_ATTRIBUTES (decl) = list;
11650 /* Instantiate a single dependent attribute T (a TREE_LIST), and return either
11651 T or a new TREE_LIST, possibly a chain in the case of a pack expansion. */
11653 static tree
11654 tsubst_attribute (tree t, tree *decl_p, tree args,
11655 tsubst_flags_t complain, tree in_decl)
11657 gcc_assert (ATTR_IS_DEPENDENT (t));
11659 /* Note that contract attributes are never substituted from this function.
11660 Their instantiation is triggered by regenerate_from_template_decl when
11661 we instantiate the body of the function. */
11663 tree val = TREE_VALUE (t);
11664 if (val == NULL_TREE)
11665 /* Nothing to do. */;
11666 else if ((flag_openmp || flag_openmp_simd)
11667 && is_attribute_p ("omp declare simd",
11668 get_attribute_name (t)))
11670 tree clauses = TREE_VALUE (val);
11671 clauses = tsubst_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD, args,
11672 complain, in_decl);
11673 c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
11674 clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
11675 tree parms = DECL_ARGUMENTS (*decl_p);
11676 clauses
11677 = c_omp_declare_simd_clauses_to_numbers (parms, clauses);
11678 if (clauses)
11679 val = build_tree_list (NULL_TREE, clauses);
11680 else
11681 val = NULL_TREE;
11683 else if (flag_openmp
11684 && is_attribute_p ("omp declare variant base",
11685 get_attribute_name (t)))
11687 ++cp_unevaluated_operand;
11688 tree varid = tsubst_expr (TREE_PURPOSE (val), args, complain, in_decl);
11689 --cp_unevaluated_operand;
11690 tree chain = TREE_CHAIN (val);
11691 location_t match_loc = cp_expr_loc_or_input_loc (TREE_PURPOSE (chain));
11692 tree ctx = copy_list (TREE_VALUE (val));
11693 tree simd = get_identifier ("simd");
11694 tree score = get_identifier (" score");
11695 tree condition = get_identifier ("condition");
11696 for (tree t1 = ctx; t1; t1 = TREE_CHAIN (t1))
11698 const char *set = IDENTIFIER_POINTER (TREE_PURPOSE (t1));
11699 TREE_VALUE (t1) = copy_list (TREE_VALUE (t1));
11700 for (tree t2 = TREE_VALUE (t1); t2; t2 = TREE_CHAIN (t2))
11702 if (TREE_PURPOSE (t2) == simd && set[0] == 'c')
11704 tree clauses = TREE_VALUE (t2);
11705 clauses = tsubst_omp_clauses (clauses,
11706 C_ORT_OMP_DECLARE_SIMD, args,
11707 complain, in_decl);
11708 c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
11709 clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
11710 TREE_VALUE (t2) = clauses;
11712 else
11714 TREE_VALUE (t2) = copy_list (TREE_VALUE (t2));
11715 for (tree t3 = TREE_VALUE (t2); t3; t3 = TREE_CHAIN (t3))
11716 if (TREE_VALUE (t3))
11718 bool allow_string
11719 = ((TREE_PURPOSE (t2) != condition || set[0] != 'u')
11720 && TREE_PURPOSE (t3) != score);
11721 tree v = TREE_VALUE (t3);
11722 if (TREE_CODE (v) == STRING_CST && allow_string)
11723 continue;
11724 v = tsubst_expr (v, args, complain, in_decl);
11725 v = fold_non_dependent_expr (v);
11726 if (!INTEGRAL_TYPE_P (TREE_TYPE (v))
11727 || (TREE_PURPOSE (t3) == score
11728 ? TREE_CODE (v) != INTEGER_CST
11729 : !tree_fits_shwi_p (v)))
11731 location_t loc
11732 = cp_expr_loc_or_loc (TREE_VALUE (t3),
11733 match_loc);
11734 if (TREE_PURPOSE (t3) == score)
11735 error_at (loc, "score argument must be "
11736 "constant integer expression");
11737 else if (allow_string)
11738 error_at (loc, "property must be constant "
11739 "integer expression or string "
11740 "literal");
11741 else
11742 error_at (loc, "property must be constant "
11743 "integer expression");
11744 return NULL_TREE;
11746 else if (TREE_PURPOSE (t3) == score
11747 && tree_int_cst_sgn (v) < 0)
11749 location_t loc
11750 = cp_expr_loc_or_loc (TREE_VALUE (t3),
11751 match_loc);
11752 error_at (loc, "score argument must be "
11753 "non-negative");
11754 return NULL_TREE;
11756 TREE_VALUE (t3) = v;
11761 val = tree_cons (varid, ctx, chain);
11763 /* If the first attribute argument is an identifier, don't
11764 pass it through tsubst. Attributes like mode, format,
11765 cleanup and several target specific attributes expect it
11766 unmodified. */
11767 else if (attribute_takes_identifier_p (get_attribute_name (t)))
11769 tree chain
11770 = tsubst_expr (TREE_CHAIN (val), args, complain, in_decl);
11771 if (chain != TREE_CHAIN (val))
11772 val = tree_cons (NULL_TREE, TREE_VALUE (val), chain);
11774 else if (PACK_EXPANSION_P (val))
11776 /* An attribute pack expansion. */
11777 tree purp = TREE_PURPOSE (t);
11778 tree pack = tsubst_pack_expansion (val, args, complain, in_decl);
11779 if (pack == error_mark_node)
11780 return error_mark_node;
11781 int len = TREE_VEC_LENGTH (pack);
11782 tree list = NULL_TREE;
11783 tree *q = &list;
11784 for (int i = 0; i < len; ++i)
11786 tree elt = TREE_VEC_ELT (pack, i);
11787 *q = build_tree_list (purp, elt);
11788 q = &TREE_CHAIN (*q);
11790 return list;
11792 else
11793 val = tsubst_expr (val, args, complain, in_decl);
11795 if (val == error_mark_node)
11796 return error_mark_node;
11797 if (val != TREE_VALUE (t))
11798 return build_tree_list (TREE_PURPOSE (t), val);
11799 return t;
11802 /* Instantiate any dependent attributes in ATTRIBUTES, returning either it
11803 unchanged or a new TREE_LIST chain. */
11805 static tree
11806 tsubst_attributes (tree attributes, tree args,
11807 tsubst_flags_t complain, tree in_decl)
11809 tree last_dep = NULL_TREE;
11811 for (tree t = attributes; t; t = TREE_CHAIN (t))
11812 if (ATTR_IS_DEPENDENT (t))
11814 last_dep = t;
11815 attributes = copy_list (attributes);
11816 break;
11819 if (last_dep)
11820 for (tree *p = &attributes; *p; )
11822 tree t = *p;
11823 if (ATTR_IS_DEPENDENT (t))
11825 tree subst = tsubst_attribute (t, NULL, args, complain, in_decl);
11826 if (subst != t)
11828 *p = subst;
11829 while (*p)
11830 p = &TREE_CHAIN (*p);
11831 *p = TREE_CHAIN (t);
11832 continue;
11835 p = &TREE_CHAIN (*p);
11838 return attributes;
11841 /* Apply any attributes which had to be deferred until instantiation
11842 time. DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
11843 ARGS, COMPLAIN, IN_DECL are as tsubst. Returns true normally,
11844 false on error. */
11846 static bool
11847 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
11848 tree args, tsubst_flags_t complain, tree in_decl)
11850 tree t;
11851 tree *p;
11853 if (attributes == NULL_TREE)
11854 return true;
11856 if (DECL_P (*decl_p))
11858 if (TREE_TYPE (*decl_p) == error_mark_node)
11859 return false;
11860 p = &DECL_ATTRIBUTES (*decl_p);
11861 /* DECL_ATTRIBUTES comes from copy_node in tsubst_decl, and is identical
11862 to our attributes parameter. */
11863 gcc_assert (*p == attributes);
11865 else
11867 p = &TYPE_ATTRIBUTES (*decl_p);
11868 /* TYPE_ATTRIBUTES was set up (with abi_tag and may_alias) in
11869 lookup_template_class_1, and should be preserved. */
11870 gcc_assert (*p != attributes);
11871 while (*p)
11872 p = &TREE_CHAIN (*p);
11875 /* save_template_attributes puts the dependent attributes at the beginning of
11876 the list; find the non-dependent ones. */
11877 for (t = attributes; t; t = TREE_CHAIN (t))
11878 if (!ATTR_IS_DEPENDENT (t))
11879 break;
11880 tree nondep = t;
11882 /* Apply any non-dependent attributes. */
11883 *p = nondep;
11885 if (nondep == attributes)
11886 return true;
11888 /* And then any dependent ones. */
11889 tree late_attrs = NULL_TREE;
11890 tree *q = &late_attrs;
11891 for (t = attributes; t != nondep; t = TREE_CHAIN (t))
11893 *q = tsubst_attribute (t, decl_p, args, complain, in_decl);
11894 if (*q == error_mark_node)
11895 return false;
11896 if (*q == t)
11898 *q = copy_node (t);
11899 TREE_CHAIN (*q) = NULL_TREE;
11901 while (*q)
11902 q = &TREE_CHAIN (*q);
11905 /* cplus_decl_attributes can add some attributes implicitly. For templates,
11906 those attributes should have been added already when those templates were
11907 parsed, and shouldn't be added based on from which context they are
11908 first time instantiated. */
11909 auto o1 = make_temp_override (current_optimize_pragma, NULL_TREE);
11910 auto o2 = make_temp_override (optimization_current_node,
11911 optimization_default_node);
11912 auto o3 = make_temp_override (current_target_pragma, NULL_TREE);
11913 auto o4 = make_temp_override (scope_chain->omp_declare_target_attribute,
11914 NULL);
11915 auto o5 = make_temp_override (scope_chain->omp_begin_assumes, NULL);
11917 cplus_decl_attributes (decl_p, late_attrs, attr_flags);
11919 return true;
11922 /* The template TMPL is being instantiated with the template arguments TARGS.
11923 Perform the access checks that we deferred when parsing the template. */
11925 static void
11926 perform_instantiation_time_access_checks (tree tmpl, tree targs)
11928 unsigned i;
11929 deferred_access_check *chk;
11931 if (!CLASS_TYPE_P (tmpl) && TREE_CODE (tmpl) != FUNCTION_DECL)
11932 return;
11934 if (vec<deferred_access_check, va_gc> *access_checks
11935 = TI_DEFERRED_ACCESS_CHECKS (get_template_info (tmpl)))
11936 FOR_EACH_VEC_ELT (*access_checks, i, chk)
11938 tree decl = chk->decl;
11939 tree diag_decl = chk->diag_decl;
11940 tree type_scope = TREE_TYPE (chk->binfo);
11942 if (uses_template_parms (type_scope))
11943 type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
11945 /* Make access check error messages point to the location
11946 of the use of the typedef. */
11947 iloc_sentinel ils (chk->loc);
11948 perform_or_defer_access_check (TYPE_BINFO (type_scope),
11949 decl, diag_decl, tf_warning_or_error);
11953 tree
11954 instantiate_class_template (tree type)
11956 auto_timevar tv (TV_TEMPLATE_INST);
11958 tree templ, args, pattern, t, member;
11959 tree typedecl;
11960 tree pbinfo;
11961 tree base_list;
11962 unsigned int saved_maximum_field_alignment;
11963 tree fn_context;
11965 if (type == error_mark_node)
11966 return error_mark_node;
11968 if (COMPLETE_OR_OPEN_TYPE_P (type)
11969 || uses_template_parms (type))
11970 return type;
11972 /* Figure out which template is being instantiated. */
11973 templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
11974 gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
11976 /* Mark the type as in the process of being defined. */
11977 TYPE_BEING_DEFINED (type) = 1;
11979 /* We may be in the middle of deferred access check. Disable
11980 it now. */
11981 deferring_access_check_sentinel acs (dk_no_deferred);
11983 /* Determine what specialization of the original template to
11984 instantiate. */
11985 t = most_specialized_partial_spec (type, tf_warning_or_error);
11986 if (t == error_mark_node)
11987 return error_mark_node;
11988 else if (t)
11990 /* This TYPE is actually an instantiation of a partial
11991 specialization. We replace the innermost set of ARGS with
11992 the arguments appropriate for substitution. For example,
11993 given:
11995 template <class T> struct S {};
11996 template <class T> struct S<T*> {};
11998 and supposing that we are instantiating S<int*>, ARGS will
11999 presently be {int*} -- but we need {int}. */
12000 pattern = TREE_TYPE (t);
12001 args = TREE_PURPOSE (t);
12003 else
12005 pattern = TREE_TYPE (templ);
12006 args = CLASSTYPE_TI_ARGS (type);
12009 /* If the template we're instantiating is incomplete, then clearly
12010 there's nothing we can do. */
12011 if (!COMPLETE_TYPE_P (pattern))
12013 /* We can try again later. */
12014 TYPE_BEING_DEFINED (type) = 0;
12015 return type;
12018 /* If we've recursively instantiated too many templates, stop. */
12019 if (! push_tinst_level (type))
12020 return type;
12022 int saved_unevaluated_operand = cp_unevaluated_operand;
12023 int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
12025 fn_context = decl_function_context (TYPE_MAIN_DECL (type));
12026 /* Also avoid push_to_top_level for a lambda in an NSDMI. */
12027 if (!fn_context && LAMBDA_TYPE_P (type) && TYPE_CLASS_SCOPE_P (type))
12028 fn_context = error_mark_node;
12029 if (!fn_context)
12030 push_to_top_level ();
12031 else
12033 cp_unevaluated_operand = 0;
12034 c_inhibit_evaluation_warnings = 0;
12036 /* Use #pragma pack from the template context. */
12037 saved_maximum_field_alignment = maximum_field_alignment;
12038 maximum_field_alignment = TYPE_PRECISION (pattern);
12040 SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
12042 /* Set the input location to the most specialized template definition.
12043 This is needed if tsubsting causes an error. */
12044 typedecl = TYPE_MAIN_DECL (pattern);
12045 input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
12046 DECL_SOURCE_LOCATION (typedecl);
12048 set_instantiating_module (TYPE_NAME (type));
12050 TYPE_PACKED (type) = TYPE_PACKED (pattern);
12051 SET_TYPE_ALIGN (type, TYPE_ALIGN (pattern));
12052 TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
12053 CLASSTYPE_NON_AGGREGATE (type) = CLASSTYPE_NON_AGGREGATE (pattern);
12054 if (ANON_AGGR_TYPE_P (pattern))
12055 SET_ANON_AGGR_TYPE_P (type);
12056 if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
12058 CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
12059 CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
12060 /* Adjust visibility for template arguments. */
12061 determine_visibility (TYPE_MAIN_DECL (type));
12063 if (CLASS_TYPE_P (type))
12064 CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
12066 pbinfo = TYPE_BINFO (pattern);
12068 /* We should never instantiate a nested class before its enclosing
12069 class; we need to look up the nested class by name before we can
12070 instantiate it, and that lookup should instantiate the enclosing
12071 class. */
12072 gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
12073 || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
12075 base_list = NULL_TREE;
12076 /* Defer access checking while we substitute into the types named in
12077 the base-clause. */
12078 push_deferring_access_checks (dk_deferred);
12079 if (BINFO_N_BASE_BINFOS (pbinfo))
12081 tree pbase_binfo;
12082 int i;
12084 /* Substitute into each of the bases to determine the actual
12085 basetypes. */
12086 for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
12088 tree base;
12089 tree access = BINFO_BASE_ACCESS (pbinfo, i);
12090 tree expanded_bases = NULL_TREE;
12091 int idx, len = 1;
12093 if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
12095 expanded_bases =
12096 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
12097 args, tf_error, NULL_TREE);
12098 if (expanded_bases == error_mark_node)
12099 continue;
12101 len = TREE_VEC_LENGTH (expanded_bases);
12104 for (idx = 0; idx < len; idx++)
12106 if (expanded_bases)
12107 /* Extract the already-expanded base class. */
12108 base = TREE_VEC_ELT (expanded_bases, idx);
12109 else
12110 /* Substitute to figure out the base class. */
12111 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error,
12112 NULL_TREE);
12114 if (base == error_mark_node)
12115 continue;
12117 base_list = tree_cons (access, base, base_list);
12118 if (BINFO_VIRTUAL_P (pbase_binfo))
12119 TREE_TYPE (base_list) = integer_type_node;
12123 /* The list is now in reverse order; correct that. */
12124 base_list = nreverse (base_list);
12126 /* Now call xref_basetypes to set up all the base-class
12127 information. */
12128 xref_basetypes (type, base_list);
12130 apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
12131 (int) ATTR_FLAG_TYPE_IN_PLACE,
12132 args, tf_error, NULL_TREE);
12133 fixup_attribute_variants (type);
12135 /* Now that our base classes are set up, enter the scope of the
12136 class, so that name lookups into base classes, etc. will work
12137 correctly. This is precisely analogous to what we do in
12138 begin_class_definition when defining an ordinary non-template
12139 class, except we also need to push the enclosing classes. */
12140 push_nested_class (type);
12142 /* Now check accessibility of the types named in its base-clause,
12143 relative to the scope of the class. */
12144 pop_to_parent_deferring_access_checks ();
12146 /* A vector to hold members marked with attribute used. */
12147 auto_vec<tree> used;
12149 /* Now members are processed in the order of declaration. */
12150 for (member = CLASSTYPE_DECL_LIST (pattern);
12151 member; member = TREE_CHAIN (member))
12153 tree t = TREE_VALUE (member);
12155 if (TREE_PURPOSE (member))
12157 if (TYPE_P (t))
12159 if (LAMBDA_TYPE_P (t))
12160 /* A closure type for a lambda in an NSDMI or default argument.
12161 Ignore it; it will be regenerated when needed. */
12162 continue;
12164 bool class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
12165 && TYPE_LANG_SPECIFIC (t)
12166 && CLASSTYPE_IS_TEMPLATE (t));
12168 /* If the member is a class template, then -- even after
12169 substitution -- there may be dependent types in the
12170 template argument list for the class. We increment
12171 PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
12172 that function will assume that no types are dependent
12173 when outside of a template. */
12174 if (class_template_p)
12175 ++processing_template_decl;
12176 tree newtag = tsubst (t, args, tf_error, NULL_TREE);
12177 if (class_template_p)
12178 --processing_template_decl;
12179 if (newtag == error_mark_node)
12180 continue;
12182 if (TREE_CODE (newtag) != ENUMERAL_TYPE)
12184 tree name = TYPE_IDENTIFIER (t);
12186 if (class_template_p)
12187 /* Unfortunately, lookup_template_class sets
12188 CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
12189 instantiation (i.e., for the type of a member
12190 template class nested within a template class.)
12191 This behavior is required for
12192 maybe_process_partial_specialization to work
12193 correctly, but is not accurate in this case;
12194 the TAG is not an instantiation of anything.
12195 (The corresponding TEMPLATE_DECL is an
12196 instantiation, but the TYPE is not.) */
12197 CLASSTYPE_USE_TEMPLATE (newtag) = 0;
12199 /* Now, install the tag. We don't use pushtag
12200 because that does too much work -- creating an
12201 implicit typedef, which we've already done. */
12202 set_identifier_type_value (name, TYPE_NAME (newtag));
12203 maybe_add_class_template_decl_list (type, newtag, false);
12204 TREE_PUBLIC (TYPE_NAME (newtag)) = true;
12205 determine_visibility (TYPE_NAME (newtag));
12208 else if (DECL_DECLARES_FUNCTION_P (t))
12210 tree r;
12212 if (TREE_CODE (t) == TEMPLATE_DECL)
12213 ++processing_template_decl;
12214 r = tsubst (t, args, tf_error, NULL_TREE);
12215 if (TREE_CODE (t) == TEMPLATE_DECL)
12216 --processing_template_decl;
12218 set_current_access_from_decl (r);
12219 finish_member_declaration (r);
12220 /* Instantiate members marked with attribute used. */
12221 if (r != error_mark_node && DECL_PRESERVE_P (r))
12222 used.safe_push (r);
12223 if (TREE_CODE (r) == FUNCTION_DECL
12224 && DECL_OMP_DECLARE_REDUCTION_P (r))
12225 cp_check_omp_declare_reduction (r);
12227 else if ((DECL_CLASS_TEMPLATE_P (t) || DECL_IMPLICIT_TYPEDEF_P (t))
12228 && LAMBDA_TYPE_P (TREE_TYPE (t)))
12229 /* A closure type for a lambda in an NSDMI or default argument.
12230 Ignore it; it will be regenerated when needed. */;
12231 else
12233 /* Build new TYPE_FIELDS. */
12234 if (TREE_CODE (t) == STATIC_ASSERT)
12235 tsubst_expr (t, args, tf_warning_or_error, NULL_TREE);
12236 else if (TREE_CODE (t) != CONST_DECL)
12238 tree r;
12239 tree vec = NULL_TREE;
12240 int len = 1;
12242 gcc_checking_assert (TREE_CODE (t) != CONST_DECL);
12243 /* The file and line for this declaration, to
12244 assist in error message reporting. Since we
12245 called push_tinst_level above, we don't need to
12246 restore these. */
12247 input_location = DECL_SOURCE_LOCATION (t);
12249 if (TREE_CODE (t) == TEMPLATE_DECL)
12250 ++processing_template_decl;
12251 r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
12252 if (TREE_CODE (t) == TEMPLATE_DECL)
12253 --processing_template_decl;
12255 if (TREE_CODE (r) == TREE_VEC)
12257 /* A capture pack became multiple fields. */
12258 vec = r;
12259 len = TREE_VEC_LENGTH (vec);
12262 for (int i = 0; i < len; ++i)
12264 if (vec)
12265 r = TREE_VEC_ELT (vec, i);
12266 if (VAR_P (r))
12268 /* In [temp.inst]:
12270 [t]he initialization (and any associated
12271 side-effects) of a static data member does
12272 not occur unless the static data member is
12273 itself used in a way that requires the
12274 definition of the static data member to
12275 exist.
12277 Therefore, we do not substitute into the
12278 initialized for the static data member here. */
12279 finish_static_data_member_decl
12281 /*init=*/NULL_TREE,
12282 /*init_const_expr_p=*/false,
12283 /*asmspec_tree=*/NULL_TREE,
12284 /*flags=*/0);
12285 /* Instantiate members marked with attribute used. */
12286 if (r != error_mark_node && DECL_PRESERVE_P (r))
12287 used.safe_push (r);
12289 else if (TREE_CODE (r) == FIELD_DECL)
12291 /* Determine whether R has a valid type and can be
12292 completed later. If R is invalid, then its type
12293 is replaced by error_mark_node. */
12294 tree rtype = TREE_TYPE (r);
12295 if (can_complete_type_without_circularity (rtype))
12296 complete_type (rtype);
12298 if (!complete_or_array_type_p (rtype))
12300 /* If R's type couldn't be completed and
12301 it isn't a flexible array member (whose
12302 type is incomplete by definition) give
12303 an error. */
12304 cxx_incomplete_type_error (r, rtype);
12305 TREE_TYPE (r) = error_mark_node;
12307 else if (TREE_CODE (rtype) == ARRAY_TYPE
12308 && TYPE_DOMAIN (rtype) == NULL_TREE
12309 && (TREE_CODE (type) == UNION_TYPE
12310 || TREE_CODE (type) == QUAL_UNION_TYPE))
12312 error ("flexible array member %qD in union", r);
12313 TREE_TYPE (r) = error_mark_node;
12315 else if (!verify_type_context (input_location,
12316 TCTX_FIELD, rtype))
12317 TREE_TYPE (r) = error_mark_node;
12320 /* If it is a TYPE_DECL for a class-scoped
12321 ENUMERAL_TYPE, such a thing will already have
12322 been added to the field list by tsubst_enum
12323 in finish_member_declaration case above. */
12324 if (!(TREE_CODE (r) == TYPE_DECL
12325 && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
12326 && DECL_ARTIFICIAL (r)))
12328 set_current_access_from_decl (r);
12329 finish_member_declaration (r);
12335 else
12337 if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t)
12338 || DECL_TEMPLATE_TEMPLATE_PARM_P (t))
12340 /* Build new CLASSTYPE_FRIEND_CLASSES. */
12342 tree friend_type = t;
12343 if (TREE_CODE (friend_type) == TEMPLATE_DECL)
12345 /* template <class T> friend class C; */
12346 friend_type = tsubst_friend_class (friend_type, args);
12348 else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
12350 /* template <class T> friend class C::D; */
12351 friend_type = tsubst (friend_type, args,
12352 tf_warning_or_error, NULL_TREE);
12353 if (TREE_CODE (friend_type) == TEMPLATE_DECL)
12354 friend_type = TREE_TYPE (friend_type);
12356 else if (TREE_CODE (friend_type) == TYPENAME_TYPE
12357 || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
12359 /* This could be either
12361 friend class T::C;
12363 when dependent_type_p is false or
12365 template <class U> friend class T::C;
12367 otherwise. */
12368 /* Bump processing_template_decl in case this is something like
12369 template <class T> friend struct A<T>::B. */
12370 ++processing_template_decl;
12371 friend_type = tsubst (friend_type, args,
12372 tf_warning_or_error, NULL_TREE);
12373 --processing_template_decl;
12375 else if (uses_template_parms (friend_type))
12376 /* friend class C<T>; */
12377 friend_type = tsubst (friend_type, args,
12378 tf_warning_or_error, NULL_TREE);
12380 /* Otherwise it's
12382 friend class C;
12384 where C is already declared or
12386 friend class C<int>;
12388 We don't have to do anything in these cases. */
12390 if (friend_type != error_mark_node)
12391 make_friend_class (type, friend_type, /*complain=*/false);
12393 else
12395 /* Build new DECL_FRIENDLIST. */
12396 tree r;
12398 /* The file and line for this declaration, to
12399 assist in error message reporting. Since we
12400 called push_tinst_level above, we don't need to
12401 restore these. */
12402 input_location = DECL_SOURCE_LOCATION (t);
12404 if (TREE_CODE (t) == TEMPLATE_DECL)
12406 ++processing_template_decl;
12407 push_deferring_access_checks (dk_no_check);
12410 r = tsubst_friend_function (t, args);
12411 add_friend (type, r, /*complain=*/false);
12412 if (TREE_CODE (t) == TEMPLATE_DECL)
12414 pop_deferring_access_checks ();
12415 --processing_template_decl;
12421 if (fn_context)
12423 /* Restore these before substituting into the lambda capture
12424 initializers. */
12425 cp_unevaluated_operand = saved_unevaluated_operand;
12426 c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
12429 /* Set the file and line number information to whatever is given for
12430 the class itself. This puts error messages involving generated
12431 implicit functions at a predictable point, and the same point
12432 that would be used for non-template classes. */
12433 input_location = DECL_SOURCE_LOCATION (typedecl);
12435 unreverse_member_declarations (type);
12436 finish_struct_1 (type);
12437 TYPE_BEING_DEFINED (type) = 0;
12439 /* Remember if instantiating this class ran into errors, so we can avoid
12440 instantiating member functions in limit_bad_template_recursion. We set
12441 this flag even if the problem was in another instantiation triggered by
12442 this one, as that will likely also cause trouble for member functions. */
12443 if (errorcount + sorrycount > current_tinst_level->errors)
12444 CLASSTYPE_ERRONEOUS (type) = true;
12446 /* We don't instantiate default arguments for member functions. 14.7.1:
12448 The implicit instantiation of a class template specialization causes
12449 the implicit instantiation of the declarations, but not of the
12450 definitions or default arguments, of the class member functions,
12451 member classes, static data members and member templates.... */
12453 perform_instantiation_time_access_checks (pattern, args);
12454 perform_deferred_access_checks (tf_warning_or_error);
12456 /* Now that we've gone through all the members, instantiate those
12457 marked with attribute used. We must do this in the context of
12458 the class -- not the context we pushed from, as that might be
12459 inside a template and change the behaviour of mark_used. */
12460 for (tree x : used)
12461 mark_used (x);
12463 pop_nested_class ();
12464 maximum_field_alignment = saved_maximum_field_alignment;
12465 if (!fn_context)
12466 pop_from_top_level ();
12467 pop_tinst_level ();
12469 /* The vtable for a template class can be emitted in any translation
12470 unit in which the class is instantiated. When there is no key
12471 method, however, finish_struct_1 will already have added TYPE to
12472 the keyed_classes. */
12473 if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
12474 vec_safe_push (keyed_classes, type);
12476 return type;
12479 tree
12480 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12482 tree r;
12484 if (!t)
12485 r = t;
12486 else if (TYPE_P (t))
12487 r = tsubst (t, args, complain, in_decl);
12488 else
12490 if (!(complain & tf_warning))
12491 ++c_inhibit_evaluation_warnings;
12492 r = tsubst_expr (t, args, complain, in_decl);
12493 if (!(complain & tf_warning))
12494 --c_inhibit_evaluation_warnings;
12497 return r;
12500 /* Given a function parameter pack TMPL_PARM and some function parameters
12501 instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
12502 and set *SPEC_P to point at the next point in the list. */
12504 tree
12505 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
12507 /* Collect all of the extra "packed" parameters into an
12508 argument pack. */
12509 tree argpack;
12510 tree spec_parm = *spec_p;
12511 int len;
12513 for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
12514 if (tmpl_parm
12515 && !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
12516 break;
12518 spec_parm = *spec_p;
12519 if (len == 1 && DECL_PACK_P (spec_parm))
12521 /* The instantiation is still a parameter pack; don't wrap it in a
12522 NONTYPE_ARGUMENT_PACK. */
12523 argpack = spec_parm;
12524 spec_parm = DECL_CHAIN (spec_parm);
12526 else
12528 /* Fill in PARMVEC with all of the parameters. */
12529 tree parmvec = make_tree_vec (len);
12530 argpack = make_node (NONTYPE_ARGUMENT_PACK);
12531 for (int i = 0; i < len; i++)
12533 tree elt = spec_parm;
12534 if (DECL_PACK_P (elt))
12535 elt = make_pack_expansion (elt);
12536 TREE_VEC_ELT (parmvec, i) = elt;
12537 spec_parm = DECL_CHAIN (spec_parm);
12540 /* Build the argument packs. */
12541 ARGUMENT_PACK_ARGS (argpack) = parmvec;
12543 *spec_p = spec_parm;
12545 return argpack;
12548 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
12549 NONTYPE_ARGUMENT_PACK. */
12551 static tree
12552 make_fnparm_pack (tree spec_parm)
12554 return extract_fnparm_pack (NULL_TREE, &spec_parm);
12557 /* Return 1 if the Ith element of the argument pack ARG_PACK is a
12558 pack expansion with no extra args, 2 if it has extra args, or 0
12559 if it is not a pack expansion. */
12561 static int
12562 argument_pack_element_is_expansion_p (tree arg_pack, int i)
12564 if (TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
12565 /* We're being called before this happens in tsubst_pack_expansion. */
12566 arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
12567 tree vec = ARGUMENT_PACK_ARGS (arg_pack);
12568 if (i >= TREE_VEC_LENGTH (vec))
12569 return 0;
12570 tree elt = TREE_VEC_ELT (vec, i);
12571 if (DECL_P (elt))
12572 /* A decl pack is itself an expansion. */
12573 elt = TREE_TYPE (elt);
12574 if (!PACK_EXPANSION_P (elt))
12575 return 0;
12576 if (PACK_EXPANSION_EXTRA_ARGS (elt))
12577 return 2;
12578 return 1;
12582 /* Creates and return an ARGUMENT_PACK_SELECT tree node. */
12584 static tree
12585 make_argument_pack_select (tree arg_pack, unsigned index)
12587 tree aps = make_node (ARGUMENT_PACK_SELECT);
12589 ARGUMENT_PACK_SELECT_FROM_PACK (aps) = arg_pack;
12590 ARGUMENT_PACK_SELECT_INDEX (aps) = index;
12592 return aps;
12595 /* This is a subroutine of tsubst_pack_expansion.
12597 It returns TRUE if we need to use the PACK_EXPANSION_EXTRA_ARGS
12598 mechanism to store the (non complete list of) arguments of the
12599 substitution and return a non substituted pack expansion, in order
12600 to wait for when we have enough arguments to really perform the
12601 substitution. */
12603 static bool
12604 use_pack_expansion_extra_args_p (tree t,
12605 tree parm_packs,
12606 int arg_pack_len,
12607 bool has_empty_arg)
12609 if (has_empty_arg
12610 && PACK_EXPANSION_FORCE_EXTRA_ARGS_P (t))
12611 return true;
12613 /* If one pack has an expansion and another pack has a normal
12614 argument or if one pack has an empty argument and an another
12615 one hasn't then tsubst_pack_expansion cannot perform the
12616 substitution and need to fall back on the
12617 PACK_EXPANSION_EXTRA mechanism. */
12618 if (parm_packs == NULL_TREE)
12619 return false;
12620 else if (has_empty_arg)
12622 /* If all the actual packs are pack expansions, we can still
12623 subsitute directly. */
12624 for (tree p = parm_packs; p; p = TREE_CHAIN (p))
12626 tree a = TREE_VALUE (p);
12627 if (TREE_CODE (a) == ARGUMENT_PACK_SELECT)
12628 a = ARGUMENT_PACK_SELECT_FROM_PACK (a);
12629 a = ARGUMENT_PACK_ARGS (a);
12630 if (TREE_VEC_LENGTH (a) == 1)
12631 a = TREE_VEC_ELT (a, 0);
12632 if (PACK_EXPANSION_P (a))
12633 continue;
12634 return true;
12636 return false;
12639 for (int i = 0 ; i < arg_pack_len; ++i)
12641 bool has_expansion_arg = false;
12642 bool has_non_expansion_arg = false;
12643 for (tree parm_pack = parm_packs;
12644 parm_pack;
12645 parm_pack = TREE_CHAIN (parm_pack))
12647 tree arg = TREE_VALUE (parm_pack);
12649 int exp = argument_pack_element_is_expansion_p (arg, i);
12650 if (exp == 2)
12651 /* We can't substitute a pack expansion with extra args into
12652 our pattern. */
12653 return true;
12654 else if (exp)
12655 has_expansion_arg = true;
12656 else
12657 has_non_expansion_arg = true;
12660 if (has_expansion_arg && has_non_expansion_arg)
12662 gcc_checking_assert (false);
12663 return true;
12666 return false;
12669 /* [temp.variadic]/6 says that:
12671 The instantiation of a pack expansion [...]
12672 produces a list E1,E2, ..., En, where N is the number of elements
12673 in the pack expansion parameters.
12675 This subroutine of tsubst_pack_expansion produces one of these Ei.
12677 PATTERN is the pattern of the pack expansion. PARM_PACKS is a
12678 TREE_LIST in which each TREE_PURPOSE is a parameter pack of
12679 PATTERN, and each TREE_VALUE is its corresponding argument pack.
12680 INDEX is the index 'i' of the element Ei to produce. ARGS,
12681 COMPLAIN, and IN_DECL are the same parameters as for the
12682 tsubst_pack_expansion function.
12684 The function returns the resulting Ei upon successful completion,
12685 or error_mark_node.
12687 Note that this function possibly modifies the ARGS parameter, so
12688 it's the responsibility of the caller to restore it. */
12690 static tree
12691 gen_elem_of_pack_expansion_instantiation (tree pattern,
12692 tree parm_packs,
12693 unsigned index,
12694 tree args /* This parm gets
12695 modified. */,
12696 tsubst_flags_t complain,
12697 tree in_decl)
12699 tree t;
12700 bool ith_elem_is_expansion = false;
12702 /* For each parameter pack, change the substitution of the parameter
12703 pack to the ith argument in its argument pack, then expand the
12704 pattern. */
12705 for (tree pack = parm_packs; pack; pack = TREE_CHAIN (pack))
12707 tree parm = TREE_PURPOSE (pack);
12708 tree arg_pack = TREE_VALUE (pack);
12709 tree aps; /* instance of ARGUMENT_PACK_SELECT. */
12711 ith_elem_is_expansion |=
12712 argument_pack_element_is_expansion_p (arg_pack, index);
12714 /* Select the Ith argument from the pack. */
12715 if (TREE_CODE (parm) == PARM_DECL
12716 || VAR_P (parm)
12717 || TREE_CODE (parm) == FIELD_DECL)
12719 if (index == 0)
12721 aps = make_argument_pack_select (arg_pack, index);
12722 if (!mark_used (parm, complain) && !(complain & tf_error))
12723 return error_mark_node;
12724 register_local_specialization (aps, parm);
12726 else
12727 aps = retrieve_local_specialization (parm);
12729 else
12731 int idx, level;
12732 template_parm_level_and_index (parm, &level, &idx);
12734 if (index == 0)
12736 aps = make_argument_pack_select (arg_pack, index);
12737 /* Update the corresponding argument. */
12738 TMPL_ARG (args, level, idx) = aps;
12740 else
12741 /* Re-use the ARGUMENT_PACK_SELECT. */
12742 aps = TMPL_ARG (args, level, idx);
12744 ARGUMENT_PACK_SELECT_INDEX (aps) = index;
12747 /* Substitute into the PATTERN with the (possibly altered)
12748 arguments. */
12749 if (pattern == in_decl)
12750 /* Expanding a fixed parameter pack from
12751 coerce_template_parameter_pack. */
12752 t = tsubst_decl (pattern, args, complain);
12753 else if (pattern == error_mark_node)
12754 t = error_mark_node;
12755 else if (!TYPE_P (pattern))
12756 t = tsubst_expr (pattern, args, complain, in_decl);
12757 else
12759 t = tsubst (pattern, args, complain, in_decl);
12760 if (is_auto (t) && !ith_elem_is_expansion)
12761 /* When expanding the fake auto... pack expansion from add_capture, we
12762 need to mark that the expansion is no longer a pack. */
12763 TEMPLATE_TYPE_PARAMETER_PACK (t) = false;
12766 /* If the Ith argument pack element is a pack expansion, then
12767 the Ith element resulting from the substituting is going to
12768 be a pack expansion as well. */
12769 if (ith_elem_is_expansion)
12770 t = make_pack_expansion (t, complain);
12772 return t;
12775 /* When the unexpanded parameter pack in a fold expression expands to an empty
12776 sequence, the value of the expression is as follows; the program is
12777 ill-formed if the operator is not listed in this table.
12779 && true
12780 || false
12781 , void() */
12783 tree
12784 expand_empty_fold (tree t, tsubst_flags_t complain)
12786 tree_code code = (tree_code)TREE_INT_CST_LOW (TREE_OPERAND (t, 0));
12787 if (!FOLD_EXPR_MODIFY_P (t))
12788 switch (code)
12790 case TRUTH_ANDIF_EXPR:
12791 return boolean_true_node;
12792 case TRUTH_ORIF_EXPR:
12793 return boolean_false_node;
12794 case COMPOUND_EXPR:
12795 return void_node;
12796 default:
12797 break;
12800 if (complain & tf_error)
12801 error_at (location_of (t),
12802 "fold of empty expansion over %O", code);
12803 return error_mark_node;
12806 /* Given a fold-expression T and a current LEFT and RIGHT operand,
12807 form an expression that combines the two terms using the
12808 operator of T. */
12810 static tree
12811 fold_expression (tree t, tree left, tree right, tsubst_flags_t complain)
12813 tree_code code = FOLD_EXPR_OP (t);
12815 tree lookups = templated_operator_saved_lookups (t);
12817 // Handle compound assignment operators.
12818 if (FOLD_EXPR_MODIFY_P (t))
12819 return build_x_modify_expr (input_location, left, code, right,
12820 lookups, complain);
12822 warning_sentinel s(warn_parentheses);
12823 switch (code)
12825 case COMPOUND_EXPR:
12826 return build_x_compound_expr (input_location, left, right,
12827 lookups, complain);
12828 default:
12829 return build_x_binary_op (input_location, code,
12830 left, TREE_CODE (left),
12831 right, TREE_CODE (right),
12832 lookups, /*overload=*/NULL,
12833 complain);
12837 /* Substitute ARGS into the pack of a fold expression T. */
12839 static inline tree
12840 tsubst_fold_expr_pack (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12842 return tsubst_pack_expansion (FOLD_EXPR_PACK (t), args, complain, in_decl);
12845 /* Substitute ARGS into the pack of a fold expression T. */
12847 static inline tree
12848 tsubst_fold_expr_init (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12850 return tsubst_expr (FOLD_EXPR_INIT (t), args, complain, in_decl);
12853 /* Expand a PACK of arguments into a grouped as left fold.
12854 Given a pack containing elements A0, A1, ..., An and an
12855 operator @, this builds the expression:
12857 ((A0 @ A1) @ A2) ... @ An
12859 Note that PACK must not be empty.
12861 The operator is defined by the original fold expression T. */
12863 static tree
12864 expand_left_fold (tree t, tree pack, tsubst_flags_t complain)
12866 tree left = TREE_VEC_ELT (pack, 0);
12867 for (int i = 1; i < TREE_VEC_LENGTH (pack); ++i)
12869 tree right = TREE_VEC_ELT (pack, i);
12870 left = fold_expression (t, left, right, complain);
12872 return left;
12875 /* Substitute into a unary left fold expression. */
12877 static tree
12878 tsubst_unary_left_fold (tree t, tree args, tsubst_flags_t complain,
12879 tree in_decl)
12881 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12882 if (pack == error_mark_node)
12883 return error_mark_node;
12884 if (PACK_EXPANSION_P (pack))
12886 tree r = copy_node (t);
12887 FOLD_EXPR_PACK (r) = pack;
12888 return r;
12890 if (TREE_VEC_LENGTH (pack) == 0)
12891 return expand_empty_fold (t, complain);
12892 else
12893 return expand_left_fold (t, pack, complain);
12896 /* Substitute into a binary left fold expression.
12898 Do ths by building a single (non-empty) vector of argumnts and
12899 building the expression from those elements. */
12901 static tree
12902 tsubst_binary_left_fold (tree t, tree args, tsubst_flags_t complain,
12903 tree in_decl)
12905 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12906 if (pack == error_mark_node)
12907 return error_mark_node;
12908 tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
12909 if (init == error_mark_node)
12910 return error_mark_node;
12912 if (PACK_EXPANSION_P (pack))
12914 tree r = copy_node (t);
12915 FOLD_EXPR_PACK (r) = pack;
12916 FOLD_EXPR_INIT (r) = init;
12917 return r;
12920 tree vec = make_tree_vec (TREE_VEC_LENGTH (pack) + 1);
12921 TREE_VEC_ELT (vec, 0) = init;
12922 for (int i = 0; i < TREE_VEC_LENGTH (pack); ++i)
12923 TREE_VEC_ELT (vec, i + 1) = TREE_VEC_ELT (pack, i);
12925 return expand_left_fold (t, vec, complain);
12928 /* Expand a PACK of arguments into a grouped as right fold.
12929 Given a pack containing elementns A0, A1, ..., and an
12930 operator @, this builds the expression:
12932 A0@ ... (An-2 @ (An-1 @ An))
12934 Note that PACK must not be empty.
12936 The operator is defined by the original fold expression T. */
12938 tree
12939 expand_right_fold (tree t, tree pack, tsubst_flags_t complain)
12941 // Build the expression.
12942 int n = TREE_VEC_LENGTH (pack);
12943 tree right = TREE_VEC_ELT (pack, n - 1);
12944 for (--n; n != 0; --n)
12946 tree left = TREE_VEC_ELT (pack, n - 1);
12947 right = fold_expression (t, left, right, complain);
12949 return right;
12952 /* Substitute into a unary right fold expression. */
12954 static tree
12955 tsubst_unary_right_fold (tree t, tree args, tsubst_flags_t complain,
12956 tree in_decl)
12958 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12959 if (pack == error_mark_node)
12960 return error_mark_node;
12961 if (PACK_EXPANSION_P (pack))
12963 tree r = copy_node (t);
12964 FOLD_EXPR_PACK (r) = pack;
12965 return r;
12967 if (TREE_VEC_LENGTH (pack) == 0)
12968 return expand_empty_fold (t, complain);
12969 else
12970 return expand_right_fold (t, pack, complain);
12973 /* Substitute into a binary right fold expression.
12975 Do ths by building a single (non-empty) vector of arguments and
12976 building the expression from those elements. */
12978 static tree
12979 tsubst_binary_right_fold (tree t, tree args, tsubst_flags_t complain,
12980 tree in_decl)
12982 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12983 if (pack == error_mark_node)
12984 return error_mark_node;
12985 tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
12986 if (init == error_mark_node)
12987 return error_mark_node;
12989 if (PACK_EXPANSION_P (pack))
12991 tree r = copy_node (t);
12992 FOLD_EXPR_PACK (r) = pack;
12993 FOLD_EXPR_INIT (r) = init;
12994 return r;
12997 int n = TREE_VEC_LENGTH (pack);
12998 tree vec = make_tree_vec (n + 1);
12999 for (int i = 0; i < n; ++i)
13000 TREE_VEC_ELT (vec, i) = TREE_VEC_ELT (pack, i);
13001 TREE_VEC_ELT (vec, n) = init;
13003 return expand_right_fold (t, vec, complain);
13006 /* Walk through the pattern of a pack expansion, adding everything in
13007 local_specializations to a list. */
13009 class el_data
13011 public:
13012 /* Set of variables declared within the pattern. */
13013 hash_set<tree> internal;
13014 /* Set of AST nodes that have been visited by the traversal. */
13015 hash_set<tree> visited;
13016 /* List of local_specializations used within the pattern. */
13017 tree extra;
13018 tsubst_flags_t complain;
13020 el_data (tsubst_flags_t c)
13021 : extra (NULL_TREE), complain (c) {}
13023 static tree
13024 extract_locals_r (tree *tp, int */*walk_subtrees*/, void *data_)
13026 el_data &data = *reinterpret_cast<el_data*>(data_);
13027 tree *extra = &data.extra;
13028 tsubst_flags_t complain = data.complain;
13030 if (TYPE_P (*tp) && typedef_variant_p (*tp))
13031 /* Remember local typedefs (85214). */
13032 tp = &TYPE_NAME (*tp);
13034 if (TREE_CODE (*tp) == DECL_EXPR)
13036 tree decl = DECL_EXPR_DECL (*tp);
13037 data.internal.add (decl);
13038 if (VAR_P (decl)
13039 && DECL_DECOMPOSITION_P (decl)
13040 && TREE_TYPE (decl) != error_mark_node)
13042 gcc_assert (DECL_NAME (decl) == NULL_TREE);
13043 for (tree decl2 = DECL_CHAIN (decl);
13044 decl2
13045 && VAR_P (decl2)
13046 && DECL_DECOMPOSITION_P (decl2)
13047 && DECL_NAME (decl2)
13048 && TREE_TYPE (decl2) != error_mark_node;
13049 decl2 = DECL_CHAIN (decl2))
13051 gcc_assert (DECL_DECOMP_BASE (decl2) == decl);
13052 data.internal.add (decl2);
13056 else if (TREE_CODE (*tp) == LAMBDA_EXPR)
13058 /* Since we defer implicit capture, look in the parms and body. */
13059 tree fn = lambda_function (*tp);
13060 cp_walk_tree (&TREE_TYPE (fn), &extract_locals_r, &data,
13061 &data.visited);
13062 cp_walk_tree (&DECL_SAVED_TREE (fn), &extract_locals_r, &data,
13063 &data.visited);
13065 else if (tree spec = retrieve_local_specialization (*tp))
13067 if (data.internal.contains (*tp))
13068 /* Don't mess with variables declared within the pattern. */
13069 return NULL_TREE;
13070 if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
13072 /* Maybe pull out the PARM_DECL for a partial instantiation. */
13073 tree args = ARGUMENT_PACK_ARGS (spec);
13074 if (TREE_VEC_LENGTH (args) == 1)
13076 tree elt = TREE_VEC_ELT (args, 0);
13077 if (PACK_EXPANSION_P (elt))
13078 elt = PACK_EXPANSION_PATTERN (elt);
13079 if (DECL_PACK_P (elt))
13080 spec = elt;
13082 if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
13084 /* Handle lambda capture here, since we aren't doing any
13085 substitution now, and so tsubst_copy won't call
13086 process_outer_var_ref. */
13087 tree args = ARGUMENT_PACK_ARGS (spec);
13088 int len = TREE_VEC_LENGTH (args);
13089 for (int i = 0; i < len; ++i)
13091 tree arg = TREE_VEC_ELT (args, i);
13092 tree carg = arg;
13093 if (outer_automatic_var_p (arg))
13094 carg = process_outer_var_ref (arg, complain);
13095 if (carg != arg)
13097 /* Make a new NONTYPE_ARGUMENT_PACK of the capture
13098 proxies. */
13099 if (i == 0)
13101 spec = copy_node (spec);
13102 args = copy_node (args);
13103 ARGUMENT_PACK_ARGS (spec) = args;
13104 register_local_specialization (spec, *tp);
13106 TREE_VEC_ELT (args, i) = carg;
13111 if (outer_automatic_var_p (spec))
13112 spec = process_outer_var_ref (spec, complain);
13113 *extra = tree_cons (*tp, spec, *extra);
13115 return NULL_TREE;
13117 static tree
13118 extract_local_specs (tree pattern, tsubst_flags_t complain)
13120 el_data data (complain);
13121 cp_walk_tree (&pattern, extract_locals_r, &data, &data.visited);
13122 return data.extra;
13125 /* Extract any uses of local_specializations from PATTERN and add them to ARGS
13126 for use in PACK_EXPANSION_EXTRA_ARGS. */
13128 tree
13129 build_extra_args (tree pattern, tree args, tsubst_flags_t complain)
13131 /* Make a copy of the extra arguments so that they won't get changed
13132 out from under us. */
13133 tree extra = preserve_args (copy_template_args (args), /*cow_p=*/false);
13134 if (local_specializations)
13135 if (tree locals = extract_local_specs (pattern, complain))
13136 extra = tree_cons (NULL_TREE, extra, locals);
13137 return extra;
13140 /* Apply any local specializations from PACK_EXPANSION_EXTRA_ARGS and add the
13141 normal template args to ARGS. */
13143 tree
13144 add_extra_args (tree extra, tree args, tsubst_flags_t complain, tree in_decl)
13146 if (extra && TREE_CODE (extra) == TREE_LIST)
13148 for (tree elt = TREE_CHAIN (extra); elt; elt = TREE_CHAIN (elt))
13150 /* The partial instantiation involved local declarations collected in
13151 extract_local_specs; map from the general template to our local
13152 context. */
13153 tree gen = TREE_PURPOSE (elt);
13154 tree inst = TREE_VALUE (elt);
13155 if (DECL_P (inst))
13156 if (tree local = retrieve_local_specialization (inst))
13157 inst = local;
13158 /* else inst is already a full instantiation of the pack. */
13159 register_local_specialization (inst, gen);
13161 gcc_assert (!TREE_PURPOSE (extra));
13162 extra = TREE_VALUE (extra);
13164 if (uses_template_parms (extra))
13166 /* This can happen after dependent substitution into a
13167 requires-expr or a lambda that uses constexpr if. */
13168 extra = tsubst_template_args (extra, args, complain, in_decl);
13169 args = add_outermost_template_args (args, extra);
13171 else
13172 args = add_to_template_args (extra, args);
13173 return args;
13176 /* Substitute ARGS into T, which is an pack expansion
13177 (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
13178 TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
13179 (if only a partial substitution could be performed) or
13180 ERROR_MARK_NODE if there was an error. */
13181 tree
13182 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
13183 tree in_decl)
13185 tree pattern;
13186 tree pack, packs = NULL_TREE;
13187 bool unsubstituted_packs = false;
13188 int i, len = -1;
13189 tree result;
13190 bool need_local_specializations = false;
13191 int levels;
13193 gcc_assert (PACK_EXPANSION_P (t));
13194 pattern = PACK_EXPANSION_PATTERN (t);
13196 /* Add in any args remembered from an earlier partial instantiation. */
13197 args = add_extra_args (PACK_EXPANSION_EXTRA_ARGS (t), args, complain, in_decl);
13199 levels = TMPL_ARGS_DEPTH (args);
13201 /* Determine the argument packs that will instantiate the parameter
13202 packs used in the expansion expression. While we're at it,
13203 compute the number of arguments to be expanded and make sure it
13204 is consistent. */
13205 for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
13206 pack = TREE_CHAIN (pack))
13208 tree parm_pack = TREE_VALUE (pack);
13209 tree arg_pack = NULL_TREE;
13210 tree orig_arg = NULL_TREE;
13211 int level = 0;
13213 if (TREE_CODE (parm_pack) == BASES)
13215 gcc_assert (parm_pack == pattern);
13216 if (BASES_DIRECT (parm_pack))
13217 return calculate_direct_bases (tsubst_expr (BASES_TYPE (parm_pack),
13218 args, complain,
13219 in_decl),
13220 complain);
13221 else
13222 return calculate_bases (tsubst_expr (BASES_TYPE (parm_pack),
13223 args, complain, in_decl),
13224 complain);
13226 else if (builtin_pack_call_p (parm_pack))
13228 if (parm_pack != pattern)
13230 if (complain & tf_error)
13231 sorry ("%qE is not the entire pattern of the pack expansion",
13232 parm_pack);
13233 return error_mark_node;
13235 return expand_builtin_pack_call (parm_pack, args,
13236 complain, in_decl);
13238 else if (TREE_CODE (parm_pack) == PARM_DECL)
13240 /* We know we have correct local_specializations if this
13241 expansion is at function scope, or if we're dealing with a
13242 local parameter in a requires expression; for the latter,
13243 tsubst_requires_expr set it up appropriately. */
13244 if (PACK_EXPANSION_LOCAL_P (t) || CONSTRAINT_VAR_P (parm_pack))
13245 arg_pack = retrieve_local_specialization (parm_pack);
13246 else
13247 /* We can't rely on local_specializations for a parameter
13248 name used later in a function declaration (such as in a
13249 late-specified return type). Even if it exists, it might
13250 have the wrong value for a recursive call. */
13251 need_local_specializations = true;
13253 if (!arg_pack)
13255 /* This parameter pack was used in an unevaluated context. Just
13256 make a dummy decl, since it's only used for its type. */
13257 ++cp_unevaluated_operand;
13258 arg_pack = tsubst_decl (parm_pack, args, complain);
13259 --cp_unevaluated_operand;
13260 if (arg_pack && DECL_PACK_P (arg_pack))
13261 /* Partial instantiation of the parm_pack, we can't build
13262 up an argument pack yet. */
13263 arg_pack = NULL_TREE;
13264 else
13265 arg_pack = make_fnparm_pack (arg_pack);
13267 else if (DECL_PACK_P (arg_pack))
13268 /* This argument pack isn't fully instantiated yet. */
13269 arg_pack = NULL_TREE;
13271 else if (is_capture_proxy (parm_pack))
13273 arg_pack = retrieve_local_specialization (parm_pack);
13274 if (DECL_PACK_P (arg_pack))
13275 arg_pack = NULL_TREE;
13277 else
13279 int idx;
13280 template_parm_level_and_index (parm_pack, &level, &idx);
13281 if (level <= levels)
13282 arg_pack = TMPL_ARG (args, level, idx);
13284 if (arg_pack && TREE_CODE (arg_pack) == TEMPLATE_TYPE_PARM
13285 && TEMPLATE_TYPE_PARAMETER_PACK (arg_pack))
13286 arg_pack = NULL_TREE;
13289 orig_arg = arg_pack;
13290 if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
13291 arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
13293 if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
13294 /* This can only happen if we forget to expand an argument
13295 pack somewhere else. Just return an error, silently. */
13297 result = make_tree_vec (1);
13298 TREE_VEC_ELT (result, 0) = error_mark_node;
13299 return result;
13302 if (arg_pack)
13304 int my_len =
13305 TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
13307 /* Don't bother trying to do a partial substitution with
13308 incomplete packs; we'll try again after deduction. */
13309 if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
13310 return t;
13312 if (len < 0)
13313 len = my_len;
13314 else if (len != my_len)
13316 if (!(complain & tf_error))
13317 /* Fail quietly. */;
13318 else if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
13319 error ("mismatched argument pack lengths while expanding %qT",
13320 pattern);
13321 else
13322 error ("mismatched argument pack lengths while expanding %qE",
13323 pattern);
13324 return error_mark_node;
13327 /* Keep track of the parameter packs and their corresponding
13328 argument packs. */
13329 packs = tree_cons (parm_pack, arg_pack, packs);
13330 TREE_TYPE (packs) = orig_arg;
13332 else
13334 /* We can't substitute for this parameter pack. We use a flag as
13335 well as the missing_level counter because function parameter
13336 packs don't have a level. */
13337 gcc_assert (processing_template_decl || is_auto (parm_pack));
13338 unsubstituted_packs = true;
13342 /* If the expansion is just T..., return the matching argument pack, unless
13343 we need to call convert_from_reference on all the elements. This is an
13344 important optimization; see c++/68422. */
13345 if (!unsubstituted_packs
13346 && TREE_PURPOSE (packs) == pattern)
13348 tree args = ARGUMENT_PACK_ARGS (TREE_VALUE (packs));
13350 /* If the argument pack is a single pack expansion, pull it out. */
13351 if (TREE_VEC_LENGTH (args) == 1
13352 && pack_expansion_args_count (args))
13353 return TREE_VEC_ELT (args, 0);
13355 /* Types need no adjustment, nor does sizeof..., and if we still have
13356 some pack expansion args we won't do anything yet. */
13357 if (TREE_CODE (t) == TYPE_PACK_EXPANSION
13358 || PACK_EXPANSION_SIZEOF_P (t)
13359 || pack_expansion_args_count (args))
13360 return args;
13361 /* Also optimize expression pack expansions if we can tell that the
13362 elements won't have reference type. */
13363 tree type = TREE_TYPE (pattern);
13364 if (type && !TYPE_REF_P (type)
13365 && !PACK_EXPANSION_P (type)
13366 && !WILDCARD_TYPE_P (type))
13367 return args;
13368 /* Otherwise use the normal path so we get convert_from_reference. */
13371 /* We cannot expand this expansion expression, because we don't have
13372 all of the argument packs we need. */
13373 if (use_pack_expansion_extra_args_p (t, packs, len, unsubstituted_packs))
13375 /* We got some full packs, but we can't substitute them in until we
13376 have values for all the packs. So remember these until then. */
13378 t = make_pack_expansion (pattern, complain);
13379 PACK_EXPANSION_EXTRA_ARGS (t)
13380 = build_extra_args (pattern, args, complain);
13381 return t;
13384 /* If NEED_LOCAL_SPECIALIZATIONS then we're in a late-specified return
13385 type, so create our own local specializations map; the current map is
13386 either NULL or (in the case of recursive unification) might have
13387 bindings that we don't want to use or alter. */
13388 local_specialization_stack lss (need_local_specializations
13389 ? lss_blank : lss_nop);
13391 if (unsubstituted_packs)
13393 /* There were no real arguments, we're just replacing a parameter
13394 pack with another version of itself. Substitute into the
13395 pattern and return a PACK_EXPANSION_*. The caller will need to
13396 deal with that. */
13397 if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
13398 result = tsubst_expr (pattern, args, complain, in_decl);
13399 else
13400 result = tsubst (pattern, args, complain, in_decl);
13401 result = make_pack_expansion (result, complain);
13402 PACK_EXPANSION_LOCAL_P (result) = PACK_EXPANSION_LOCAL_P (t);
13403 PACK_EXPANSION_SIZEOF_P (result) = PACK_EXPANSION_SIZEOF_P (t);
13404 if (PACK_EXPANSION_AUTO_P (t))
13406 /* This is a fake auto... pack expansion created in add_capture with
13407 _PACKS that don't appear in the pattern. Copy one over. */
13408 packs = PACK_EXPANSION_PARAMETER_PACKS (t);
13409 pack = retrieve_local_specialization (TREE_VALUE (packs));
13410 gcc_checking_assert (DECL_PACK_P (pack));
13411 PACK_EXPANSION_PARAMETER_PACKS (result)
13412 = build_tree_list (NULL_TREE, pack);
13413 PACK_EXPANSION_AUTO_P (result) = true;
13415 return result;
13418 gcc_assert (len >= 0);
13420 /* For each argument in each argument pack, substitute into the
13421 pattern. */
13422 result = make_tree_vec (len);
13423 tree elem_args = copy_template_args (args);
13424 for (i = 0; i < len; ++i)
13426 t = gen_elem_of_pack_expansion_instantiation (pattern, packs,
13428 elem_args, complain,
13429 in_decl);
13430 TREE_VEC_ELT (result, i) = t;
13431 if (t == error_mark_node)
13433 result = error_mark_node;
13434 break;
13438 /* Update ARGS to restore the substitution from parameter packs to
13439 their argument packs. */
13440 for (pack = packs; pack; pack = TREE_CHAIN (pack))
13442 tree parm = TREE_PURPOSE (pack);
13444 if (TREE_CODE (parm) == PARM_DECL
13445 || VAR_P (parm)
13446 || TREE_CODE (parm) == FIELD_DECL)
13447 register_local_specialization (TREE_TYPE (pack), parm);
13448 else
13450 int idx, level;
13452 if (TREE_VALUE (pack) == NULL_TREE)
13453 continue;
13455 template_parm_level_and_index (parm, &level, &idx);
13457 /* Update the corresponding argument. */
13458 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
13459 TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
13460 TREE_TYPE (pack);
13461 else
13462 TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
13466 /* If the dependent pack arguments were such that we end up with only a
13467 single pack expansion again, there's no need to keep it in a TREE_VEC. */
13468 if (len == 1 && TREE_CODE (result) == TREE_VEC
13469 && PACK_EXPANSION_P (TREE_VEC_ELT (result, 0)))
13470 return TREE_VEC_ELT (result, 0);
13472 return result;
13475 /* Make an argument pack out of the TREE_VEC VEC. */
13477 static tree
13478 make_argument_pack (tree vec)
13480 tree pack;
13482 if (TYPE_P (TREE_VEC_ELT (vec, 0)))
13483 pack = cxx_make_type (TYPE_ARGUMENT_PACK);
13484 else
13486 pack = make_node (NONTYPE_ARGUMENT_PACK);
13487 TREE_CONSTANT (pack) = 1;
13489 ARGUMENT_PACK_ARGS (pack) = vec;
13490 return pack;
13493 /* Return an exact copy of template args T that can be modified
13494 independently. */
13496 static tree
13497 copy_template_args (tree t)
13499 if (t == error_mark_node)
13500 return t;
13502 int len = TREE_VEC_LENGTH (t);
13503 tree new_vec = make_tree_vec (len);
13505 for (int i = 0; i < len; ++i)
13507 tree elt = TREE_VEC_ELT (t, i);
13508 if (elt && TREE_CODE (elt) == TREE_VEC)
13509 elt = copy_template_args (elt);
13510 TREE_VEC_ELT (new_vec, i) = elt;
13513 NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_vec)
13514 = NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
13516 return new_vec;
13519 /* Substitute ARGS into the *_ARGUMENT_PACK orig_arg. */
13521 tree
13522 tsubst_argument_pack (tree orig_arg, tree args, tsubst_flags_t complain,
13523 tree in_decl)
13525 /* This flag is used only during deduction, and we don't expect to
13526 substitute such ARGUMENT_PACKs. */
13527 gcc_assert (!ARGUMENT_PACK_INCOMPLETE_P (orig_arg));
13529 /* Substitute into each of the arguments. */
13530 tree pack_args = tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
13531 args, complain, in_decl);
13532 if (pack_args == error_mark_node)
13533 return error_mark_node;
13535 if (pack_args == ARGUMENT_PACK_ARGS (orig_arg))
13536 return orig_arg;
13538 /* If we're substituting into a generic ARGUMENT_PACK for a variadic
13539 template parameter, we might be able to avoid allocating a new
13540 ARGUMENT_PACK and reuse the corresponding ARGUMENT_PACK from ARGS
13541 if the substituted result is identical to it. */
13542 if (tree parm = template_arg_to_parm (orig_arg))
13544 int level, index;
13545 template_parm_level_and_index (parm, &level, &index);
13546 if (TMPL_ARGS_DEPTH (args) >= level)
13547 if (tree arg = TMPL_ARG (args, level, index))
13548 if (TREE_CODE (arg) == TREE_CODE (orig_arg)
13549 && ARGUMENT_PACK_ARGS (arg) == pack_args)
13551 gcc_assert (!ARGUMENT_PACK_INCOMPLETE_P (arg));
13552 return arg;
13556 tree new_arg;
13557 if (TYPE_P (orig_arg))
13559 new_arg = cxx_make_type (TREE_CODE (orig_arg));
13560 SET_TYPE_STRUCTURAL_EQUALITY (new_arg);
13562 else
13564 new_arg = make_node (TREE_CODE (orig_arg));
13565 TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
13567 ARGUMENT_PACK_ARGS (new_arg) = pack_args;
13568 return new_arg;
13571 /* Substitute ARGS into the vector or list of template arguments T. */
13573 tree
13574 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
13576 if (t == error_mark_node)
13577 return error_mark_node;
13579 /* In "sizeof(X<I>)" we need to evaluate "I". */
13580 cp_evaluated ev;
13582 const int len = TREE_VEC_LENGTH (t);
13583 tree *elts = XALLOCAVEC (tree, len);
13584 int expanded_len_adjust = 0;
13586 /* True iff the substituted result is identical to T. */
13587 bool const_subst_p = true;
13589 for (int i = 0; i < len; i++)
13591 tree orig_arg = TREE_VEC_ELT (t, i);
13592 tree new_arg;
13594 if (!orig_arg)
13595 new_arg = NULL_TREE;
13596 else if (TREE_CODE (orig_arg) == TREE_VEC)
13597 new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
13598 else if (PACK_EXPANSION_P (orig_arg))
13600 /* Substitute into an expansion expression. */
13601 new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
13603 if (TREE_CODE (new_arg) == TREE_VEC)
13604 /* Add to the expanded length adjustment the number of
13605 expanded arguments. We subtract one from this
13606 measurement, because the argument pack expression
13607 itself is already counted as 1 in
13608 LEN. EXPANDED_LEN_ADJUST can actually be negative, if
13609 the argument pack is empty. */
13610 expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
13612 else if (ARGUMENT_PACK_P (orig_arg))
13613 new_arg = tsubst_argument_pack (orig_arg, args, complain, in_decl);
13614 else
13615 new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
13617 if (new_arg == error_mark_node)
13618 return error_mark_node;
13620 elts[i] = new_arg;
13621 if (new_arg != orig_arg)
13622 const_subst_p = false;
13625 if (const_subst_p)
13626 return t;
13628 tree maybe_reuse = NULL_TREE;
13630 /* If ARGS and T are both multi-level, the substituted result may be
13631 identical to ARGS. */
13632 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (t)
13633 && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args)
13634 && TMPL_ARGS_DEPTH (t) == TMPL_ARGS_DEPTH (args))
13635 maybe_reuse = args;
13636 /* If T appears to be a vector of generic template arguments, the
13637 substituted result may be identical to the corresponding level
13638 from ARGS. */
13639 else if (tree parm = template_arg_to_parm (TREE_VEC_ELT (t, 0)))
13641 int level, index;
13642 template_parm_level_and_index (parm, &level, &index);
13643 if (index == 0 && TMPL_ARGS_DEPTH (args) >= level)
13644 maybe_reuse = TMPL_ARGS_LEVEL (args, level);
13647 /* If the substituted result is identical to MAYBE_REUSE, return
13648 it and avoid allocating a new TREE_VEC, as an optimization. */
13649 if (maybe_reuse != NULL_TREE
13650 && TREE_VEC_LENGTH (maybe_reuse) == len
13651 && std::equal (elts, elts+len, TREE_VEC_BEGIN (maybe_reuse)))
13652 return maybe_reuse;
13654 /* If T consists of only a pack expansion for which substitution yielded
13655 a TREE_VEC of the expanded elements, then reuse that TREE_VEC instead
13656 of effectively making a copy. */
13657 if (len == 1
13658 && PACK_EXPANSION_P (TREE_VEC_ELT (t, 0))
13659 && TREE_CODE (elts[0]) == TREE_VEC)
13660 return elts[0];
13662 /* Make space for the expanded arguments coming from template
13663 argument packs. */
13664 tree r = make_tree_vec (len + expanded_len_adjust);
13665 /* T can contain TREE_VECs. That happens if T contains the
13666 arguments for a member template.
13667 In that case each TREE_VEC in T represents a level of template
13668 arguments, and T won't carry any non defaulted argument count.
13669 It will rather be the nested TREE_VECs that will carry one.
13670 In other words, T carries a non defaulted argument count only
13671 if it doesn't contain any nested TREE_VEC. */
13672 if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (t))
13674 int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
13675 count += expanded_len_adjust;
13676 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (r, count);
13679 int out = 0;
13680 for (int i = 0; i < len; i++)
13682 tree orig_arg = TREE_VEC_ELT (t, i);
13683 if (orig_arg
13684 && PACK_EXPANSION_P (orig_arg)
13685 && TREE_CODE (elts[i]) == TREE_VEC)
13687 /* Now expand the template argument pack "in place". */
13688 for (int idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
13689 TREE_VEC_ELT (r, out) = TREE_VEC_ELT (elts[i], idx);
13691 else
13693 TREE_VEC_ELT (r, out) = elts[i];
13694 out++;
13697 gcc_assert (out == TREE_VEC_LENGTH (r));
13699 return r;
13702 /* Substitute ARGS into one level PARMS of template parameters. */
13704 static tree
13705 tsubst_template_parms_level (tree parms, tree args, tsubst_flags_t complain)
13707 if (parms == error_mark_node)
13708 return error_mark_node;
13710 tree new_vec = make_tree_vec (TREE_VEC_LENGTH (parms));
13712 for (int i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
13714 tree tuple = TREE_VEC_ELT (parms, i);
13716 if (tuple == error_mark_node)
13717 continue;
13719 TREE_VEC_ELT (new_vec, i) =
13720 tsubst_template_parm (tuple, args, complain);
13723 return new_vec;
13726 /* Return the result of substituting ARGS into the template parameters
13727 given by PARMS. If there are m levels of ARGS and m + n levels of
13728 PARMS, then the result will contain n levels of PARMS. For
13729 example, if PARMS is `template <class T> template <class U>
13730 template <T*, U, class V>' and ARGS is {{int}, {double}} then the
13731 result will be `template <int*, double, class V>'. */
13733 static tree
13734 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
13736 tree r = NULL_TREE;
13737 tree* new_parms;
13739 /* When substituting into a template, we must set
13740 PROCESSING_TEMPLATE_DECL as the template parameters may be
13741 dependent if they are based on one-another, and the dependency
13742 predicates are short-circuit outside of templates. */
13743 ++processing_template_decl;
13745 for (new_parms = &r;
13746 parms && TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
13747 new_parms = &(TREE_CHAIN (*new_parms)),
13748 parms = TREE_CHAIN (parms))
13750 tree new_vec = tsubst_template_parms_level (TREE_VALUE (parms),
13751 args, complain);
13752 *new_parms =
13753 tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
13754 - TMPL_ARGS_DEPTH (args)),
13755 new_vec, NULL_TREE);
13756 TEMPLATE_PARMS_CONSTRAINTS (*new_parms)
13757 = TEMPLATE_PARMS_CONSTRAINTS (parms);
13760 --processing_template_decl;
13762 return r;
13765 /* Return the result of substituting ARGS into one template parameter
13766 given by T. T Must be a TREE_LIST which TREE_VALUE is the template
13767 parameter and which TREE_PURPOSE is the default argument of the
13768 template parameter. */
13770 static tree
13771 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
13773 tree default_value, parm_decl;
13775 if (args == NULL_TREE
13776 || t == NULL_TREE
13777 || t == error_mark_node)
13778 return t;
13780 gcc_assert (TREE_CODE (t) == TREE_LIST);
13782 default_value = TREE_PURPOSE (t);
13783 parm_decl = TREE_VALUE (t);
13785 parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
13786 if (TREE_CODE (parm_decl) == PARM_DECL
13787 && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
13788 parm_decl = error_mark_node;
13789 default_value = tsubst_template_arg (default_value, args,
13790 complain, NULL_TREE);
13792 tree r = build_tree_list (default_value, parm_decl);
13793 TEMPLATE_PARM_CONSTRAINTS (r) = TEMPLATE_PARM_CONSTRAINTS (t);
13794 return r;
13797 /* Substitute in-place the TEMPLATE_PARM_CONSTRAINTS of each template
13798 parameter in PARMS for sake of declaration matching. */
13800 static void
13801 tsubst_each_template_parm_constraints (tree parms, tree args,
13802 tsubst_flags_t complain)
13804 ++processing_template_decl;
13805 for (; parms; parms = TREE_CHAIN (parms))
13807 tree level = TREE_VALUE (parms);
13808 for (tree parm : tree_vec_range (level))
13809 TEMPLATE_PARM_CONSTRAINTS (parm)
13810 = tsubst_constraint (TEMPLATE_PARM_CONSTRAINTS (parm), args,
13811 complain, NULL_TREE);
13813 --processing_template_decl;
13816 /* Substitute the ARGS into the indicated aggregate (or enumeration)
13817 type T. If T is not an aggregate or enumeration type, it is
13818 handled as if by tsubst. IN_DECL is as for tsubst. If
13819 ENTERING_SCOPE is nonzero, T is the context for a template which
13820 we are presently tsubst'ing. Return the substituted value. */
13822 static tree
13823 tsubst_aggr_type (tree t,
13824 tree args,
13825 tsubst_flags_t complain,
13826 tree in_decl,
13827 int entering_scope)
13829 if (t == NULL_TREE)
13830 return NULL_TREE;
13832 /* Handle typedefs via tsubst so that they get consistently reused. */
13833 if (typedef_variant_p (t))
13835 t = tsubst (t, args, complain, in_decl);
13836 if (t == error_mark_node)
13837 return error_mark_node;
13839 /* The effect of entering_scope is that for a dependent specialization
13840 A<T>, lookup_template_class prefers to return A's primary template
13841 type instead of the implicit instantiation. So when entering_scope,
13842 we mirror this behavior by inspecting TYPE_CANONICAL appropriately,
13843 taking advantage of the fact that lookup_template_class links the two
13844 types by setting TYPE_CANONICAL of the latter to the former. */
13845 if (entering_scope
13846 && CLASS_TYPE_P (t)
13847 && dependent_type_p (t)
13848 && TYPE_CANONICAL (t) == TREE_TYPE (TYPE_TI_TEMPLATE (t)))
13849 t = TYPE_CANONICAL (t);
13851 return t;
13854 switch (TREE_CODE (t))
13856 case RECORD_TYPE:
13857 case ENUMERAL_TYPE:
13858 case UNION_TYPE:
13859 return tsubst_aggr_type_1 (t, args, complain, in_decl, entering_scope);
13861 default:
13862 return tsubst (t, args, complain, in_decl);
13866 /* The part of tsubst_aggr_type that's shared with the RECORD_, UNION_
13867 and ENUMERAL_TYPE cases of tsubst. */
13869 static tree
13870 tsubst_aggr_type_1 (tree t,
13871 tree args,
13872 tsubst_flags_t complain,
13873 tree in_decl,
13874 int entering_scope)
13876 if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
13878 tree argvec;
13879 tree r;
13881 /* Figure out what arguments are appropriate for the
13882 type we are trying to find. For example, given:
13884 template <class T> struct S;
13885 template <class T, class U> void f(T, U) { S<U> su; }
13887 and supposing that we are instantiating f<int, double>,
13888 then our ARGS will be {int, double}, but, when looking up
13889 S we only want {double}. */
13890 argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
13891 complain, in_decl);
13892 if (argvec == error_mark_node)
13893 r = error_mark_node;
13894 else
13896 r = lookup_template_class (t, argvec, in_decl, NULL_TREE,
13897 entering_scope, complain);
13898 r = cp_build_qualified_type (r, cp_type_quals (t), complain);
13901 return r;
13903 else
13904 /* This is not a template type, so there's nothing to do. */
13905 return t;
13908 /* Map from a FUNCTION_DECL to a vec of default argument instantiations,
13909 indexed in reverse order of the parameters. */
13911 static GTY((cache)) hash_table<tree_vec_map_cache_hasher> *defarg_inst;
13913 /* Return a reference to the vec* of defarg insts for FN. */
13915 static vec<tree,va_gc> *&
13916 defarg_insts_for (tree fn)
13918 if (!defarg_inst)
13919 defarg_inst = hash_table<tree_vec_map_cache_hasher>::create_ggc (13);
13920 tree_vec_map in = { { fn }, nullptr };
13921 tree_vec_map **slot
13922 = defarg_inst->find_slot_with_hash (&in, DECL_UID (fn), INSERT);
13923 if (!*slot)
13925 *slot = ggc_alloc<tree_vec_map> ();
13926 **slot = in;
13928 return (*slot)->to;
13931 /* Substitute into the default argument ARG (a default argument for
13932 FN), which has the indicated TYPE. */
13934 tree
13935 tsubst_default_argument (tree fn, int parmnum, tree type, tree arg,
13936 tsubst_flags_t complain)
13938 int errs = errorcount + sorrycount;
13940 /* This can happen in invalid code. */
13941 if (TREE_CODE (arg) == DEFERRED_PARSE)
13942 return arg;
13944 /* Shortcut {}. */
13945 if (BRACE_ENCLOSED_INITIALIZER_P (arg)
13946 && CONSTRUCTOR_NELTS (arg) == 0)
13947 return arg;
13949 tree parm = FUNCTION_FIRST_USER_PARM (fn);
13950 parm = chain_index (parmnum, parm);
13951 tree parmtype = TREE_TYPE (parm);
13952 if (DECL_BY_REFERENCE (parm))
13953 parmtype = TREE_TYPE (parmtype);
13954 if (parmtype == error_mark_node)
13955 return error_mark_node;
13957 gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, parmtype));
13959 /* Remember the location of the pointer to the vec rather than the location
13960 of the particular element, in case the vec grows in tsubst_expr. */
13961 vec<tree,va_gc> *&defs = defarg_insts_for (fn);
13962 /* Index in reverse order to avoid allocating space for initial parameters
13963 that don't have default arguments. */
13964 unsigned ridx = list_length (parm);
13965 if (vec_safe_length (defs) < ridx)
13966 vec_safe_grow_cleared (defs, ridx);
13967 else if (tree inst = (*defs)[ridx - 1])
13968 return inst;
13970 /* This default argument came from a template. Instantiate the
13971 default argument here, not in tsubst. In the case of
13972 something like:
13974 template <class T>
13975 struct S {
13976 static T t();
13977 void f(T = t());
13980 we must be careful to do name lookup in the scope of S<T>,
13981 rather than in the current class. */
13982 push_to_top_level ();
13983 push_access_scope (fn);
13984 push_deferring_access_checks (dk_no_deferred);
13985 /* So in_immediate_context knows this is a default argument. */
13986 begin_scope (sk_function_parms, fn);
13987 start_lambda_scope (parm);
13989 /* The default argument expression may cause implicitly defined
13990 member functions to be synthesized, which will result in garbage
13991 collection. We must treat this situation as if we were within
13992 the body of function so as to avoid collecting live data on the
13993 stack. */
13994 ++function_depth;
13995 arg = tsubst_expr (arg, DECL_TI_ARGS (fn), complain, NULL_TREE);
13996 --function_depth;
13998 finish_lambda_scope ();
14000 /* Make sure the default argument is reasonable. */
14001 arg = check_default_argument (type, arg, complain);
14003 if (errorcount+sorrycount > errs
14004 && (complain & tf_warning_or_error))
14005 inform (input_location,
14006 " when instantiating default argument for call to %qD", fn);
14008 leave_scope ();
14009 pop_deferring_access_checks ();
14010 pop_access_scope (fn);
14011 pop_from_top_level ();
14013 if (arg != error_mark_node && !cp_unevaluated_operand)
14014 (*defs)[ridx - 1] = arg;
14016 return arg;
14019 /* Substitute into all the default arguments for FN. */
14021 static void
14022 tsubst_default_arguments (tree fn, tsubst_flags_t complain)
14024 tree arg;
14025 tree tmpl_args;
14027 tmpl_args = DECL_TI_ARGS (fn);
14029 /* If this function is not yet instantiated, we certainly don't need
14030 its default arguments. */
14031 if (uses_template_parms (tmpl_args))
14032 return;
14033 /* Don't do this again for clones. */
14034 if (DECL_CLONED_FUNCTION_P (fn))
14035 return;
14037 int i = 0;
14038 for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
14039 arg;
14040 arg = TREE_CHAIN (arg), ++i)
14041 if (TREE_PURPOSE (arg))
14042 TREE_PURPOSE (arg) = tsubst_default_argument (fn, i,
14043 TREE_VALUE (arg),
14044 TREE_PURPOSE (arg),
14045 complain);
14048 /* Hash table mapping a FUNCTION_DECL to its dependent explicit-specifier. */
14049 static GTY((cache)) decl_tree_cache_map *explicit_specifier_map;
14051 /* Store a pair to EXPLICIT_SPECIFIER_MAP. */
14053 void
14054 store_explicit_specifier (tree v, tree t)
14056 if (!explicit_specifier_map)
14057 explicit_specifier_map = decl_tree_cache_map::create_ggc (37);
14058 DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (v) = true;
14059 explicit_specifier_map->put (v, t);
14062 /* Lookup an element in EXPLICIT_SPECIFIER_MAP. */
14064 tree
14065 lookup_explicit_specifier (tree v)
14067 return *explicit_specifier_map->get (v);
14070 /* Given T, a FUNCTION_TYPE or METHOD_TYPE, construct and return a corresponding
14071 FUNCTION_TYPE or METHOD_TYPE whose return type is RETURN_TYPE, argument types
14072 are ARG_TYPES, and exception specification is RAISES, and otherwise is
14073 identical to T. */
14075 static tree
14076 rebuild_function_or_method_type (tree t, tree return_type, tree arg_types,
14077 tree raises, tsubst_flags_t complain)
14079 gcc_assert (FUNC_OR_METHOD_TYPE_P (t));
14081 tree new_type;
14082 if (TREE_CODE (t) == FUNCTION_TYPE)
14084 new_type = build_function_type (return_type, arg_types);
14085 new_type = apply_memfn_quals (new_type, type_memfn_quals (t));
14087 else
14089 tree r = TREE_TYPE (TREE_VALUE (arg_types));
14090 /* Don't pick up extra function qualifiers from the basetype. */
14091 r = cp_build_qualified_type (r, type_memfn_quals (t), complain);
14092 if (! MAYBE_CLASS_TYPE_P (r))
14094 /* [temp.deduct]
14096 Type deduction may fail for any of the following
14097 reasons:
14099 -- Attempting to create "pointer to member of T" when T
14100 is not a class type. */
14101 if (complain & tf_error)
14102 error ("creating pointer to member function of non-class type %qT",
14104 return error_mark_node;
14107 new_type = build_method_type_directly (r, return_type,
14108 TREE_CHAIN (arg_types));
14110 new_type = cp_build_type_attribute_variant (new_type, TYPE_ATTRIBUTES (t));
14112 cp_ref_qualifier rqual = type_memfn_rqual (t);
14113 bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
14114 return build_cp_fntype_variant (new_type, rqual, raises, late_return_type_p);
14117 /* Check if the function type of DECL, a FUNCTION_DECL, agrees with the type of
14118 each of its formal parameters. If there is a disagreement then rebuild
14119 DECL's function type according to its formal parameter types, as part of a
14120 resolution for Core issues 1001/1322. */
14122 static void
14123 maybe_rebuild_function_decl_type (tree decl)
14125 bool function_type_needs_rebuilding = false;
14126 if (tree parm_list = FUNCTION_FIRST_USER_PARM (decl))
14128 tree parm_type_list = FUNCTION_FIRST_USER_PARMTYPE (decl);
14129 while (parm_type_list && parm_type_list != void_list_node)
14131 tree parm_type = TREE_VALUE (parm_type_list);
14132 tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
14133 if (!same_type_p (parm_type, formal_parm_type_unqual))
14135 function_type_needs_rebuilding = true;
14136 break;
14139 parm_list = DECL_CHAIN (parm_list);
14140 parm_type_list = TREE_CHAIN (parm_type_list);
14144 if (!function_type_needs_rebuilding)
14145 return;
14147 const tree fntype = TREE_TYPE (decl);
14148 tree parm_list = DECL_ARGUMENTS (decl);
14149 tree old_parm_type_list = TYPE_ARG_TYPES (fntype);
14150 tree new_parm_type_list = NULL_TREE;
14151 tree *q = &new_parm_type_list;
14152 for (int skip = num_artificial_parms_for (decl); skip > 0; skip--)
14154 *q = copy_node (old_parm_type_list);
14155 parm_list = DECL_CHAIN (parm_list);
14156 old_parm_type_list = TREE_CHAIN (old_parm_type_list);
14157 q = &TREE_CHAIN (*q);
14159 while (old_parm_type_list && old_parm_type_list != void_list_node)
14161 *q = copy_node (old_parm_type_list);
14162 tree *new_parm_type = &TREE_VALUE (*q);
14163 tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
14164 if (!same_type_p (*new_parm_type, formal_parm_type_unqual))
14165 *new_parm_type = formal_parm_type_unqual;
14167 parm_list = DECL_CHAIN (parm_list);
14168 old_parm_type_list = TREE_CHAIN (old_parm_type_list);
14169 q = &TREE_CHAIN (*q);
14171 if (old_parm_type_list == void_list_node)
14172 *q = void_list_node;
14174 TREE_TYPE (decl)
14175 = rebuild_function_or_method_type (fntype,
14176 TREE_TYPE (fntype), new_parm_type_list,
14177 TYPE_RAISES_EXCEPTIONS (fntype), tf_none);
14180 /* Subroutine of tsubst_decl for the case when T is a FUNCTION_DECL. */
14182 static tree
14183 tsubst_function_decl (tree t, tree args, tsubst_flags_t complain,
14184 tree lambda_fntype)
14186 tree gen_tmpl = NULL_TREE, argvec = NULL_TREE;
14187 hashval_t hash = 0;
14188 tree in_decl = t;
14190 /* Nobody should be tsubst'ing into non-template functions. */
14191 gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE
14192 || DECL_LOCAL_DECL_P (t));
14194 if (DECL_LOCAL_DECL_P (t))
14196 if (tree spec = retrieve_local_specialization (t))
14197 return spec;
14199 else if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
14201 /* If T is not dependent, just return it. */
14202 if (!uses_template_parms (DECL_TI_ARGS (t))
14203 && !LAMBDA_FUNCTION_P (t))
14204 return t;
14206 /* A non-templated friend doesn't get DECL_TEMPLATE_INFO. */
14207 if (non_templated_friend_p (t))
14208 goto friend_case;
14210 /* Calculate the most general template of which R is a
14211 specialization. */
14212 gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
14214 /* We're substituting a lambda function under tsubst_lambda_expr but not
14215 directly from it; find the matching function we're already inside.
14216 But don't do this if T is a generic lambda with a single level of
14217 template parms, as in that case we're doing a normal instantiation. */
14218 if (LAMBDA_FUNCTION_P (t) && !lambda_fntype
14219 && (!generic_lambda_fn_p (t)
14220 || TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)) > 1))
14221 return enclosing_instantiation_of (t);
14223 /* Calculate the complete set of arguments used to
14224 specialize R. */
14225 argvec = tsubst_template_args (DECL_TI_ARGS
14226 (DECL_TEMPLATE_RESULT
14227 (DECL_TI_TEMPLATE (t))),
14228 args, complain, in_decl);
14229 if (argvec == error_mark_node)
14230 return error_mark_node;
14232 /* Check to see if we already have this specialization. */
14233 if (!lambda_fntype)
14235 hash = spec_hasher::hash (gen_tmpl, argvec);
14236 if (tree spec = retrieve_specialization (gen_tmpl, argvec, hash))
14237 /* The spec for these args might be a partial instantiation of the
14238 template, but here what we want is the FUNCTION_DECL. */
14239 return STRIP_TEMPLATE (spec);
14242 else
14244 /* This special case arises when we have something like this:
14246 template <class T> struct S {
14247 friend void f<int>(int, double);
14250 Here, the DECL_TI_TEMPLATE for the friend declaration
14251 will be an IDENTIFIER_NODE. We are being called from
14252 tsubst_friend_function, and we want only to create a
14253 new decl (R) with appropriate types so that we can call
14254 determine_specialization. */
14255 friend_case:
14256 gen_tmpl = NULL_TREE;
14257 argvec = NULL_TREE;
14260 tree closure = (lambda_fntype ? TYPE_METHOD_BASETYPE (lambda_fntype)
14261 : NULL_TREE);
14262 tree ctx = closure ? closure : DECL_CONTEXT (t);
14263 bool member = ctx && TYPE_P (ctx);
14265 if (member && !closure)
14266 ctx = tsubst_aggr_type (ctx, args,
14267 complain, t, /*entering_scope=*/1);
14269 tree type = (lambda_fntype ? lambda_fntype
14270 : tsubst (TREE_TYPE (t), args,
14271 complain | tf_fndecl_type, in_decl));
14272 if (type == error_mark_node)
14273 return error_mark_node;
14275 /* If we hit excessive deduction depth, the type is bogus even if
14276 it isn't error_mark_node, so don't build a decl. */
14277 if (excessive_deduction_depth)
14278 return error_mark_node;
14280 /* We do NOT check for matching decls pushed separately at this
14281 point, as they may not represent instantiations of this
14282 template, and in any case are considered separate under the
14283 discrete model. */
14284 tree r = copy_decl (t);
14285 DECL_USE_TEMPLATE (r) = 0;
14286 TREE_TYPE (r) = type;
14287 /* Clear out the mangled name and RTL for the instantiation. */
14288 SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
14289 SET_DECL_RTL (r, NULL);
14290 /* Leave DECL_INITIAL set on deleted instantiations. */
14291 if (!DECL_DELETED_FN (r))
14292 DECL_INITIAL (r) = NULL_TREE;
14293 DECL_CONTEXT (r) = ctx;
14294 set_instantiating_module (r);
14296 /* Handle explicit(dependent-expr). */
14297 if (DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (t))
14299 tree spec = lookup_explicit_specifier (t);
14300 spec = tsubst_copy_and_build (spec, args, complain, in_decl);
14301 spec = build_explicit_specifier (spec, complain);
14302 if (spec == error_mark_node)
14303 return error_mark_node;
14304 if (instantiation_dependent_expression_p (spec))
14305 store_explicit_specifier (r, spec);
14306 else
14308 DECL_NONCONVERTING_P (r) = (spec == boolean_true_node);
14309 DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (r) = false;
14313 /* OpenMP UDRs have the only argument a reference to the declared
14314 type. We want to diagnose if the declared type is a reference,
14315 which is invalid, but as references to references are usually
14316 quietly merged, diagnose it here. */
14317 if (DECL_OMP_DECLARE_REDUCTION_P (t))
14319 tree argtype
14320 = TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (t))));
14321 argtype = tsubst (argtype, args, complain, in_decl);
14322 if (TYPE_REF_P (argtype))
14323 error_at (DECL_SOURCE_LOCATION (t),
14324 "reference type %qT in "
14325 "%<#pragma omp declare reduction%>", argtype);
14326 if (strchr (IDENTIFIER_POINTER (DECL_NAME (t)), '~') == NULL)
14327 DECL_NAME (r) = omp_reduction_id (ERROR_MARK, DECL_NAME (t),
14328 argtype);
14331 if (member && DECL_CONV_FN_P (r))
14332 /* Type-conversion operator. Reconstruct the name, in
14333 case it's the name of one of the template's parameters. */
14334 DECL_NAME (r) = make_conv_op_name (TREE_TYPE (type));
14336 tree parms = DECL_ARGUMENTS (t);
14337 if (closure)
14338 parms = DECL_CHAIN (parms);
14339 parms = tsubst (parms, args, complain, t);
14340 for (tree parm = parms; parm; parm = DECL_CHAIN (parm))
14341 DECL_CONTEXT (parm) = r;
14342 if (closure)
14344 tree tparm = build_this_parm (r, closure, type_memfn_quals (type));
14345 DECL_NAME (tparm) = closure_identifier;
14346 DECL_CHAIN (tparm) = parms;
14347 parms = tparm;
14349 DECL_ARGUMENTS (r) = parms;
14350 DECL_RESULT (r) = NULL_TREE;
14352 maybe_rebuild_function_decl_type (r);
14354 TREE_STATIC (r) = 0;
14355 TREE_PUBLIC (r) = TREE_PUBLIC (t);
14356 DECL_EXTERNAL (r) = 1;
14357 /* If this is an instantiation of a function with internal
14358 linkage, we already know what object file linkage will be
14359 assigned to the instantiation. */
14360 DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
14361 DECL_DEFER_OUTPUT (r) = 0;
14362 DECL_CHAIN (r) = NULL_TREE;
14363 DECL_PENDING_INLINE_INFO (r) = 0;
14364 DECL_PENDING_INLINE_P (r) = 0;
14365 DECL_SAVED_TREE (r) = NULL_TREE;
14366 DECL_STRUCT_FUNCTION (r) = NULL;
14367 TREE_USED (r) = 0;
14368 /* We'll re-clone as appropriate in instantiate_template. */
14369 DECL_CLONED_FUNCTION (r) = NULL_TREE;
14371 /* If we aren't complaining now, return on error before we register
14372 the specialization so that we'll complain eventually. */
14373 if ((complain & tf_error) == 0
14374 && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
14375 && !grok_op_properties (r, /*complain=*/false))
14376 return error_mark_node;
14378 /* Associate the constraints directly with the instantiation. We
14379 don't substitute through the constraints; that's only done when
14380 they are checked. */
14381 if (tree ci = get_constraints (t))
14382 set_constraints (r, ci);
14384 if (DECL_FRIEND_CONTEXT (t))
14385 SET_DECL_FRIEND_CONTEXT (r,
14386 tsubst (DECL_FRIEND_CONTEXT (t),
14387 args, complain, in_decl));
14389 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14390 args, complain, in_decl))
14391 return error_mark_node;
14393 /* Set up the DECL_TEMPLATE_INFO for R. There's no need to do
14394 this in the special friend case mentioned above where
14395 GEN_TMPL is NULL. */
14396 if (gen_tmpl && !closure)
14398 DECL_TEMPLATE_INFO (r)
14399 = build_template_info (gen_tmpl, argvec);
14400 SET_DECL_IMPLICIT_INSTANTIATION (r);
14402 tree new_r
14403 = register_specialization (r, gen_tmpl, argvec, false, hash);
14404 if (new_r != r)
14405 /* We instantiated this while substituting into
14406 the type earlier (template/friend54.C). */
14407 return new_r;
14409 /* We're not supposed to instantiate default arguments
14410 until they are called, for a template. But, for a
14411 declaration like:
14413 template <class T> void f ()
14414 { extern void g(int i = T()); }
14416 we should do the substitution when the template is
14417 instantiated. We handle the member function case in
14418 instantiate_class_template since the default arguments
14419 might refer to other members of the class. */
14420 if (!member
14421 && !PRIMARY_TEMPLATE_P (gen_tmpl)
14422 && !uses_template_parms (argvec))
14423 tsubst_default_arguments (r, complain);
14425 else if (DECL_LOCAL_DECL_P (r))
14427 if (!cp_unevaluated_operand)
14428 register_local_specialization (r, t);
14430 else
14431 DECL_TEMPLATE_INFO (r) = NULL_TREE;
14433 /* Copy the list of befriending classes. */
14434 for (tree *friends = &DECL_BEFRIENDING_CLASSES (r);
14435 *friends;
14436 friends = &TREE_CHAIN (*friends))
14438 *friends = copy_node (*friends);
14439 TREE_VALUE (*friends)
14440 = tsubst (TREE_VALUE (*friends), args, complain, in_decl);
14443 if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
14445 maybe_retrofit_in_chrg (r);
14446 if (DECL_CONSTRUCTOR_P (r) && !grok_ctor_properties (ctx, r))
14447 return error_mark_node;
14448 /* If this is an instantiation of a member template, clone it.
14449 If it isn't, that'll be handled by
14450 clone_constructors_and_destructors. */
14451 if (gen_tmpl && PRIMARY_TEMPLATE_P (gen_tmpl))
14452 clone_cdtor (r, /*update_methods=*/false);
14454 else if ((complain & tf_error) != 0
14455 && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
14456 && !grok_op_properties (r, /*complain=*/true))
14457 return error_mark_node;
14459 /* Possibly limit visibility based on template args. */
14460 DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
14461 if (DECL_VISIBILITY_SPECIFIED (t))
14463 DECL_VISIBILITY_SPECIFIED (r) = 0;
14464 DECL_ATTRIBUTES (r)
14465 = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
14467 determine_visibility (r);
14468 if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
14469 && !processing_template_decl)
14470 defaulted_late_check (r);
14472 if (flag_openmp)
14473 if (tree attr = lookup_attribute ("omp declare variant base",
14474 DECL_ATTRIBUTES (r)))
14475 omp_declare_variant_finalize (r, attr);
14477 return r;
14480 /* Subroutine of tsubst_decl for the case when T is a TEMPLATE_DECL. */
14482 static tree
14483 tsubst_template_decl (tree t, tree args, tsubst_flags_t complain,
14484 tree lambda_fntype)
14486 /* We can get here when processing a member function template,
14487 member class template, or template template parameter. */
14488 tree decl = DECL_TEMPLATE_RESULT (t);
14489 tree in_decl = t;
14490 tree spec;
14491 tree tmpl_args;
14492 tree full_args;
14493 tree r;
14494 hashval_t hash = 0;
14496 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
14498 /* Template template parameter is treated here. */
14499 tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14500 if (new_type == error_mark_node)
14501 r = error_mark_node;
14502 /* If we get a real template back, return it. This can happen in
14503 the context of most_specialized_partial_spec. */
14504 else if (TREE_CODE (new_type) == TEMPLATE_DECL)
14505 r = new_type;
14506 else
14507 /* The new TEMPLATE_DECL was built in
14508 reduce_template_parm_level. */
14509 r = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (new_type);
14510 return r;
14513 if (!lambda_fntype)
14515 /* We might already have an instance of this template.
14516 The ARGS are for the surrounding class type, so the
14517 full args contain the tsubst'd args for the context,
14518 plus the innermost args from the template decl. */
14519 tmpl_args = DECL_CLASS_TEMPLATE_P (t)
14520 ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
14521 : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
14522 /* Because this is a template, the arguments will still be
14523 dependent, even after substitution. If
14524 PROCESSING_TEMPLATE_DECL is not set, the dependency
14525 predicates will short-circuit. */
14526 ++processing_template_decl;
14527 full_args = tsubst_template_args (tmpl_args, args,
14528 complain, in_decl);
14529 --processing_template_decl;
14530 if (full_args == error_mark_node)
14531 return error_mark_node;
14533 /* If this is a default template template argument,
14534 tsubst might not have changed anything. */
14535 if (full_args == tmpl_args)
14536 return t;
14538 hash = spec_hasher::hash (t, full_args);
14539 spec = retrieve_specialization (t, full_args, hash);
14540 if (spec != NULL_TREE)
14542 if (TYPE_P (spec))
14543 /* Type partial instantiations are stored as the type by
14544 lookup_template_class_1, not here as the template. */
14545 spec = CLASSTYPE_TI_TEMPLATE (spec);
14546 return spec;
14550 /* Make a new template decl. It will be similar to the
14551 original, but will record the current template arguments.
14552 We also create a new function declaration, which is just
14553 like the old one, but points to this new template, rather
14554 than the old one. */
14555 r = copy_decl (t);
14556 gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
14557 DECL_CHAIN (r) = NULL_TREE;
14559 // Build new template info linking to the original template decl.
14560 if (!lambda_fntype)
14562 DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
14563 SET_DECL_IMPLICIT_INSTANTIATION (r);
14565 else
14566 DECL_TEMPLATE_INFO (r) = NULL_TREE;
14568 /* The template parameters for this new template are all the
14569 template parameters for the old template, except the
14570 outermost level of parameters. */
14571 auto tparm_guard = make_temp_override (current_template_parms);
14572 DECL_TEMPLATE_PARMS (r)
14573 = current_template_parms
14574 = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
14575 complain);
14577 bool class_p = false;
14578 tree inner = decl;
14579 ++processing_template_decl;
14580 if (TREE_CODE (inner) == FUNCTION_DECL)
14581 inner = tsubst_function_decl (inner, args, complain, lambda_fntype);
14582 else
14584 if (TREE_CODE (inner) == TYPE_DECL && !TYPE_DECL_ALIAS_P (inner))
14586 class_p = true;
14587 inner = TREE_TYPE (inner);
14589 if (class_p)
14590 inner = tsubst_aggr_type (inner, args, complain,
14591 in_decl, /*entering*/1);
14592 else
14593 inner = tsubst (inner, args, complain, in_decl);
14595 --processing_template_decl;
14596 if (inner == error_mark_node)
14597 return error_mark_node;
14599 if (class_p)
14601 /* For a partial specialization, we need to keep pointing to
14602 the primary template. */
14603 if (!DECL_TEMPLATE_SPECIALIZATION (t))
14604 CLASSTYPE_TI_TEMPLATE (inner) = r;
14606 DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (inner);
14607 inner = TYPE_MAIN_DECL (inner);
14609 else if (lambda_fntype)
14611 tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (r));
14612 DECL_TEMPLATE_INFO (inner) = build_template_info (r, args);
14614 else
14616 DECL_TI_TEMPLATE (inner) = r;
14617 DECL_TI_ARGS (r) = DECL_TI_ARGS (inner);
14620 DECL_TEMPLATE_RESULT (r) = inner;
14621 TREE_TYPE (r) = TREE_TYPE (inner);
14622 DECL_CONTEXT (r) = DECL_CONTEXT (inner);
14624 if (modules_p ())
14626 /* Propagate module information from the decl. */
14627 DECL_MODULE_EXPORT_P (r) = DECL_MODULE_EXPORT_P (inner);
14628 if (DECL_LANG_SPECIFIC (inner))
14629 /* If this is a constrained template, the above tsubst of
14630 inner can find the unconstrained template, which may have
14631 come from an import. This is ok, because we don't
14632 register this instantiation (see below). */
14633 gcc_checking_assert (!DECL_MODULE_IMPORT_P (inner)
14634 || (TEMPLATE_PARMS_CONSTRAINTS
14635 (DECL_TEMPLATE_PARMS (t))));
14638 DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
14639 DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
14641 if (PRIMARY_TEMPLATE_P (t))
14642 DECL_PRIMARY_TEMPLATE (r) = r;
14644 if (TREE_CODE (decl) == FUNCTION_DECL && !lambda_fntype)
14645 /* Record this non-type partial instantiation. */
14646 register_specialization (r, t,
14647 DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
14648 false, hash);
14650 return r;
14653 /* True if FN is the op() for a lambda in an uninstantiated template. */
14655 bool
14656 lambda_fn_in_template_p (tree fn)
14658 if (!fn || !LAMBDA_FUNCTION_P (fn))
14659 return false;
14660 tree closure = DECL_CONTEXT (fn);
14661 return CLASSTYPE_TEMPLATE_INFO (closure) != NULL_TREE;
14664 /* True if FN is the substitution (via tsubst_lambda_expr) of a function for
14665 which the above is true. */
14667 bool
14668 regenerated_lambda_fn_p (tree fn)
14670 if (!fn || !LAMBDA_FUNCTION_P (fn))
14671 return false;
14672 tree closure = DECL_CONTEXT (fn);
14673 tree lam = CLASSTYPE_LAMBDA_EXPR (closure);
14674 return LAMBDA_EXPR_REGEN_INFO (lam) != NULL_TREE;
14677 /* Return the LAMBDA_EXPR from which T was ultimately regenerated.
14678 If T is not a regenerated LAMBDA_EXPR, return T. */
14680 tree
14681 most_general_lambda (tree t)
14683 while (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
14684 t = TI_TEMPLATE (ti);
14685 return t;
14688 /* Return the set of template arguments used to regenerate the lambda T
14689 from its most general lambda. */
14691 tree
14692 lambda_regenerating_args (tree t)
14694 if (LAMBDA_FUNCTION_P (t))
14695 t = CLASSTYPE_LAMBDA_EXPR (DECL_CONTEXT (t));
14696 gcc_assert (TREE_CODE (t) == LAMBDA_EXPR);
14697 if (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
14698 return TI_ARGS (ti);
14699 else
14700 return NULL_TREE;
14703 /* We're instantiating a variable from template function TCTX. Return the
14704 corresponding current enclosing scope. We can match them up using
14705 DECL_SOURCE_LOCATION because lambdas only ever have one source location, and
14706 the DECL_SOURCE_LOCATION for a function instantiation is updated to match
14707 the template definition in regenerate_decl_from_template. */
14709 static tree
14710 enclosing_instantiation_of (tree tctx)
14712 tree fn = current_function_decl;
14714 /* We shouldn't ever need to do this for other artificial functions. */
14715 gcc_assert (!DECL_ARTIFICIAL (tctx) || LAMBDA_FUNCTION_P (tctx));
14717 for (; fn; fn = decl_function_context (fn))
14718 if (DECL_SOURCE_LOCATION (fn) == DECL_SOURCE_LOCATION (tctx))
14719 return fn;
14720 gcc_unreachable ();
14723 /* Substitute the ARGS into the T, which is a _DECL. Return the
14724 result of the substitution. Issue error and warning messages under
14725 control of COMPLAIN. */
14727 static tree
14728 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
14730 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
14731 location_t saved_loc;
14732 tree r = NULL_TREE;
14733 tree in_decl = t;
14734 hashval_t hash = 0;
14736 /* Set the filename and linenumber to improve error-reporting. */
14737 saved_loc = input_location;
14738 input_location = DECL_SOURCE_LOCATION (t);
14740 switch (TREE_CODE (t))
14742 case TEMPLATE_DECL:
14743 r = tsubst_template_decl (t, args, complain, /*lambda*/NULL_TREE);
14744 break;
14746 case FUNCTION_DECL:
14747 r = tsubst_function_decl (t, args, complain, /*lambda*/NULL_TREE);
14748 break;
14750 case PARM_DECL:
14752 tree type = NULL_TREE;
14753 int i, len = 1;
14754 tree expanded_types = NULL_TREE;
14755 tree prev_r = NULL_TREE;
14756 tree first_r = NULL_TREE;
14758 if (DECL_PACK_P (t))
14760 /* If there is a local specialization that isn't a
14761 parameter pack, it means that we're doing a "simple"
14762 substitution from inside tsubst_pack_expansion. Just
14763 return the local specialization (which will be a single
14764 parm). */
14765 tree spec = retrieve_local_specialization (t);
14766 if (spec
14767 && TREE_CODE (spec) == PARM_DECL
14768 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
14769 RETURN (spec);
14771 /* Expand the TYPE_PACK_EXPANSION that provides the types for
14772 the parameters in this function parameter pack. */
14773 expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
14774 complain, in_decl);
14775 if (TREE_CODE (expanded_types) == TREE_VEC)
14777 len = TREE_VEC_LENGTH (expanded_types);
14779 /* Zero-length parameter packs are boring. Just substitute
14780 into the chain. */
14781 if (len == 0 && !cp_unevaluated_operand)
14782 RETURN (tsubst (TREE_CHAIN (t), args, complain,
14783 TREE_CHAIN (t)));
14785 else
14787 /* All we did was update the type. Make a note of that. */
14788 type = expanded_types;
14789 expanded_types = NULL_TREE;
14793 /* Loop through all of the parameters we'll build. When T is
14794 a function parameter pack, LEN is the number of expanded
14795 types in EXPANDED_TYPES; otherwise, LEN is 1. */
14796 r = NULL_TREE;
14797 for (i = 0; i < len; ++i)
14799 prev_r = r;
14800 r = copy_node (t);
14801 if (DECL_TEMPLATE_PARM_P (t))
14802 SET_DECL_TEMPLATE_PARM_P (r);
14804 if (expanded_types)
14805 /* We're on the Ith parameter of the function parameter
14806 pack. */
14808 /* Get the Ith type. */
14809 type = TREE_VEC_ELT (expanded_types, i);
14811 /* Rename the parameter to include the index. */
14812 DECL_NAME (r)
14813 = make_ith_pack_parameter_name (DECL_NAME (r), i);
14815 else if (!type)
14816 /* We're dealing with a normal parameter. */
14817 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14819 type = type_decays_to (type);
14820 TREE_TYPE (r) = type;
14821 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
14823 if (DECL_INITIAL (r))
14825 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
14826 DECL_INITIAL (r) = TREE_TYPE (r);
14827 else
14828 DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
14829 complain, in_decl);
14832 DECL_CONTEXT (r) = NULL_TREE;
14834 if (!DECL_TEMPLATE_PARM_P (r))
14835 DECL_ARG_TYPE (r) = type_passed_as (type);
14837 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14838 args, complain, in_decl))
14839 return error_mark_node;
14841 /* Keep track of the first new parameter we
14842 generate. That's what will be returned to the
14843 caller. */
14844 if (!first_r)
14845 first_r = r;
14847 /* Build a proper chain of parameters when substituting
14848 into a function parameter pack. */
14849 if (prev_r)
14850 DECL_CHAIN (prev_r) = r;
14853 /* If cp_unevaluated_operand is set, we're just looking for a
14854 single dummy parameter, so don't keep going. */
14855 if (DECL_CHAIN (t) && !cp_unevaluated_operand)
14856 DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
14857 complain, DECL_CHAIN (t));
14859 /* FIRST_R contains the start of the chain we've built. */
14860 r = first_r;
14862 break;
14864 case FIELD_DECL:
14866 tree type = NULL_TREE;
14867 tree vec = NULL_TREE;
14868 tree expanded_types = NULL_TREE;
14869 int len = 1;
14871 if (PACK_EXPANSION_P (TREE_TYPE (t)))
14873 /* This field is a lambda capture pack. Return a TREE_VEC of
14874 the expanded fields to instantiate_class_template_1. */
14875 expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
14876 complain, in_decl);
14877 if (TREE_CODE (expanded_types) == TREE_VEC)
14879 len = TREE_VEC_LENGTH (expanded_types);
14880 vec = make_tree_vec (len);
14882 else
14884 /* All we did was update the type. Make a note of that. */
14885 type = expanded_types;
14886 expanded_types = NULL_TREE;
14890 for (int i = 0; i < len; ++i)
14892 r = copy_decl (t);
14893 if (expanded_types)
14895 type = TREE_VEC_ELT (expanded_types, i);
14896 DECL_NAME (r)
14897 = make_ith_pack_parameter_name (DECL_NAME (r), i);
14899 else if (!type)
14900 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14902 if (type == error_mark_node)
14903 RETURN (error_mark_node);
14904 TREE_TYPE (r) = type;
14905 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
14907 if (DECL_C_BIT_FIELD (r))
14908 /* For bit-fields, DECL_BIT_FIELD_REPRESENTATIVE gives the
14909 number of bits. */
14910 DECL_BIT_FIELD_REPRESENTATIVE (r)
14911 = tsubst_expr (DECL_BIT_FIELD_REPRESENTATIVE (t), args,
14912 complain, in_decl);
14913 if (DECL_INITIAL (t))
14915 /* Set up DECL_TEMPLATE_INFO so that we can get at the
14916 NSDMI in perform_member_init. Still set DECL_INITIAL
14917 so that we know there is one. */
14918 DECL_INITIAL (r) = void_node;
14919 gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
14920 retrofit_lang_decl (r);
14921 DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
14923 /* We don't have to set DECL_CONTEXT here; it is set by
14924 finish_member_declaration. */
14925 DECL_CHAIN (r) = NULL_TREE;
14927 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14928 args, complain, in_decl))
14929 return error_mark_node;
14931 if (vec)
14932 TREE_VEC_ELT (vec, i) = r;
14935 if (vec)
14936 r = vec;
14938 break;
14940 case USING_DECL:
14941 /* We reach here only for member using decls. We also need to check
14942 uses_template_parms because DECL_DEPENDENT_P is not set for a
14943 using-declaration that designates a member of the current
14944 instantiation (c++/53549). */
14945 if (DECL_DEPENDENT_P (t)
14946 || uses_template_parms (USING_DECL_SCOPE (t)))
14948 tree scope = USING_DECL_SCOPE (t);
14949 tree name = tsubst_copy (DECL_NAME (t), args, complain, in_decl);
14950 if (PACK_EXPANSION_P (scope))
14952 tree vec = tsubst_pack_expansion (scope, args, complain, in_decl);
14953 int len = TREE_VEC_LENGTH (vec);
14954 r = make_tree_vec (len);
14955 for (int i = 0; i < len; ++i)
14957 tree escope = TREE_VEC_ELT (vec, i);
14958 tree elt = do_class_using_decl (escope, name);
14959 if (!elt)
14961 r = error_mark_node;
14962 break;
14964 else
14966 TREE_PROTECTED (elt) = TREE_PROTECTED (t);
14967 TREE_PRIVATE (elt) = TREE_PRIVATE (t);
14969 TREE_VEC_ELT (r, i) = elt;
14972 else
14974 tree inst_scope = tsubst_copy (USING_DECL_SCOPE (t), args,
14975 complain, in_decl);
14976 r = do_class_using_decl (inst_scope, name);
14977 if (!r)
14978 r = error_mark_node;
14979 else
14981 TREE_PROTECTED (r) = TREE_PROTECTED (t);
14982 TREE_PRIVATE (r) = TREE_PRIVATE (t);
14986 else
14988 r = copy_node (t);
14989 DECL_CHAIN (r) = NULL_TREE;
14991 break;
14993 case TYPE_DECL:
14994 case VAR_DECL:
14996 tree argvec = NULL_TREE;
14997 tree gen_tmpl = NULL_TREE;
14998 tree tmpl = NULL_TREE;
14999 tree type = NULL_TREE;
15001 if (TREE_TYPE (t) == error_mark_node)
15002 RETURN (error_mark_node);
15004 if (TREE_CODE (t) == TYPE_DECL
15005 && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
15007 /* If this is the canonical decl, we don't have to
15008 mess with instantiations, and often we can't (for
15009 typename, template type parms and such). Note that
15010 TYPE_NAME is not correct for the above test if
15011 we've copied the type for a typedef. */
15012 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15013 if (type == error_mark_node)
15014 RETURN (error_mark_node);
15015 r = TYPE_NAME (type);
15016 break;
15019 /* Check to see if we already have the specialization we
15020 need. */
15021 tree spec = NULL_TREE;
15022 bool local_p = false;
15023 tree ctx = DECL_CONTEXT (t);
15024 if (!(VAR_P (t) && DECL_LOCAL_DECL_P (t))
15025 && (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t)))
15027 local_p = false;
15028 if (DECL_CLASS_SCOPE_P (t))
15030 ctx = tsubst_aggr_type (ctx, args,
15031 complain,
15032 in_decl, /*entering_scope=*/1);
15033 if (DECL_SELF_REFERENCE_P (t))
15034 /* The context and type of an injected-class-name are
15035 the same, so we don't need to substitute both. */
15036 type = ctx;
15037 /* If CTX is unchanged, then T is in fact the
15038 specialization we want. That situation occurs when
15039 referencing a static data member within in its own
15040 class. We can use pointer equality, rather than
15041 same_type_p, because DECL_CONTEXT is always
15042 canonical... */
15043 if (ctx == DECL_CONTEXT (t)
15044 /* ... unless T is a member template; in which
15045 case our caller can be willing to create a
15046 specialization of that template represented
15047 by T. */
15048 && !(DECL_TI_TEMPLATE (t)
15049 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (t))))
15050 spec = t;
15053 if (!spec)
15055 tmpl = DECL_TI_TEMPLATE (t);
15056 gen_tmpl = most_general_template (tmpl);
15057 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
15058 if (argvec != error_mark_node
15059 && PRIMARY_TEMPLATE_P (gen_tmpl)
15060 && TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (argvec))
15061 /* We're fully specializing a template declaration, so
15062 we need to coerce the innermost arguments corresponding to
15063 the template. */
15064 argvec = (coerce_template_parms
15065 (DECL_TEMPLATE_PARMS (gen_tmpl),
15066 argvec, t, complain));
15067 if (argvec == error_mark_node)
15068 RETURN (error_mark_node);
15069 hash = spec_hasher::hash (gen_tmpl, argvec);
15070 spec = retrieve_specialization (gen_tmpl, argvec, hash);
15073 else
15075 if (!(VAR_P (t) && DECL_LOCAL_DECL_P (t)))
15076 /* Subsequent calls to pushdecl will fill this in. */
15077 ctx = NULL_TREE;
15078 /* A local variable. */
15079 local_p = true;
15080 /* Unless this is a reference to a static variable from an
15081 enclosing function, in which case we need to fill it in now. */
15082 if (TREE_STATIC (t))
15084 tree fn = enclosing_instantiation_of (DECL_CONTEXT (t));
15085 if (fn != current_function_decl)
15086 ctx = fn;
15088 spec = retrieve_local_specialization (t);
15090 /* If we already have the specialization we need, there is
15091 nothing more to do. */
15092 if (spec)
15094 r = spec;
15095 break;
15098 /* Create a new node for the specialization we need. */
15099 if (type == NULL_TREE)
15101 if (is_typedef_decl (t))
15102 type = DECL_ORIGINAL_TYPE (t);
15103 else
15104 type = TREE_TYPE (t);
15105 if (VAR_P (t)
15106 && VAR_HAD_UNKNOWN_BOUND (t)
15107 && type != error_mark_node)
15108 type = strip_array_domain (type);
15109 tsubst_flags_t tcomplain = complain;
15110 if (VAR_P (t))
15111 tcomplain |= tf_tst_ok;
15112 type = tsubst (type, args, tcomplain, in_decl);
15113 /* Substituting the type might have recursively instantiated this
15114 same alias (c++/86171). */
15115 if (gen_tmpl && DECL_ALIAS_TEMPLATE_P (gen_tmpl)
15116 && (spec = retrieve_specialization (gen_tmpl, argvec, hash)))
15118 r = spec;
15119 break;
15122 r = copy_decl (t);
15123 if (VAR_P (r))
15125 DECL_INITIALIZED_P (r) = 0;
15126 DECL_TEMPLATE_INSTANTIATED (r) = 0;
15127 if (type == error_mark_node)
15128 RETURN (error_mark_node);
15129 if (TREE_CODE (type) == FUNCTION_TYPE)
15131 /* It may seem that this case cannot occur, since:
15133 typedef void f();
15134 void g() { f x; }
15136 declares a function, not a variable. However:
15138 typedef void f();
15139 template <typename T> void g() { T t; }
15140 template void g<f>();
15142 is an attempt to declare a variable with function
15143 type. */
15144 error ("variable %qD has function type",
15145 /* R is not yet sufficiently initialized, so we
15146 just use its name. */
15147 DECL_NAME (r));
15148 RETURN (error_mark_node);
15150 type = complete_type (type);
15151 /* Wait until cp_finish_decl to set this again, to handle
15152 circular dependency (template/instantiate6.C). */
15153 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
15154 type = check_var_type (DECL_NAME (r), type,
15155 DECL_SOURCE_LOCATION (r));
15156 if (DECL_HAS_VALUE_EXPR_P (t))
15158 tree ve = DECL_VALUE_EXPR (t);
15159 /* If the DECL_VALUE_EXPR is converted to the declared type,
15160 preserve the identity so that gimplify_type_sizes works. */
15161 bool nop = (TREE_CODE (ve) == NOP_EXPR);
15162 if (nop)
15163 ve = TREE_OPERAND (ve, 0);
15164 ve = tsubst_expr (ve, args, complain, in_decl);
15165 if (REFERENCE_REF_P (ve))
15167 gcc_assert (TYPE_REF_P (type));
15168 ve = TREE_OPERAND (ve, 0);
15170 if (nop)
15171 ve = build_nop (type, ve);
15172 else if (DECL_LANG_SPECIFIC (t)
15173 && DECL_OMP_PRIVATIZED_MEMBER (t)
15174 && TREE_CODE (ve) == COMPONENT_REF
15175 && TREE_CODE (TREE_OPERAND (ve, 1)) == FIELD_DECL
15176 && DECL_BIT_FIELD_TYPE (TREE_OPERAND (ve, 1)) == type)
15177 type = TREE_TYPE (ve);
15178 else
15179 gcc_checking_assert (TYPE_MAIN_VARIANT (TREE_TYPE (ve))
15180 == TYPE_MAIN_VARIANT (type));
15181 SET_DECL_VALUE_EXPR (r, ve);
15183 if (CP_DECL_THREAD_LOCAL_P (r)
15184 && !processing_template_decl)
15185 set_decl_tls_model (r, decl_default_tls_model (r));
15187 else if (DECL_SELF_REFERENCE_P (t))
15188 SET_DECL_SELF_REFERENCE_P (r);
15189 TREE_TYPE (r) = type;
15190 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
15191 DECL_CONTEXT (r) = ctx;
15192 /* Clear out the mangled name and RTL for the instantiation. */
15193 SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
15194 if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
15195 SET_DECL_RTL (r, NULL);
15196 set_instantiating_module (r);
15198 /* The initializer must not be expanded until it is required;
15199 see [temp.inst]. */
15200 DECL_INITIAL (r) = NULL_TREE;
15201 DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
15202 if (VAR_P (r))
15204 if (DECL_LANG_SPECIFIC (r))
15205 SET_DECL_DEPENDENT_INIT_P (r, false);
15207 SET_DECL_MODE (r, VOIDmode);
15209 /* Possibly limit visibility based on template args. */
15210 DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
15211 if (DECL_VISIBILITY_SPECIFIED (t))
15213 DECL_VISIBILITY_SPECIFIED (r) = 0;
15214 DECL_ATTRIBUTES (r)
15215 = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
15217 determine_visibility (r);
15220 if (!local_p)
15222 /* A static data member declaration is always marked
15223 external when it is declared in-class, even if an
15224 initializer is present. We mimic the non-template
15225 processing here. */
15226 DECL_EXTERNAL (r) = 1;
15227 if (DECL_NAMESPACE_SCOPE_P (t))
15228 DECL_NOT_REALLY_EXTERN (r) = 1;
15230 DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
15231 SET_DECL_IMPLICIT_INSTANTIATION (r);
15232 if (!error_operand_p (r) || (complain & tf_error))
15233 register_specialization (r, gen_tmpl, argvec, false, hash);
15235 else
15237 if (DECL_LANG_SPECIFIC (r))
15238 DECL_TEMPLATE_INFO (r) = NULL_TREE;
15239 if (!cp_unevaluated_operand)
15240 register_local_specialization (r, t);
15243 DECL_CHAIN (r) = NULL_TREE;
15245 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
15246 /*flags=*/0,
15247 args, complain, in_decl))
15248 return error_mark_node;
15250 /* Preserve a typedef that names a type. */
15251 if (is_typedef_decl (r) && type != error_mark_node)
15253 DECL_ORIGINAL_TYPE (r) = NULL_TREE;
15254 set_underlying_type (r);
15256 /* common_handle_aligned_attribute doesn't apply the alignment
15257 to DECL_ORIGINAL_TYPE. */
15258 if (TYPE_USER_ALIGN (TREE_TYPE (t)))
15259 TREE_TYPE (r) = build_aligned_type (TREE_TYPE (r),
15260 TYPE_ALIGN (TREE_TYPE (t)));
15263 layout_decl (r, 0);
15265 break;
15267 default:
15268 gcc_unreachable ();
15270 #undef RETURN
15272 out:
15273 /* Restore the file and line information. */
15274 input_location = saved_loc;
15276 return r;
15279 /* Substitute into the complete parameter type list PARMS. */
15281 tree
15282 tsubst_function_parms (tree parms,
15283 tree args,
15284 tsubst_flags_t complain,
15285 tree in_decl)
15287 return tsubst_arg_types (parms, args, NULL_TREE, complain, in_decl);
15290 /* Substitute into the ARG_TYPES of a function type.
15291 If END is a TREE_CHAIN, leave it and any following types
15292 un-substituted. */
15294 static tree
15295 tsubst_arg_types (tree arg_types,
15296 tree args,
15297 tree end,
15298 tsubst_flags_t complain,
15299 tree in_decl)
15301 tree type = NULL_TREE;
15302 int len = 1;
15303 tree expanded_args = NULL_TREE;
15305 if (!arg_types || arg_types == void_list_node || arg_types == end)
15306 return arg_types;
15308 if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
15310 /* For a pack expansion, perform substitution on the
15311 entire expression. Later on, we'll handle the arguments
15312 one-by-one. */
15313 expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
15314 args, complain, in_decl);
15316 if (TREE_CODE (expanded_args) == TREE_VEC)
15317 /* So that we'll spin through the parameters, one by one. */
15318 len = TREE_VEC_LENGTH (expanded_args);
15319 else
15321 /* We only partially substituted into the parameter
15322 pack. Our type is TYPE_PACK_EXPANSION. */
15323 type = expanded_args;
15324 expanded_args = NULL_TREE;
15327 else
15328 type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
15330 /* Check if a substituted type is erroneous before substituting into
15331 the rest of the chain. */
15332 for (int i = 0; i < len; i++)
15334 if (expanded_args)
15335 type = TREE_VEC_ELT (expanded_args, i);
15337 if (type == error_mark_node)
15338 return error_mark_node;
15339 if (VOID_TYPE_P (type))
15341 if (complain & tf_error)
15343 error ("invalid parameter type %qT", type);
15344 if (in_decl)
15345 error ("in declaration %q+D", in_decl);
15347 return error_mark_node;
15351 /* We do not substitute into default arguments here. The standard
15352 mandates that they be instantiated only when needed, which is
15353 done in build_over_call. */
15354 tree default_arg = TREE_PURPOSE (arg_types);
15356 /* Except that we do substitute default arguments under tsubst_lambda_expr,
15357 since the new op() won't have any associated template arguments for us
15358 to refer to later. */
15359 if (lambda_fn_in_template_p (in_decl)
15360 || (in_decl && TREE_CODE (in_decl) == FUNCTION_DECL
15361 && DECL_LOCAL_DECL_P (in_decl)))
15362 default_arg = tsubst_copy_and_build (default_arg, args, complain, in_decl);
15364 tree remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
15365 args, end, complain, in_decl);
15366 if (remaining_arg_types == error_mark_node)
15367 return error_mark_node;
15369 for (int i = len-1; i >= 0; i--)
15371 if (expanded_args)
15372 type = TREE_VEC_ELT (expanded_args, i);
15374 /* Do array-to-pointer, function-to-pointer conversion, and ignore
15375 top-level qualifiers as required. */
15376 type = cv_unqualified (type_decays_to (type));
15378 if (default_arg && TREE_CODE (default_arg) == DEFERRED_PARSE)
15380 /* We've instantiated a template before its default arguments
15381 have been parsed. This can happen for a nested template
15382 class, and is not an error unless we require the default
15383 argument in a call of this function. */
15384 remaining_arg_types
15385 = tree_cons (default_arg, type, remaining_arg_types);
15386 vec_safe_push (DEFPARSE_INSTANTIATIONS (default_arg),
15387 remaining_arg_types);
15389 else
15390 remaining_arg_types
15391 = hash_tree_cons (default_arg, type, remaining_arg_types);
15394 return remaining_arg_types;
15397 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE. This routine does
15398 *not* handle the exception-specification for FNTYPE, because the
15399 initial substitution of explicitly provided template parameters
15400 during argument deduction forbids substitution into the
15401 exception-specification:
15403 [temp.deduct]
15405 All references in the function type of the function template to the
15406 corresponding template parameters are replaced by the specified tem-
15407 plate argument values. If a substitution in a template parameter or
15408 in the function type of the function template results in an invalid
15409 type, type deduction fails. [Note: The equivalent substitution in
15410 exception specifications is done only when the function is instanti-
15411 ated, at which point a program is ill-formed if the substitution
15412 results in an invalid type.] */
15414 static tree
15415 tsubst_function_type (tree t,
15416 tree args,
15417 tsubst_flags_t complain,
15418 tree in_decl)
15420 tree return_type;
15421 tree arg_types = NULL_TREE;
15423 /* The TYPE_CONTEXT is not used for function/method types. */
15424 gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
15426 /* DR 1227: Mixing immediate and non-immediate contexts in deduction
15427 failure. */
15428 bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
15430 if (late_return_type_p)
15432 /* Substitute the argument types. */
15433 arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
15434 complain, in_decl);
15435 if (arg_types == error_mark_node)
15436 return error_mark_node;
15438 tree save_ccp = current_class_ptr;
15439 tree save_ccr = current_class_ref;
15440 tree this_type = (TREE_CODE (t) == METHOD_TYPE
15441 ? TREE_TYPE (TREE_VALUE (arg_types)) : NULL_TREE);
15442 bool do_inject = this_type && CLASS_TYPE_P (this_type);
15443 if (do_inject)
15445 /* DR 1207: 'this' is in scope in the trailing return type. */
15446 inject_this_parameter (this_type, cp_type_quals (this_type));
15449 /* Substitute the return type. */
15450 return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15452 if (do_inject)
15454 current_class_ptr = save_ccp;
15455 current_class_ref = save_ccr;
15458 else
15459 /* Substitute the return type. */
15460 return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15462 if (return_type == error_mark_node)
15463 return error_mark_node;
15464 /* DR 486 clarifies that creation of a function type with an
15465 invalid return type is a deduction failure. */
15466 if (TREE_CODE (return_type) == ARRAY_TYPE
15467 || TREE_CODE (return_type) == FUNCTION_TYPE)
15469 if (complain & tf_error)
15471 if (TREE_CODE (return_type) == ARRAY_TYPE)
15472 error ("function returning an array");
15473 else
15474 error ("function returning a function");
15476 return error_mark_node;
15479 if (!late_return_type_p)
15481 /* Substitute the argument types. */
15482 arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
15483 complain, in_decl);
15484 if (arg_types == error_mark_node)
15485 return error_mark_node;
15488 /* Construct a new type node and return it. */
15489 return rebuild_function_or_method_type (t, return_type, arg_types,
15490 /*raises=*/NULL_TREE, complain);
15493 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE. Substitute the template
15494 ARGS into that specification, and return the substituted
15495 specification. If there is no specification, return NULL_TREE. */
15497 static tree
15498 tsubst_exception_specification (tree fntype,
15499 tree args,
15500 tsubst_flags_t complain,
15501 tree in_decl,
15502 bool defer_ok)
15504 tree specs;
15505 tree new_specs;
15507 specs = TYPE_RAISES_EXCEPTIONS (fntype);
15508 new_specs = NULL_TREE;
15509 if (specs && TREE_PURPOSE (specs))
15511 /* A noexcept-specifier. */
15512 tree expr = TREE_PURPOSE (specs);
15513 if (TREE_CODE (expr) == INTEGER_CST)
15514 new_specs = expr;
15515 else if (defer_ok)
15517 /* Defer instantiation of noexcept-specifiers to avoid
15518 excessive instantiations (c++/49107). */
15519 new_specs = make_node (DEFERRED_NOEXCEPT);
15520 if (DEFERRED_NOEXCEPT_SPEC_P (specs))
15522 /* We already partially instantiated this member template,
15523 so combine the new args with the old. */
15524 DEFERRED_NOEXCEPT_PATTERN (new_specs)
15525 = DEFERRED_NOEXCEPT_PATTERN (expr);
15526 DEFERRED_NOEXCEPT_ARGS (new_specs)
15527 = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
15529 else
15531 DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
15532 DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
15535 else
15537 if (DEFERRED_NOEXCEPT_SPEC_P (specs))
15539 args = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr),
15540 args);
15541 expr = DEFERRED_NOEXCEPT_PATTERN (expr);
15543 new_specs = tsubst_copy_and_build (expr, args, complain, in_decl);
15545 new_specs = build_noexcept_spec (new_specs, complain);
15546 /* We've instantiated a template before a noexcept-specifier
15547 contained therein has been parsed. This can happen for
15548 a nested template class:
15550 struct S {
15551 template<typename> struct B { B() noexcept(...); };
15552 struct A : B<int> { ... use B() ... };
15555 where completing B<int> will trigger instantiating the
15556 noexcept, even though we only parse it at the end of S. */
15557 if (UNPARSED_NOEXCEPT_SPEC_P (specs))
15559 gcc_checking_assert (defer_ok);
15560 vec_safe_push (DEFPARSE_INSTANTIATIONS (expr), new_specs);
15563 else if (specs)
15565 if (! TREE_VALUE (specs))
15566 new_specs = specs;
15567 else
15568 while (specs)
15570 tree spec;
15571 int i, len = 1;
15572 tree expanded_specs = NULL_TREE;
15574 if (PACK_EXPANSION_P (TREE_VALUE (specs)))
15576 /* Expand the pack expansion type. */
15577 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
15578 args, complain,
15579 in_decl);
15581 if (expanded_specs == error_mark_node)
15582 return error_mark_node;
15583 else if (TREE_CODE (expanded_specs) == TREE_VEC)
15584 len = TREE_VEC_LENGTH (expanded_specs);
15585 else
15587 /* We're substituting into a member template, so
15588 we got a TYPE_PACK_EXPANSION back. Add that
15589 expansion and move on. */
15590 gcc_assert (TREE_CODE (expanded_specs)
15591 == TYPE_PACK_EXPANSION);
15592 new_specs = add_exception_specifier (new_specs,
15593 expanded_specs,
15594 complain);
15595 specs = TREE_CHAIN (specs);
15596 continue;
15600 for (i = 0; i < len; ++i)
15602 if (expanded_specs)
15603 spec = TREE_VEC_ELT (expanded_specs, i);
15604 else
15605 spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
15606 if (spec == error_mark_node)
15607 return spec;
15608 new_specs = add_exception_specifier (new_specs, spec,
15609 complain);
15612 specs = TREE_CHAIN (specs);
15615 return new_specs;
15618 /* Substitute through a TREE_LIST of types or expressions, handling pack
15619 expansions. */
15621 tree
15622 tsubst_tree_list (tree t, tree args, tsubst_flags_t complain, tree in_decl)
15624 if (t == void_list_node)
15625 return t;
15627 tree purpose = TREE_PURPOSE (t);
15628 tree purposevec = NULL_TREE;
15629 if (!purpose)
15631 else if (PACK_EXPANSION_P (purpose))
15633 purpose = tsubst_pack_expansion (purpose, args, complain, in_decl);
15634 if (TREE_CODE (purpose) == TREE_VEC)
15635 purposevec = purpose;
15637 else if (TYPE_P (purpose))
15638 purpose = tsubst (purpose, args, complain, in_decl);
15639 else
15640 purpose = tsubst_copy_and_build (purpose, args, complain, in_decl);
15641 if (purpose == error_mark_node || purposevec == error_mark_node)
15642 return error_mark_node;
15644 tree value = TREE_VALUE (t);
15645 tree valuevec = NULL_TREE;
15646 if (!value)
15648 else if (PACK_EXPANSION_P (value))
15650 value = tsubst_pack_expansion (value, args, complain, in_decl);
15651 if (TREE_CODE (value) == TREE_VEC)
15652 valuevec = value;
15654 else if (TYPE_P (value))
15655 value = tsubst (value, args, complain, in_decl);
15656 else
15657 value = tsubst_copy_and_build (value, args, complain, in_decl);
15658 if (value == error_mark_node || valuevec == error_mark_node)
15659 return error_mark_node;
15661 tree chain = TREE_CHAIN (t);
15662 if (!chain)
15664 else if (TREE_CODE (chain) == TREE_LIST)
15665 chain = tsubst_tree_list (chain, args, complain, in_decl);
15666 else if (TYPE_P (chain))
15667 chain = tsubst (chain, args, complain, in_decl);
15668 else
15669 chain = tsubst_copy_and_build (chain, args, complain, in_decl);
15670 if (chain == error_mark_node)
15671 return error_mark_node;
15673 if (purpose == TREE_PURPOSE (t)
15674 && value == TREE_VALUE (t)
15675 && chain == TREE_CHAIN (t))
15676 return t;
15678 int len;
15679 /* Determine the number of arguments. */
15680 if (purposevec)
15682 len = TREE_VEC_LENGTH (purposevec);
15683 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
15685 else if (valuevec)
15686 len = TREE_VEC_LENGTH (valuevec);
15687 else
15688 len = 1;
15690 for (int i = len; i-- > 0; )
15692 if (purposevec)
15693 purpose = TREE_VEC_ELT (purposevec, i);
15694 if (valuevec)
15695 value = TREE_VEC_ELT (valuevec, i);
15697 if (value && TYPE_P (value))
15698 chain = hash_tree_cons (purpose, value, chain);
15699 else
15700 chain = tree_cons (purpose, value, chain);
15703 return chain;
15706 /* Take the tree structure T and replace template parameters used
15707 therein with the argument vector ARGS. IN_DECL is an associated
15708 decl for diagnostics. If an error occurs, returns ERROR_MARK_NODE.
15709 Issue error and warning messages under control of COMPLAIN. Note
15710 that we must be relatively non-tolerant of extensions here, in
15711 order to preserve conformance; if we allow substitutions that
15712 should not be allowed, we may allow argument deductions that should
15713 not succeed, and therefore report ambiguous overload situations
15714 where there are none. In theory, we could allow the substitution,
15715 but indicate that it should have failed, and allow our caller to
15716 make sure that the right thing happens, but we don't try to do this
15717 yet.
15719 This function is used for dealing with types, decls and the like;
15720 for expressions, use tsubst_expr or tsubst_copy. */
15722 tree
15723 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
15725 enum tree_code code;
15726 tree type, r = NULL_TREE;
15728 if (t == NULL_TREE || t == error_mark_node
15729 || t == integer_type_node
15730 || t == void_type_node
15731 || t == char_type_node
15732 || t == unknown_type_node
15733 || TREE_CODE (t) == NAMESPACE_DECL
15734 || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
15735 return t;
15737 if (DECL_P (t))
15738 return tsubst_decl (t, args, complain);
15740 if (args == NULL_TREE)
15741 return t;
15743 code = TREE_CODE (t);
15745 gcc_assert (code != IDENTIFIER_NODE);
15746 type = TREE_TYPE (t);
15748 gcc_assert (type != unknown_type_node);
15750 if (tree d = maybe_dependent_member_ref (t, args, complain, in_decl))
15751 return d;
15753 /* Reuse typedefs. We need to do this to handle dependent attributes,
15754 such as attribute aligned. */
15755 if (TYPE_P (t)
15756 && typedef_variant_p (t))
15758 tree decl = TYPE_NAME (t);
15760 if (alias_template_specialization_p (t, nt_opaque))
15762 /* DECL represents an alias template and we want to
15763 instantiate it. */
15764 tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15765 tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
15766 r = instantiate_alias_template (tmpl, gen_args, complain);
15768 else if (DECL_CLASS_SCOPE_P (decl)
15769 && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
15770 && uses_template_parms (DECL_CONTEXT (decl)))
15772 tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15773 tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
15774 r = retrieve_specialization (tmpl, gen_args, 0);
15776 else if (DECL_FUNCTION_SCOPE_P (decl)
15777 && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
15778 && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
15779 r = retrieve_local_specialization (decl);
15780 else
15781 /* The typedef is from a non-template context. */
15782 return t;
15784 if (r)
15786 r = TREE_TYPE (r);
15787 r = cp_build_qualified_type
15788 (r, cp_type_quals (t) | cp_type_quals (r),
15789 complain | tf_ignore_bad_quals);
15790 return r;
15792 else
15794 /* We don't have an instantiation yet, so drop the typedef. */
15795 int quals = cp_type_quals (t);
15796 t = DECL_ORIGINAL_TYPE (decl);
15797 t = cp_build_qualified_type (t, quals,
15798 complain | tf_ignore_bad_quals);
15802 bool fndecl_type = (complain & tf_fndecl_type);
15803 complain &= ~tf_fndecl_type;
15805 bool tst_ok = (complain & tf_tst_ok);
15806 complain &= ~tf_tst_ok;
15808 if (type
15809 && code != TYPENAME_TYPE
15810 && code != TEMPLATE_TYPE_PARM
15811 && code != TEMPLATE_PARM_INDEX
15812 && code != IDENTIFIER_NODE
15813 && code != FUNCTION_TYPE
15814 && code != METHOD_TYPE)
15815 type = tsubst (type, args, complain, in_decl);
15816 if (type == error_mark_node)
15817 return error_mark_node;
15819 switch (code)
15821 case RECORD_TYPE:
15822 if (TYPE_PTRMEMFUNC_P (t))
15823 return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
15824 /* Fall through. */
15825 case UNION_TYPE:
15826 case ENUMERAL_TYPE:
15827 return tsubst_aggr_type_1 (t, args, complain, in_decl,
15828 /*entering_scope=*/0);
15830 case ERROR_MARK:
15831 case IDENTIFIER_NODE:
15832 case VOID_TYPE:
15833 case OPAQUE_TYPE:
15834 case REAL_TYPE:
15835 case COMPLEX_TYPE:
15836 case VECTOR_TYPE:
15837 case BOOLEAN_TYPE:
15838 case NULLPTR_TYPE:
15839 case LANG_TYPE:
15840 return t;
15842 case INTEGER_TYPE:
15843 if (t == integer_type_node)
15844 return t;
15846 if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
15847 && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
15848 return t;
15851 tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
15853 max = tsubst_expr (omax, args, complain, in_decl);
15855 /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
15856 needed. */
15857 if (TREE_CODE (max) == NOP_EXPR
15858 && TREE_SIDE_EFFECTS (omax)
15859 && !TREE_TYPE (max))
15860 TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
15862 /* If we're in a partial instantiation, preserve the magic NOP_EXPR
15863 with TREE_SIDE_EFFECTS that indicates this is not an integral
15864 constant expression. */
15865 if (processing_template_decl
15866 && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
15868 gcc_assert (TREE_CODE (max) == NOP_EXPR);
15869 TREE_SIDE_EFFECTS (max) = 1;
15872 return compute_array_index_type (NULL_TREE, max, complain);
15875 case TEMPLATE_TYPE_PARM:
15876 if (template_placeholder_p (t))
15878 tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (t);
15879 tmpl = tsubst_copy (tmpl, args, complain, in_decl);
15880 if (TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
15881 tmpl = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (tmpl);
15883 if (tmpl != CLASS_PLACEHOLDER_TEMPLATE (t))
15884 return make_template_placeholder (tmpl);
15885 else
15886 return t;
15888 /* Fall through. */
15889 case TEMPLATE_TEMPLATE_PARM:
15890 case BOUND_TEMPLATE_TEMPLATE_PARM:
15891 case TEMPLATE_PARM_INDEX:
15893 int idx;
15894 int level;
15895 int levels;
15896 tree arg = NULL_TREE;
15898 r = NULL_TREE;
15900 gcc_assert (TREE_VEC_LENGTH (args) > 0);
15901 template_parm_level_and_index (t, &level, &idx);
15903 levels = TMPL_ARGS_DEPTH (args);
15904 if (level <= levels
15905 && TREE_VEC_LENGTH (TMPL_ARGS_LEVEL (args, level)) > 0)
15907 arg = TMPL_ARG (args, level, idx);
15909 /* See through ARGUMENT_PACK_SELECT arguments. */
15910 if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
15911 arg = argument_pack_select_arg (arg);
15914 if (arg == error_mark_node)
15915 return error_mark_node;
15916 else if (arg != NULL_TREE)
15918 if (ARGUMENT_PACK_P (arg))
15919 /* If ARG is an argument pack, we don't actually want to
15920 perform a substitution here, because substitutions
15921 for argument packs are only done
15922 element-by-element. We can get to this point when
15923 substituting the type of a non-type template
15924 parameter pack, when that type actually contains
15925 template parameter packs from an outer template, e.g.,
15927 template<typename... Types> struct A {
15928 template<Types... Values> struct B { };
15929 }; */
15930 return t;
15932 if (code == TEMPLATE_TYPE_PARM)
15934 int quals;
15936 /* When building concept checks for the purpose of
15937 deducing placeholders, we can end up with wildcards
15938 where types are expected. Adjust this to the deduced
15939 value. */
15940 if (TREE_CODE (arg) == WILDCARD_DECL)
15941 arg = TREE_TYPE (TREE_TYPE (arg));
15943 gcc_assert (TYPE_P (arg));
15945 quals = cp_type_quals (arg) | cp_type_quals (t);
15947 return cp_build_qualified_type
15948 (arg, quals, complain | tf_ignore_bad_quals);
15950 else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
15952 /* We are processing a type constructed from a
15953 template template parameter. */
15954 tree argvec = tsubst (TYPE_TI_ARGS (t),
15955 args, complain, in_decl);
15956 if (argvec == error_mark_node)
15957 return error_mark_node;
15959 gcc_assert (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
15960 || TREE_CODE (arg) == TEMPLATE_DECL
15961 || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
15963 if (TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
15964 /* Consider this code:
15966 template <template <class> class Template>
15967 struct Internal {
15968 template <class Arg> using Bind = Template<Arg>;
15971 template <template <class> class Template, class Arg>
15972 using Instantiate = Template<Arg>; //#0
15974 template <template <class> class Template,
15975 class Argument>
15976 using Bind =
15977 Instantiate<Internal<Template>::template Bind,
15978 Argument>; //#1
15980 When #1 is parsed, the
15981 BOUND_TEMPLATE_TEMPLATE_PARM representing the
15982 parameter `Template' in #0 matches the
15983 UNBOUND_CLASS_TEMPLATE representing the argument
15984 `Internal<Template>::template Bind'; We then want
15985 to assemble the type `Bind<Argument>' that can't
15986 be fully created right now, because
15987 `Internal<Template>' not being complete, the Bind
15988 template cannot be looked up in that context. So
15989 we need to "store" `Bind<Argument>' for later
15990 when the context of Bind becomes complete. Let's
15991 store that in a TYPENAME_TYPE. */
15992 return make_typename_type (TYPE_CONTEXT (arg),
15993 build_nt (TEMPLATE_ID_EXPR,
15994 TYPE_IDENTIFIER (arg),
15995 argvec),
15996 typename_type,
15997 complain);
15999 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
16000 are resolving nested-types in the signature of a
16001 member function templates. Otherwise ARG is a
16002 TEMPLATE_DECL and is the real template to be
16003 instantiated. */
16004 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
16005 arg = TYPE_NAME (arg);
16007 r = lookup_template_class (arg,
16008 argvec, in_decl,
16009 DECL_CONTEXT (arg),
16010 /*entering_scope=*/0,
16011 complain);
16012 return cp_build_qualified_type
16013 (r, cp_type_quals (t) | cp_type_quals (r), complain);
16015 else if (code == TEMPLATE_TEMPLATE_PARM)
16016 return arg;
16017 else
16018 /* TEMPLATE_PARM_INDEX. */
16019 return convert_from_reference (unshare_expr (arg));
16022 if (level == 1)
16023 /* This can happen during the attempted tsubst'ing in
16024 unify. This means that we don't yet have any information
16025 about the template parameter in question. */
16026 return t;
16028 /* Early in template argument deduction substitution, we don't
16029 want to reduce the level of 'auto', or it will be confused
16030 with a normal template parm in subsequent deduction.
16031 Similarly, don't reduce the level of template parameters to
16032 avoid mismatches when deducing their types. */
16033 if (complain & tf_partial)
16034 return t;
16036 /* If we get here, we must have been looking at a parm for a
16037 more deeply nested template. Make a new version of this
16038 template parameter, but with a lower level. */
16039 switch (code)
16041 case TEMPLATE_TYPE_PARM:
16042 case TEMPLATE_TEMPLATE_PARM:
16043 case BOUND_TEMPLATE_TEMPLATE_PARM:
16044 if (cp_type_quals (t))
16046 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
16047 r = cp_build_qualified_type
16048 (r, cp_type_quals (t),
16049 complain | (code == TEMPLATE_TYPE_PARM
16050 ? tf_ignore_bad_quals : 0));
16052 else if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
16053 && PLACEHOLDER_TYPE_CONSTRAINTS_INFO (t)
16054 && (r = (TEMPLATE_PARM_DESCENDANTS
16055 (TEMPLATE_TYPE_PARM_INDEX (t))))
16056 && (r = TREE_TYPE (r))
16057 && !PLACEHOLDER_TYPE_CONSTRAINTS_INFO (r))
16058 /* Break infinite recursion when substituting the constraints
16059 of a constrained placeholder. */;
16060 else if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
16061 && !PLACEHOLDER_TYPE_CONSTRAINTS_INFO (t)
16062 && (arg = TEMPLATE_TYPE_PARM_INDEX (t),
16063 r = TEMPLATE_PARM_DESCENDANTS (arg))
16064 && (TEMPLATE_PARM_LEVEL (r)
16065 == TEMPLATE_PARM_LEVEL (arg) - levels))
16066 /* Cache the simple case of lowering a type parameter. */
16067 r = TREE_TYPE (r);
16068 else
16070 r = copy_type (t);
16071 TEMPLATE_TYPE_PARM_INDEX (r)
16072 = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
16073 r, levels, args, complain);
16074 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
16075 TYPE_MAIN_VARIANT (r) = r;
16076 TYPE_POINTER_TO (r) = NULL_TREE;
16077 TYPE_REFERENCE_TO (r) = NULL_TREE;
16079 if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
16080 if (tree ci = PLACEHOLDER_TYPE_CONSTRAINTS_INFO (t))
16081 /* Propagate constraints on placeholders since they are
16082 only instantiated during satisfaction. */
16083 PLACEHOLDER_TYPE_CONSTRAINTS_INFO (r) = ci;
16085 if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
16087 tree tinfo = TYPE_TEMPLATE_INFO (t);
16088 /* We might need to substitute into the types of non-type
16089 template parameters. */
16090 tree tmpl = tsubst (TI_TEMPLATE (tinfo), args,
16091 complain, in_decl);
16092 if (tmpl == error_mark_node)
16093 return error_mark_node;
16094 tree argvec = tsubst (TI_ARGS (tinfo), args,
16095 complain, in_decl);
16096 if (argvec == error_mark_node)
16097 return error_mark_node;
16099 TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
16100 = build_template_info (tmpl, argvec);
16103 if (TYPE_STRUCTURAL_EQUALITY_P (t))
16104 SET_TYPE_STRUCTURAL_EQUALITY (r);
16105 else
16106 TYPE_CANONICAL (r) = canonical_type_parameter (r);
16108 break;
16110 case TEMPLATE_PARM_INDEX:
16111 /* OK, now substitute the type of the non-type parameter. We
16112 couldn't do it earlier because it might be an auto parameter,
16113 and we wouldn't need to if we had an argument. */
16114 type = tsubst (type, args, complain, in_decl);
16115 if (type == error_mark_node)
16116 return error_mark_node;
16117 r = reduce_template_parm_level (t, type, levels, args, complain);
16118 break;
16120 default:
16121 gcc_unreachable ();
16124 return r;
16127 case TREE_LIST:
16128 return tsubst_tree_list (t, args, complain, in_decl);
16130 case TREE_BINFO:
16131 /* We should never be tsubsting a binfo. */
16132 gcc_unreachable ();
16134 case TREE_VEC:
16135 /* A vector of template arguments. */
16136 gcc_assert (!type);
16137 return tsubst_template_args (t, args, complain, in_decl);
16139 case POINTER_TYPE:
16140 case REFERENCE_TYPE:
16142 if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
16143 return t;
16145 /* [temp.deduct]
16147 Type deduction may fail for any of the following
16148 reasons:
16150 -- Attempting to create a pointer to reference type.
16151 -- Attempting to create a reference to a reference type or
16152 a reference to void.
16154 Core issue 106 says that creating a reference to a reference
16155 during instantiation is no longer a cause for failure. We
16156 only enforce this check in strict C++98 mode. */
16157 if ((TYPE_REF_P (type)
16158 && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
16159 || (code == REFERENCE_TYPE && VOID_TYPE_P (type)))
16161 static location_t last_loc;
16163 /* We keep track of the last time we issued this error
16164 message to avoid spewing a ton of messages during a
16165 single bad template instantiation. */
16166 if (complain & tf_error
16167 && last_loc != input_location)
16169 if (VOID_TYPE_P (type))
16170 error ("forming reference to void");
16171 else if (code == POINTER_TYPE)
16172 error ("forming pointer to reference type %qT", type);
16173 else
16174 error ("forming reference to reference type %qT", type);
16175 last_loc = input_location;
16178 return error_mark_node;
16180 else if (TREE_CODE (type) == FUNCTION_TYPE
16181 && (type_memfn_quals (type) != TYPE_UNQUALIFIED
16182 || type_memfn_rqual (type) != REF_QUAL_NONE))
16184 if (complain & tf_error)
16186 if (code == POINTER_TYPE)
16187 error ("forming pointer to qualified function type %qT",
16188 type);
16189 else
16190 error ("forming reference to qualified function type %qT",
16191 type);
16193 return error_mark_node;
16195 else if (code == POINTER_TYPE)
16197 r = build_pointer_type (type);
16198 if (TREE_CODE (type) == METHOD_TYPE)
16199 r = build_ptrmemfunc_type (r);
16201 else if (TYPE_REF_P (type))
16202 /* In C++0x, during template argument substitution, when there is an
16203 attempt to create a reference to a reference type, reference
16204 collapsing is applied as described in [14.3.1/4 temp.arg.type]:
16206 "If a template-argument for a template-parameter T names a type
16207 that is a reference to a type A, an attempt to create the type
16208 'lvalue reference to cv T' creates the type 'lvalue reference to
16209 A,' while an attempt to create the type type rvalue reference to
16210 cv T' creates the type T"
16212 r = cp_build_reference_type
16213 (TREE_TYPE (type),
16214 TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
16215 else
16216 r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
16217 r = cp_build_qualified_type (r, cp_type_quals (t), complain);
16219 if (r != error_mark_node)
16220 /* Will this ever be needed for TYPE_..._TO values? */
16221 layout_type (r);
16223 return r;
16225 case OFFSET_TYPE:
16227 r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
16228 if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
16230 /* [temp.deduct]
16232 Type deduction may fail for any of the following
16233 reasons:
16235 -- Attempting to create "pointer to member of T" when T
16236 is not a class type. */
16237 if (complain & tf_error)
16238 error ("creating pointer to member of non-class type %qT", r);
16239 return error_mark_node;
16241 if (TYPE_REF_P (type))
16243 if (complain & tf_error)
16244 error ("creating pointer to member reference type %qT", type);
16245 return error_mark_node;
16247 if (VOID_TYPE_P (type))
16249 if (complain & tf_error)
16250 error ("creating pointer to member of type void");
16251 return error_mark_node;
16253 gcc_assert (TREE_CODE (type) != METHOD_TYPE);
16254 if (TREE_CODE (type) == FUNCTION_TYPE)
16256 /* The type of the implicit object parameter gets its
16257 cv-qualifiers from the FUNCTION_TYPE. */
16258 tree memptr;
16259 tree method_type
16260 = build_memfn_type (type, r, type_memfn_quals (type),
16261 type_memfn_rqual (type));
16262 memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
16263 return cp_build_qualified_type (memptr, cp_type_quals (t),
16264 complain);
16266 else
16267 return cp_build_qualified_type (build_ptrmem_type (r, type),
16268 cp_type_quals (t),
16269 complain);
16271 case FUNCTION_TYPE:
16272 case METHOD_TYPE:
16274 tree fntype;
16275 tree specs;
16276 fntype = tsubst_function_type (t, args, complain, in_decl);
16277 if (fntype == error_mark_node)
16278 return error_mark_node;
16280 /* Substitute the exception specification. */
16281 specs = tsubst_exception_specification (t, args, complain, in_decl,
16282 /*defer_ok*/fndecl_type);
16283 if (specs == error_mark_node)
16284 return error_mark_node;
16285 if (specs)
16286 fntype = build_exception_variant (fntype, specs);
16287 return fntype;
16289 case ARRAY_TYPE:
16291 tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
16292 if (domain == error_mark_node)
16293 return error_mark_node;
16295 /* As an optimization, we avoid regenerating the array type if
16296 it will obviously be the same as T. */
16297 if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
16298 return t;
16300 /* These checks should match the ones in create_array_type_for_decl.
16302 [temp.deduct]
16304 The deduction may fail for any of the following reasons:
16306 -- Attempting to create an array with an element type that
16307 is void, a function type, or a reference type, or [DR337]
16308 an abstract class type. */
16309 if (VOID_TYPE_P (type)
16310 || TREE_CODE (type) == FUNCTION_TYPE
16311 || (TREE_CODE (type) == ARRAY_TYPE
16312 && TYPE_DOMAIN (type) == NULL_TREE)
16313 || TYPE_REF_P (type))
16315 if (complain & tf_error)
16316 error ("creating array of %qT", type);
16317 return error_mark_node;
16320 if (!verify_type_context (input_location, TCTX_ARRAY_ELEMENT, type,
16321 !(complain & tf_error)))
16322 return error_mark_node;
16324 r = build_cplus_array_type (type, domain);
16326 if (!valid_array_size_p (input_location, r, in_decl,
16327 (complain & tf_error)))
16328 return error_mark_node;
16330 if (TYPE_USER_ALIGN (t))
16332 SET_TYPE_ALIGN (r, TYPE_ALIGN (t));
16333 TYPE_USER_ALIGN (r) = 1;
16336 return r;
16339 case TYPENAME_TYPE:
16341 tree ctx = TYPE_CONTEXT (t);
16342 if (TREE_CODE (ctx) == TYPE_PACK_EXPANSION)
16344 ctx = tsubst_pack_expansion (ctx, args, complain, in_decl);
16345 if (ctx == error_mark_node
16346 || TREE_VEC_LENGTH (ctx) > 1)
16347 return error_mark_node;
16348 if (TREE_VEC_LENGTH (ctx) == 0)
16350 if (complain & tf_error)
16351 error ("%qD is instantiated for an empty pack",
16352 TYPENAME_TYPE_FULLNAME (t));
16353 return error_mark_node;
16355 ctx = TREE_VEC_ELT (ctx, 0);
16357 else
16358 ctx = tsubst_aggr_type (ctx, args, complain, in_decl,
16359 /*entering_scope=*/1);
16360 if (ctx == error_mark_node)
16361 return error_mark_node;
16363 tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
16364 complain, in_decl);
16365 if (f == error_mark_node)
16366 return error_mark_node;
16368 if (!MAYBE_CLASS_TYPE_P (ctx))
16370 if (complain & tf_error)
16371 error ("%qT is not a class, struct, or union type", ctx);
16372 return error_mark_node;
16374 else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
16376 /* Normally, make_typename_type does not require that the CTX
16377 have complete type in order to allow things like:
16379 template <class T> struct S { typename S<T>::X Y; };
16381 But, such constructs have already been resolved by this
16382 point, so here CTX really should have complete type, unless
16383 it's a partial instantiation. */
16384 if (!complete_type_or_maybe_complain (ctx, NULL_TREE, complain))
16385 return error_mark_node;
16388 tsubst_flags_t tcomplain = complain | tf_keep_type_decl;
16389 if (tst_ok)
16390 tcomplain |= tf_tst_ok;
16391 f = make_typename_type (ctx, f, typename_type, tcomplain);
16392 if (f == error_mark_node)
16393 return f;
16394 if (TREE_CODE (f) == TYPE_DECL)
16396 complain |= tf_ignore_bad_quals;
16397 f = TREE_TYPE (f);
16400 if (TREE_CODE (f) != TYPENAME_TYPE)
16402 if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
16404 if (complain & tf_error)
16405 error ("%qT resolves to %qT, which is not an enumeration type",
16406 t, f);
16407 else
16408 return error_mark_node;
16410 else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
16412 if (complain & tf_error)
16413 error ("%qT resolves to %qT, which is not a class type",
16414 t, f);
16415 else
16416 return error_mark_node;
16420 return cp_build_qualified_type
16421 (f, cp_type_quals (f) | cp_type_quals (t), complain);
16424 case UNBOUND_CLASS_TEMPLATE:
16426 tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
16427 in_decl, /*entering_scope=*/1);
16428 tree name = TYPE_IDENTIFIER (t);
16429 tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
16431 if (ctx == error_mark_node || name == error_mark_node)
16432 return error_mark_node;
16434 if (parm_list)
16435 parm_list = tsubst_template_parms (parm_list, args, complain);
16436 return make_unbound_class_template (ctx, name, parm_list, complain);
16439 case TYPEOF_TYPE:
16441 tree type;
16443 ++cp_unevaluated_operand;
16444 ++c_inhibit_evaluation_warnings;
16446 type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args, complain, in_decl);
16448 --cp_unevaluated_operand;
16449 --c_inhibit_evaluation_warnings;
16451 type = finish_typeof (type);
16452 return cp_build_qualified_type (type,
16453 cp_type_quals (t)
16454 | cp_type_quals (type),
16455 complain);
16458 case DECLTYPE_TYPE:
16460 tree type;
16462 ++cp_unevaluated_operand;
16463 ++c_inhibit_evaluation_warnings;
16465 type = tsubst_copy_and_build (DECLTYPE_TYPE_EXPR (t), args,
16466 complain|tf_decltype, in_decl);
16468 --cp_unevaluated_operand;
16469 --c_inhibit_evaluation_warnings;
16471 if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
16472 type = lambda_capture_field_type (type,
16473 false /*explicit_init*/,
16474 DECLTYPE_FOR_REF_CAPTURE (t));
16475 else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
16476 type = lambda_proxy_type (type);
16477 else
16479 bool id = DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t);
16480 if (id && TREE_CODE (DECLTYPE_TYPE_EXPR (t)) == BIT_NOT_EXPR
16481 && EXPR_P (type))
16482 /* In a template ~id could be either a complement expression
16483 or an unqualified-id naming a destructor; if instantiating
16484 it produces an expression, it's not an id-expression or
16485 member access. */
16486 id = false;
16487 type = finish_decltype_type (type, id, complain);
16489 return cp_build_qualified_type (type,
16490 cp_type_quals (t)
16491 | cp_type_quals (type),
16492 complain | tf_ignore_bad_quals);
16495 case TRAIT_TYPE:
16497 tree type1 = tsubst (TRAIT_TYPE_TYPE1 (t), args, complain, in_decl);
16498 tree type2 = tsubst (TRAIT_TYPE_TYPE2 (t), args, complain, in_decl);
16499 type = finish_trait_type (TRAIT_TYPE_KIND (t), type1, type2);
16500 return cp_build_qualified_type (type,
16501 cp_type_quals (t) | cp_type_quals (type),
16502 complain | tf_ignore_bad_quals);
16505 case TYPE_ARGUMENT_PACK:
16506 case NONTYPE_ARGUMENT_PACK:
16507 return tsubst_argument_pack (t, args, complain, in_decl);
16509 case VOID_CST:
16510 case INTEGER_CST:
16511 case REAL_CST:
16512 case STRING_CST:
16513 case PLUS_EXPR:
16514 case MINUS_EXPR:
16515 case NEGATE_EXPR:
16516 case NOP_EXPR:
16517 case INDIRECT_REF:
16518 case ADDR_EXPR:
16519 case CALL_EXPR:
16520 case ARRAY_REF:
16521 case SCOPE_REF:
16522 /* We should use one of the expression tsubsts for these codes. */
16523 gcc_unreachable ();
16525 default:
16526 sorry ("use of %qs in template", get_tree_code_name (code));
16527 return error_mark_node;
16531 /* OLDFNS is a lookup set of member functions from some class template, and
16532 NEWFNS is a lookup set of member functions from NEWTYPE, a specialization
16533 of that class template. Return the subset of NEWFNS which are
16534 specializations of a function from OLDFNS. */
16536 static tree
16537 filter_memfn_lookup (tree oldfns, tree newfns, tree newtype)
16539 /* Record all member functions from the old lookup set OLDFNS into
16540 VISIBLE_SET. */
16541 hash_set<tree> visible_set;
16542 bool seen_dep_using = false;
16543 for (tree fn : lkp_range (oldfns))
16545 if (TREE_CODE (fn) == USING_DECL)
16547 /* Imprecisely handle dependent using-decl by keeping all members
16548 in the new lookup set that are defined in a base class, i.e.
16549 members that could plausibly have been introduced by this
16550 dependent using-decl.
16551 FIXME: Track which members are introduced by a dependent
16552 using-decl precisely, perhaps by performing another lookup
16553 from the substituted USING_DECL_SCOPE. */
16554 gcc_checking_assert (DECL_DEPENDENT_P (fn));
16555 seen_dep_using = true;
16557 else
16558 visible_set.add (fn);
16561 /* Returns true iff (a less specialized version of) FN appeared in
16562 the old lookup set OLDFNS. */
16563 auto visible_p = [newtype, seen_dep_using, &visible_set] (tree fn) {
16564 if (DECL_CONTEXT (fn) != newtype)
16565 /* FN is a member function from a base class, introduced via a
16566 using-decl; if it might have been introduced by a dependent
16567 using-decl then just conservatively keep it, otherwise look
16568 in the old lookup set for FN exactly. */
16569 return seen_dep_using || visible_set.contains (fn);
16570 else if (TREE_CODE (fn) == TEMPLATE_DECL)
16571 /* FN is a member function template from the current class;
16572 look in the old lookup set for the TEMPLATE_DECL from which
16573 it was specialized. */
16574 return visible_set.contains (DECL_TI_TEMPLATE (fn));
16575 else
16576 /* FN is a non-template member function from the current class;
16577 look in the old lookup set for the FUNCTION_DECL from which
16578 it was specialized. */
16579 return visible_set.contains (DECL_TEMPLATE_RESULT
16580 (DECL_TI_TEMPLATE (fn)));
16583 bool lookup_changed_p = false;
16584 for (tree fn : lkp_range (newfns))
16585 if (!visible_p (fn))
16587 lookup_changed_p = true;
16588 break;
16590 if (!lookup_changed_p)
16591 return newfns;
16593 /* Filter out from NEWFNS the member functions that weren't
16594 previously visible according to OLDFNS. */
16595 tree filtered_fns = NULL_TREE;
16596 unsigned filtered_size = 0;
16597 for (tree fn : lkp_range (newfns))
16598 if (visible_p (fn))
16600 filtered_fns = lookup_add (fn, filtered_fns);
16601 filtered_size++;
16603 gcc_checking_assert (seen_dep_using
16604 ? filtered_size >= visible_set.elements ()
16605 : filtered_size == visible_set.elements ());
16607 return filtered_fns;
16610 /* tsubst a BASELINK. OBJECT_TYPE, if non-NULL, is the type of the
16611 expression on the left-hand side of the "." or "->" operator. We
16612 only do the lookup if we had a dependent BASELINK. Otherwise we
16613 adjust it onto the instantiated heirarchy. */
16615 static tree
16616 tsubst_baselink (tree baselink, tree object_type,
16617 tree args, tsubst_flags_t complain, tree in_decl)
16619 bool qualified_p = BASELINK_QUALIFIED_P (baselink);
16620 tree qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
16621 qualifying_scope = tsubst (qualifying_scope, args, complain, in_decl);
16623 tree optype = BASELINK_OPTYPE (baselink);
16624 optype = tsubst (optype, args, complain, in_decl);
16626 tree template_args = NULL_TREE;
16627 bool template_id_p = false;
16628 tree fns = BASELINK_FUNCTIONS (baselink);
16629 if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
16631 template_id_p = true;
16632 template_args = TREE_OPERAND (fns, 1);
16633 fns = TREE_OPERAND (fns, 0);
16634 if (template_args)
16635 template_args = tsubst_template_args (template_args, args,
16636 complain, in_decl);
16639 tree binfo_type = BINFO_TYPE (BASELINK_BINFO (baselink));
16640 binfo_type = tsubst (binfo_type, args, complain, in_decl);
16641 bool dependent_p = (binfo_type != BINFO_TYPE (BASELINK_BINFO (baselink))
16642 || optype != BASELINK_OPTYPE (baselink));
16644 if (dependent_p)
16646 tree name = OVL_NAME (fns);
16647 if (IDENTIFIER_CONV_OP_P (name))
16648 name = make_conv_op_name (optype);
16650 /* See maybe_dependent_member_ref. */
16651 if ((complain & tf_dguide) && dependent_scope_p (qualifying_scope))
16653 if (template_id_p)
16654 name = build2 (TEMPLATE_ID_EXPR, unknown_type_node, name,
16655 template_args);
16656 return build_qualified_name (NULL_TREE, qualifying_scope, name,
16657 /* ::template */false);
16660 if (name == complete_dtor_identifier)
16661 /* Treat as-if non-dependent below. */
16662 dependent_p = false;
16664 bool maybe_incomplete = BASELINK_FUNCTIONS_MAYBE_INCOMPLETE_P (baselink);
16665 baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1,
16666 complain);
16667 if (maybe_incomplete)
16669 /* Filter out from the new lookup set those functions which didn't
16670 appear in the original lookup set (in a less specialized form).
16671 This is needed to preserve the consistency of member lookup
16672 performed in an incomplete-class context, within which
16673 later-declared members ought to remain invisible. */
16674 BASELINK_FUNCTIONS (baselink)
16675 = filter_memfn_lookup (fns, BASELINK_FUNCTIONS (baselink),
16676 binfo_type);
16677 BASELINK_FUNCTIONS_MAYBE_INCOMPLETE_P (baselink) = true;
16680 if (!baselink)
16682 if ((complain & tf_error)
16683 && constructor_name_p (name, qualifying_scope))
16684 error ("cannot call constructor %<%T::%D%> directly",
16685 qualifying_scope, name);
16686 return error_mark_node;
16689 fns = BASELINK_FUNCTIONS (baselink);
16691 else
16693 /* We're going to overwrite pieces below, make a duplicate. */
16694 baselink = copy_node (baselink);
16696 if (qualifying_scope != BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink)))
16698 /* The decl we found was from non-dependent scope, but we still need
16699 to update the binfos for the instantiated qualifying_scope. */
16700 BASELINK_ACCESS_BINFO (baselink) = TYPE_BINFO (qualifying_scope);
16701 BASELINK_BINFO (baselink) = lookup_base (qualifying_scope, binfo_type,
16702 ba_unique, nullptr, complain);
16706 /* If lookup found a single function, mark it as used at this point.
16707 (If lookup found multiple functions the one selected later by
16708 overload resolution will be marked as used at that point.) */
16709 if (!template_id_p && !really_overloaded_fn (fns))
16711 tree fn = OVL_FIRST (fns);
16712 bool ok = mark_used (fn, complain);
16713 if (!ok && !(complain & tf_error))
16714 return error_mark_node;
16715 if (ok && BASELINK_P (baselink))
16716 /* We might have instantiated an auto function. */
16717 TREE_TYPE (baselink) = TREE_TYPE (fn);
16720 if (BASELINK_P (baselink))
16722 /* Add back the template arguments, if present. */
16723 if (template_id_p)
16724 BASELINK_FUNCTIONS (baselink)
16725 = build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, template_args);
16727 /* Update the conversion operator type. */
16728 BASELINK_OPTYPE (baselink) = optype;
16731 if (!object_type)
16732 object_type = current_class_type;
16734 if (qualified_p || !dependent_p)
16736 baselink = adjust_result_of_qualified_name_lookup (baselink,
16737 qualifying_scope,
16738 object_type);
16739 if (!qualified_p)
16740 /* We need to call adjust_result_of_qualified_name_lookup in case the
16741 destructor names a base class, but we unset BASELINK_QUALIFIED_P
16742 so that we still get virtual function binding. */
16743 BASELINK_QUALIFIED_P (baselink) = false;
16746 return baselink;
16749 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID. DONE is
16750 true if the qualified-id will be a postfix-expression in-and-of
16751 itself; false if more of the postfix-expression follows the
16752 QUALIFIED_ID. ADDRESS_P is true if the qualified-id is the operand
16753 of "&". */
16755 static tree
16756 tsubst_qualified_id (tree qualified_id, tree args,
16757 tsubst_flags_t complain, tree in_decl,
16758 bool done, bool address_p)
16760 tree expr;
16761 tree scope;
16762 tree name;
16763 bool is_template;
16764 tree template_args;
16765 location_t loc = EXPR_LOCATION (qualified_id);
16767 gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
16769 /* Figure out what name to look up. */
16770 name = TREE_OPERAND (qualified_id, 1);
16771 if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
16773 is_template = true;
16774 template_args = TREE_OPERAND (name, 1);
16775 if (template_args)
16776 template_args = tsubst_template_args (template_args, args,
16777 complain, in_decl);
16778 if (template_args == error_mark_node)
16779 return error_mark_node;
16780 name = TREE_OPERAND (name, 0);
16782 else
16784 is_template = false;
16785 template_args = NULL_TREE;
16788 /* Substitute into the qualifying scope. When there are no ARGS, we
16789 are just trying to simplify a non-dependent expression. In that
16790 case the qualifying scope may be dependent, and, in any case,
16791 substituting will not help. */
16792 scope = TREE_OPERAND (qualified_id, 0);
16793 if (args)
16795 scope = tsubst (scope, args, complain, in_decl);
16796 expr = tsubst_copy (name, args, complain, in_decl);
16798 else
16799 expr = name;
16801 if (dependent_scope_p (scope))
16803 if (TREE_CODE (expr) == SCOPE_REF)
16804 /* We built one in tsubst_baselink. */
16805 gcc_checking_assert (same_type_p (scope, TREE_OPERAND (expr, 0)));
16806 else
16808 if (is_template)
16809 expr = build_min_nt_loc (loc, TEMPLATE_ID_EXPR, expr,
16810 template_args);
16811 expr = build_qualified_name (NULL_TREE, scope, expr,
16812 QUALIFIED_NAME_IS_TEMPLATE
16813 (qualified_id));
16815 REF_PARENTHESIZED_P (expr) = REF_PARENTHESIZED_P (qualified_id);
16816 return expr;
16819 if (!BASELINK_P (name) && !DECL_P (expr))
16821 if (TREE_CODE (expr) == BIT_NOT_EXPR)
16823 /* A BIT_NOT_EXPR is used to represent a destructor. */
16824 if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
16826 error ("qualifying type %qT does not match destructor name ~%qT",
16827 scope, TREE_OPERAND (expr, 0));
16828 expr = error_mark_node;
16830 else
16831 expr = lookup_qualified_name (scope, complete_dtor_identifier,
16832 LOOK_want::NORMAL, false);
16834 else
16835 expr = lookup_qualified_name (scope, expr, LOOK_want::NORMAL, false);
16836 if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
16837 ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
16839 if (complain & tf_error)
16841 error ("dependent-name %qE is parsed as a non-type, but "
16842 "instantiation yields a type", qualified_id);
16843 inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
16845 return error_mark_node;
16849 if (DECL_P (expr))
16851 if (!check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
16852 scope, complain))
16853 return error_mark_node;
16854 /* Remember that there was a reference to this entity. */
16855 if (!mark_used (expr, complain) && !(complain & tf_error))
16856 return error_mark_node;
16859 if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
16861 if (complain & tf_error)
16862 qualified_name_lookup_error (scope,
16863 TREE_OPERAND (qualified_id, 1),
16864 expr, input_location);
16865 return error_mark_node;
16868 if (is_template)
16870 /* We may be repeating a check already done during parsing, but
16871 if it was well-formed and passed then, it will pass again
16872 now, and if it didn't, we wouldn't have got here. The case
16873 we want to catch is when we couldn't tell then, and can now,
16874 namely when templ prior to substitution was an
16875 identifier. */
16876 if (flag_concepts && check_auto_in_tmpl_args (expr, template_args))
16877 return error_mark_node;
16879 if (variable_template_p (expr))
16880 expr = lookup_and_finish_template_variable (expr, template_args,
16881 complain);
16882 else
16883 expr = lookup_template_function (expr, template_args);
16886 if (expr == error_mark_node && complain & tf_error)
16887 qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
16888 expr, input_location);
16889 else if (TYPE_P (scope))
16891 expr = (adjust_result_of_qualified_name_lookup
16892 (expr, scope, current_nonlambda_class_type ()));
16893 expr = (finish_qualified_id_expr
16894 (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
16895 QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
16896 /*template_arg_p=*/false, complain));
16899 /* Expressions do not generally have reference type. */
16900 if (TREE_CODE (expr) != SCOPE_REF
16901 /* However, if we're about to form a pointer-to-member, we just
16902 want the referenced member referenced. */
16903 && TREE_CODE (expr) != OFFSET_REF)
16904 expr = convert_from_reference (expr);
16906 if (REF_PARENTHESIZED_P (qualified_id))
16907 expr = force_paren_expr (expr);
16909 expr = maybe_wrap_with_location (expr, loc);
16911 return expr;
16914 /* tsubst the initializer for a VAR_DECL. INIT is the unsubstituted
16915 initializer, DECL is the substituted VAR_DECL. Other arguments are as
16916 for tsubst. */
16918 static tree
16919 tsubst_init (tree init, tree decl, tree args,
16920 tsubst_flags_t complain, tree in_decl)
16922 if (!init)
16923 return NULL_TREE;
16925 init = tsubst_expr (init, args, complain, in_decl);
16927 tree type = TREE_TYPE (decl);
16929 if (!init && type != error_mark_node)
16931 if (tree auto_node = type_uses_auto (type))
16933 if (!CLASS_PLACEHOLDER_TEMPLATE (auto_node))
16935 if (complain & tf_error)
16936 error ("initializer for %q#D expands to an empty list "
16937 "of expressions", decl);
16938 return error_mark_node;
16941 else if (!dependent_type_p (type))
16943 /* If we had an initializer but it
16944 instantiated to nothing,
16945 value-initialize the object. This will
16946 only occur when the initializer was a
16947 pack expansion where the parameter packs
16948 used in that expansion were of length
16949 zero. */
16950 init = build_value_init (type, complain);
16951 if (TREE_CODE (init) == AGGR_INIT_EXPR)
16952 init = get_target_expr (init, complain);
16953 if (TREE_CODE (init) == TARGET_EXPR)
16954 TARGET_EXPR_DIRECT_INIT_P (init) = true;
16958 return init;
16961 /* If T is a reference to a dependent member of the current instantiation C and
16962 we are trying to refer to that member in a partial instantiation of C,
16963 return a SCOPE_REF; otherwise, return NULL_TREE.
16965 This can happen when forming a C++17 deduction guide, as in PR96199. */
16967 static tree
16968 maybe_dependent_member_ref (tree t, tree args, tsubst_flags_t complain,
16969 tree in_decl)
16971 if (!(complain & tf_dguide))
16972 return NULL_TREE;
16974 tree decl = (t && TYPE_P (t)) ? TYPE_NAME (t) : t;
16975 if (!decl || !DECL_P (decl))
16976 return NULL_TREE;
16978 tree ctx = context_for_name_lookup (decl);
16979 if (!CLASS_TYPE_P (ctx))
16980 return NULL_TREE;
16982 ctx = tsubst (ctx, args, complain, in_decl);
16983 if (!dependent_scope_p (ctx))
16984 return NULL_TREE;
16986 if (TYPE_P (t))
16988 if (typedef_variant_p (t))
16989 t = strip_typedefs (t);
16990 tree decl = TYPE_NAME (t);
16991 if (decl)
16992 decl = maybe_dependent_member_ref (decl, args, complain, in_decl);
16993 if (!decl)
16994 return NULL_TREE;
16995 return cp_build_qualified_type (TREE_TYPE (decl), cp_type_quals (t),
16996 complain);
16999 tree name = DECL_NAME (t);
17000 tree fullname = name;
17001 if (instantiates_primary_template_p (t))
17003 tree tinfo = get_template_info (t);
17004 name = DECL_NAME (TI_TEMPLATE (tinfo));
17005 tree targs = INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo));
17006 targs = tsubst_template_args (targs, args, complain, in_decl);
17007 fullname = build_nt (TEMPLATE_ID_EXPR, name, targs);
17010 if (TREE_CODE (t) == TYPE_DECL)
17012 if (TREE_CODE (TREE_TYPE (t)) == TYPENAME_TYPE
17013 && TYPE_NAME (TREE_TYPE (t)) == t)
17014 /* The TYPE_DECL for a typename has DECL_CONTEXT of the typename
17015 scope, but it doesn't need to be rewritten again. */
17016 return NULL_TREE;
17017 tree type = build_typename_type (ctx, name, fullname, typename_type);
17018 return TYPE_NAME (type);
17020 else if (DECL_TYPE_TEMPLATE_P (t))
17021 return make_unbound_class_template (ctx, name,
17022 NULL_TREE, complain);
17023 else
17024 return build_qualified_name (NULL_TREE, ctx, fullname,
17025 TREE_CODE (t) == TEMPLATE_DECL);
17028 /* Like tsubst, but deals with expressions. This function just replaces
17029 template parms; to finish processing the resultant expression, use
17030 tsubst_copy_and_build or tsubst_expr. */
17032 static tree
17033 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
17035 enum tree_code code;
17036 tree r;
17038 if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
17039 return t;
17041 if (tree d = maybe_dependent_member_ref (t, args, complain, in_decl))
17042 return d;
17044 code = TREE_CODE (t);
17046 switch (code)
17048 case PARM_DECL:
17049 r = retrieve_local_specialization (t);
17051 if (r == NULL_TREE)
17053 /* We get here for a use of 'this' in an NSDMI. */
17054 if (DECL_NAME (t) == this_identifier && current_class_ptr)
17055 return current_class_ptr;
17057 /* This can happen for a parameter name used later in a function
17058 declaration (such as in a late-specified return type). Just
17059 make a dummy decl, since it's only used for its type. */
17060 gcc_assert (cp_unevaluated_operand);
17061 r = tsubst_decl (t, args, complain);
17062 /* Give it the template pattern as its context; its true context
17063 hasn't been instantiated yet and this is good enough for
17064 mangling. */
17065 DECL_CONTEXT (r) = DECL_CONTEXT (t);
17068 if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
17069 r = argument_pack_select_arg (r);
17070 if (!mark_used (r, complain) && !(complain & tf_error))
17071 return error_mark_node;
17072 return r;
17074 case CONST_DECL:
17076 tree enum_type;
17077 tree v;
17079 if (DECL_TEMPLATE_PARM_P (t))
17080 return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
17081 if (!uses_template_parms (DECL_CONTEXT (t)))
17082 return t;
17084 /* Unfortunately, we cannot just call lookup_name here.
17085 Consider:
17087 template <int I> int f() {
17088 enum E { a = I };
17089 struct S { void g() { E e = a; } };
17092 When we instantiate f<7>::S::g(), say, lookup_name is not
17093 clever enough to find f<7>::a. */
17094 enum_type
17095 = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
17096 /*entering_scope=*/0);
17098 for (v = TYPE_VALUES (enum_type);
17099 v != NULL_TREE;
17100 v = TREE_CHAIN (v))
17101 if (TREE_PURPOSE (v) == DECL_NAME (t))
17102 return TREE_VALUE (v);
17104 /* We didn't find the name. That should never happen; if
17105 name-lookup found it during preliminary parsing, we
17106 should find it again here during instantiation. */
17107 gcc_unreachable ();
17109 return t;
17111 case FIELD_DECL:
17112 if (DECL_CONTEXT (t))
17114 tree ctx;
17116 ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
17117 /*entering_scope=*/1);
17118 if (ctx != DECL_CONTEXT (t))
17120 tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
17121 if (!r)
17123 if (complain & tf_error)
17124 error ("using invalid field %qD", t);
17125 return error_mark_node;
17127 return r;
17131 return t;
17133 case VAR_DECL:
17134 case FUNCTION_DECL:
17135 if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
17136 r = tsubst (t, args, complain, in_decl);
17137 else if (DECL_LOCAL_DECL_P (t))
17139 /* Local specialization will usually have been created when
17140 we instantiated the DECL_EXPR_DECL. */
17141 r = retrieve_local_specialization (t);
17142 if (!r)
17144 /* We're in a generic lambda referencing a local extern
17145 from an outer block-scope of a non-template. */
17146 gcc_checking_assert (LAMBDA_FUNCTION_P (current_function_decl));
17147 r = t;
17150 else if (local_variable_p (t)
17151 && uses_template_parms (DECL_CONTEXT (t)))
17153 r = retrieve_local_specialization (t);
17154 if (r == NULL_TREE)
17156 /* First try name lookup to find the instantiation. */
17157 r = lookup_name (DECL_NAME (t));
17158 if (r)
17160 if (!VAR_P (r))
17162 /* During error-recovery we may find a non-variable,
17163 even an OVERLOAD: just bail out and avoid ICEs and
17164 duplicate diagnostics (c++/62207). */
17165 gcc_assert (seen_error ());
17166 return error_mark_node;
17168 if (!is_capture_proxy (r))
17170 /* Make sure the one we found is the one we want. */
17171 tree ctx = enclosing_instantiation_of (DECL_CONTEXT (t));
17172 if (ctx != DECL_CONTEXT (r))
17173 r = NULL_TREE;
17177 if (r)
17178 /* OK */;
17179 else
17181 /* This can happen for a variable used in a
17182 late-specified return type of a local lambda, or for a
17183 local static or constant. Building a new VAR_DECL
17184 should be OK in all those cases. */
17185 r = tsubst_decl (t, args, complain);
17186 if (local_specializations)
17187 /* Avoid infinite recursion (79640). */
17188 register_local_specialization (r, t);
17189 if (decl_maybe_constant_var_p (r))
17191 /* We can't call cp_finish_decl, so handle the
17192 initializer by hand. */
17193 tree init = tsubst_init (DECL_INITIAL (t), r, args,
17194 complain, in_decl);
17195 if (!processing_template_decl)
17196 init = maybe_constant_init (init);
17197 if (processing_template_decl
17198 ? potential_constant_expression (init)
17199 : reduced_constant_expression_p (init))
17200 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
17201 = TREE_CONSTANT (r) = true;
17202 DECL_INITIAL (r) = init;
17203 if (tree auto_node = type_uses_auto (TREE_TYPE (r)))
17204 TREE_TYPE (r)
17205 = do_auto_deduction (TREE_TYPE (r), init, auto_node,
17206 complain, adc_variable_type);
17208 gcc_assert (cp_unevaluated_operand
17209 || processing_contract_condition
17210 || TREE_STATIC (r)
17211 || decl_constant_var_p (r)
17212 || seen_error ());
17213 if (!processing_template_decl
17214 && !TREE_STATIC (r))
17215 r = process_outer_var_ref (r, complain);
17217 /* Remember this for subsequent uses. */
17218 if (local_specializations)
17219 register_local_specialization (r, t);
17221 if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
17222 r = argument_pack_select_arg (r);
17224 else
17225 r = t;
17226 if (!mark_used (r, complain))
17227 return error_mark_node;
17228 return r;
17230 case NAMESPACE_DECL:
17231 return t;
17233 case OVERLOAD:
17234 return t;
17236 case BASELINK:
17237 return tsubst_baselink (t, current_nonlambda_class_type (),
17238 args, complain, in_decl);
17240 case TEMPLATE_DECL:
17241 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
17242 return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
17243 args, complain, in_decl);
17244 else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
17245 return tsubst (t, args, complain, in_decl);
17246 else if (DECL_CLASS_SCOPE_P (t)
17247 && uses_template_parms (DECL_CONTEXT (t)))
17249 /* Template template argument like the following example need
17250 special treatment:
17252 template <template <class> class TT> struct C {};
17253 template <class T> struct D {
17254 template <class U> struct E {};
17255 C<E> c; // #1
17257 D<int> d; // #2
17259 We are processing the template argument `E' in #1 for
17260 the template instantiation #2. Originally, `E' is a
17261 TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT. Now we
17262 have to substitute this with one having context `D<int>'. */
17264 tree context = tsubst_aggr_type (DECL_CONTEXT (t), args, complain,
17265 in_decl, /*entering_scope=*/true);
17266 return lookup_field (context, DECL_NAME(t), 0, false);
17268 else
17269 /* Ordinary template template argument. */
17270 return t;
17272 case NON_LVALUE_EXPR:
17273 case VIEW_CONVERT_EXPR:
17275 /* Handle location wrappers by substituting the wrapped node
17276 first, *then* reusing the resulting type. Doing the type
17277 first ensures that we handle template parameters and
17278 parameter pack expansions. */
17279 if (location_wrapper_p (t))
17281 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args,
17282 complain, in_decl);
17283 return maybe_wrap_with_location (op0, EXPR_LOCATION (t));
17285 tree op = TREE_OPERAND (t, 0);
17286 if (code == VIEW_CONVERT_EXPR
17287 && TREE_CODE (op) == TEMPLATE_PARM_INDEX)
17289 /* Wrapper to make a C++20 template parameter object const. */
17290 op = tsubst_copy (op, args, complain, in_decl);
17291 if (!CP_TYPE_CONST_P (TREE_TYPE (op)))
17293 /* The template argument is not const, presumably because
17294 it is still dependent, and so not the const template parm
17295 object. */
17296 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17297 gcc_checking_assert (same_type_ignoring_top_level_qualifiers_p
17298 (type, TREE_TYPE (op)));
17299 if (TREE_CODE (op) == CONSTRUCTOR
17300 || TREE_CODE (op) == IMPLICIT_CONV_EXPR)
17302 /* Don't add a wrapper to these. */
17303 op = copy_node (op);
17304 TREE_TYPE (op) = type;
17306 else
17307 /* Do add a wrapper otherwise (in particular, if op is
17308 another TEMPLATE_PARM_INDEX). */
17309 op = build1 (code, type, op);
17311 return op;
17313 /* force_paren_expr can also create a VIEW_CONVERT_EXPR. */
17314 else if (code == VIEW_CONVERT_EXPR && REF_PARENTHESIZED_P (t))
17316 op = tsubst_copy (op, args, complain, in_decl);
17317 op = build1 (code, TREE_TYPE (op), op);
17318 REF_PARENTHESIZED_P (op) = true;
17319 return op;
17321 /* We shouldn't see any other uses of these in templates. */
17322 gcc_unreachable ();
17325 case CAST_EXPR:
17326 case REINTERPRET_CAST_EXPR:
17327 case CONST_CAST_EXPR:
17328 case STATIC_CAST_EXPR:
17329 case DYNAMIC_CAST_EXPR:
17330 case IMPLICIT_CONV_EXPR:
17331 CASE_CONVERT:
17333 tsubst_flags_t tcomplain = complain;
17334 if (code == CAST_EXPR)
17335 tcomplain |= tf_tst_ok;
17336 tree type = tsubst (TREE_TYPE (t), args, tcomplain, in_decl);
17337 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17338 return build1 (code, type, op0);
17341 case BIT_CAST_EXPR:
17343 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17344 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17345 r = build_min (BIT_CAST_EXPR, type, op0);
17346 SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
17347 return r;
17350 case SIZEOF_EXPR:
17351 if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
17352 || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
17354 tree expanded, op = TREE_OPERAND (t, 0);
17355 int len = 0;
17357 if (SIZEOF_EXPR_TYPE_P (t))
17358 op = TREE_TYPE (op);
17360 ++cp_unevaluated_operand;
17361 ++c_inhibit_evaluation_warnings;
17362 /* We only want to compute the number of arguments. */
17363 if (PACK_EXPANSION_P (op))
17364 expanded = tsubst_pack_expansion (op, args, complain, in_decl);
17365 else
17366 expanded = tsubst_template_args (ARGUMENT_PACK_ARGS (op),
17367 args, complain, in_decl);
17368 --cp_unevaluated_operand;
17369 --c_inhibit_evaluation_warnings;
17371 if (TREE_CODE (expanded) == TREE_VEC)
17373 len = TREE_VEC_LENGTH (expanded);
17374 /* Set TREE_USED for the benefit of -Wunused. */
17375 for (int i = 0; i < len; i++)
17376 if (DECL_P (TREE_VEC_ELT (expanded, i)))
17377 TREE_USED (TREE_VEC_ELT (expanded, i)) = true;
17380 if (expanded == error_mark_node)
17381 return error_mark_node;
17382 else if (PACK_EXPANSION_P (expanded)
17383 || (TREE_CODE (expanded) == TREE_VEC
17384 && pack_expansion_args_count (expanded)))
17387 if (PACK_EXPANSION_P (expanded))
17388 /* OK. */;
17389 else if (TREE_VEC_LENGTH (expanded) == 1)
17390 expanded = TREE_VEC_ELT (expanded, 0);
17391 else
17392 expanded = make_argument_pack (expanded);
17394 if (TYPE_P (expanded))
17395 return cxx_sizeof_or_alignof_type (input_location,
17396 expanded, SIZEOF_EXPR,
17397 false,
17398 complain & tf_error);
17399 else
17400 return cxx_sizeof_or_alignof_expr (input_location,
17401 expanded, SIZEOF_EXPR,
17402 false,
17403 complain & tf_error);
17405 else
17406 return build_int_cst (size_type_node, len);
17408 if (SIZEOF_EXPR_TYPE_P (t))
17410 r = tsubst (TREE_TYPE (TREE_OPERAND (t, 0)),
17411 args, complain, in_decl);
17412 r = build1 (NOP_EXPR, r, error_mark_node);
17413 r = build1 (SIZEOF_EXPR,
17414 tsubst (TREE_TYPE (t), args, complain, in_decl), r);
17415 SIZEOF_EXPR_TYPE_P (r) = 1;
17416 return r;
17418 /* Fall through */
17420 case INDIRECT_REF:
17421 case NEGATE_EXPR:
17422 case TRUTH_NOT_EXPR:
17423 case BIT_NOT_EXPR:
17424 case ADDR_EXPR:
17425 case UNARY_PLUS_EXPR: /* Unary + */
17426 case ALIGNOF_EXPR:
17427 case AT_ENCODE_EXPR:
17428 case ARROW_EXPR:
17429 case THROW_EXPR:
17430 case TYPEID_EXPR:
17431 case REALPART_EXPR:
17432 case IMAGPART_EXPR:
17433 case PAREN_EXPR:
17435 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17436 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17437 r = build1_loc (EXPR_LOCATION (t), code, type, op0);
17438 if (code == ALIGNOF_EXPR)
17439 ALIGNOF_EXPR_STD_P (r) = ALIGNOF_EXPR_STD_P (t);
17440 /* For addresses of immediate functions ensure we have EXPR_LOCATION
17441 set for possible later diagnostics. */
17442 if (code == ADDR_EXPR
17443 && EXPR_LOCATION (r) == UNKNOWN_LOCATION
17444 && TREE_CODE (op0) == FUNCTION_DECL
17445 && DECL_IMMEDIATE_FUNCTION_P (op0))
17446 SET_EXPR_LOCATION (r, input_location);
17447 return r;
17450 case EXCESS_PRECISION_EXPR:
17452 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17453 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17454 if (TREE_CODE (op0) == EXCESS_PRECISION_EXPR)
17456 gcc_checking_assert (same_type_p (type, TREE_TYPE (op0)));
17457 return op0;
17459 return build1_loc (EXPR_LOCATION (t), code, type, op0);
17462 case COMPONENT_REF:
17464 tree object;
17465 tree name;
17467 object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17468 name = TREE_OPERAND (t, 1);
17469 if (TREE_CODE (name) == BIT_NOT_EXPR)
17471 name = tsubst_copy (TREE_OPERAND (name, 0), args,
17472 complain, in_decl);
17473 name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
17475 else if (TREE_CODE (name) == SCOPE_REF
17476 && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
17478 tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
17479 complain, in_decl);
17480 name = TREE_OPERAND (name, 1);
17481 name = tsubst_copy (TREE_OPERAND (name, 0), args,
17482 complain, in_decl);
17483 name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
17484 name = build_qualified_name (/*type=*/NULL_TREE,
17485 base, name,
17486 /*template_p=*/false);
17488 else if (BASELINK_P (name))
17489 name = tsubst_baselink (name,
17490 non_reference (TREE_TYPE (object)),
17491 args, complain,
17492 in_decl);
17493 else
17494 name = tsubst_copy (name, args, complain, in_decl);
17495 return build_nt (COMPONENT_REF, object, name, NULL_TREE);
17498 case PLUS_EXPR:
17499 case MINUS_EXPR:
17500 case MULT_EXPR:
17501 case TRUNC_DIV_EXPR:
17502 case CEIL_DIV_EXPR:
17503 case FLOOR_DIV_EXPR:
17504 case ROUND_DIV_EXPR:
17505 case EXACT_DIV_EXPR:
17506 case BIT_AND_EXPR:
17507 case BIT_IOR_EXPR:
17508 case BIT_XOR_EXPR:
17509 case TRUNC_MOD_EXPR:
17510 case FLOOR_MOD_EXPR:
17511 case TRUTH_ANDIF_EXPR:
17512 case TRUTH_ORIF_EXPR:
17513 case TRUTH_AND_EXPR:
17514 case TRUTH_OR_EXPR:
17515 case RSHIFT_EXPR:
17516 case LSHIFT_EXPR:
17517 case EQ_EXPR:
17518 case NE_EXPR:
17519 case MAX_EXPR:
17520 case MIN_EXPR:
17521 case LE_EXPR:
17522 case GE_EXPR:
17523 case LT_EXPR:
17524 case GT_EXPR:
17525 case COMPOUND_EXPR:
17526 case DOTSTAR_EXPR:
17527 case MEMBER_REF:
17528 case PREDECREMENT_EXPR:
17529 case PREINCREMENT_EXPR:
17530 case POSTDECREMENT_EXPR:
17531 case POSTINCREMENT_EXPR:
17533 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17534 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17535 return build_nt (code, op0, op1);
17538 case SCOPE_REF:
17540 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17541 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17542 return build_qualified_name (/*type=*/NULL_TREE, op0, op1,
17543 QUALIFIED_NAME_IS_TEMPLATE (t));
17546 case ARRAY_REF:
17548 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17549 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17550 return build_nt (ARRAY_REF, op0, op1, NULL_TREE, NULL_TREE);
17553 case CALL_EXPR:
17555 int n = VL_EXP_OPERAND_LENGTH (t);
17556 tree result = build_vl_exp (CALL_EXPR, n);
17557 int i;
17558 for (i = 0; i < n; i++)
17559 TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
17560 complain, in_decl);
17561 return result;
17564 case COND_EXPR:
17565 case MODOP_EXPR:
17566 case PSEUDO_DTOR_EXPR:
17567 case VEC_PERM_EXPR:
17569 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17570 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17571 tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
17572 r = build_nt (code, op0, op1, op2);
17573 copy_warning (r, t);
17574 return r;
17577 case NEW_EXPR:
17579 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17580 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17581 tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
17582 r = build_nt (code, op0, op1, op2);
17583 NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
17584 return r;
17587 case DELETE_EXPR:
17589 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17590 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17591 r = build_nt (code, op0, op1);
17592 DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
17593 DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
17594 return r;
17597 case TEMPLATE_ID_EXPR:
17599 /* Substituted template arguments */
17600 tree tmpl = TREE_OPERAND (t, 0);
17601 tree targs = TREE_OPERAND (t, 1);
17603 tmpl = tsubst_copy (tmpl, args, complain, in_decl);
17604 if (targs)
17605 targs = tsubst_template_args (targs, args, complain, in_decl);
17607 if (variable_template_p (tmpl))
17608 return lookup_template_variable (tmpl, targs);
17609 else
17610 return lookup_template_function (tmpl, targs);
17613 case TREE_LIST:
17615 tree purpose, value, chain;
17617 if (t == void_list_node)
17618 return t;
17620 purpose = TREE_PURPOSE (t);
17621 if (purpose)
17622 purpose = tsubst_copy (purpose, args, complain, in_decl);
17623 value = TREE_VALUE (t);
17624 if (value)
17625 value = tsubst_copy (value, args, complain, in_decl);
17626 chain = TREE_CHAIN (t);
17627 if (chain && chain != void_type_node)
17628 chain = tsubst_copy (chain, args, complain, in_decl);
17629 if (purpose == TREE_PURPOSE (t)
17630 && value == TREE_VALUE (t)
17631 && chain == TREE_CHAIN (t))
17632 return t;
17633 return tree_cons (purpose, value, chain);
17636 case RECORD_TYPE:
17637 case UNION_TYPE:
17638 case ENUMERAL_TYPE:
17639 case INTEGER_TYPE:
17640 case TEMPLATE_TYPE_PARM:
17641 case TEMPLATE_TEMPLATE_PARM:
17642 case BOUND_TEMPLATE_TEMPLATE_PARM:
17643 case TEMPLATE_PARM_INDEX:
17644 case POINTER_TYPE:
17645 case REFERENCE_TYPE:
17646 case OFFSET_TYPE:
17647 case FUNCTION_TYPE:
17648 case METHOD_TYPE:
17649 case ARRAY_TYPE:
17650 case TYPENAME_TYPE:
17651 case UNBOUND_CLASS_TEMPLATE:
17652 case TYPEOF_TYPE:
17653 case DECLTYPE_TYPE:
17654 case TYPE_DECL:
17655 return tsubst (t, args, complain, in_decl);
17657 case USING_DECL:
17658 t = DECL_NAME (t);
17659 /* Fall through. */
17660 case IDENTIFIER_NODE:
17661 if (IDENTIFIER_CONV_OP_P (t))
17663 tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17664 return make_conv_op_name (new_type);
17666 else
17667 return t;
17669 case CONSTRUCTOR:
17670 /* This is handled by tsubst_copy_and_build. */
17671 gcc_unreachable ();
17673 case VA_ARG_EXPR:
17675 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17676 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17677 return build_x_va_arg (EXPR_LOCATION (t), op0, type);
17680 case CLEANUP_POINT_EXPR:
17681 /* We shouldn't have built any of these during initial template
17682 generation. Instead, they should be built during instantiation
17683 in response to the saved STMT_IS_FULL_EXPR_P setting. */
17684 gcc_unreachable ();
17686 case OFFSET_REF:
17688 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17689 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17690 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17691 r = build2 (code, type, op0, op1);
17692 PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
17693 if (!mark_used (TREE_OPERAND (r, 1), complain)
17694 && !(complain & tf_error))
17695 return error_mark_node;
17696 return r;
17699 case EXPR_PACK_EXPANSION:
17700 error ("invalid use of pack expansion expression");
17701 return error_mark_node;
17703 case NONTYPE_ARGUMENT_PACK:
17704 error ("use %<...%> to expand argument pack");
17705 return error_mark_node;
17707 case VOID_CST:
17708 gcc_checking_assert (t == void_node && VOID_TYPE_P (TREE_TYPE (t)));
17709 return t;
17711 case INTEGER_CST:
17712 case REAL_CST:
17713 case COMPLEX_CST:
17714 case VECTOR_CST:
17716 /* Instantiate any typedefs in the type. */
17717 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17718 r = fold_convert (type, t);
17719 gcc_assert (TREE_CODE (r) == code);
17720 return r;
17723 case STRING_CST:
17725 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17726 r = t;
17727 if (type != TREE_TYPE (t))
17729 r = copy_node (t);
17730 TREE_TYPE (r) = type;
17732 return r;
17735 case PTRMEM_CST:
17736 /* These can sometimes show up in a partial instantiation, but never
17737 involve template parms. */
17738 gcc_assert (!uses_template_parms (t));
17739 return t;
17741 case UNARY_LEFT_FOLD_EXPR:
17742 return tsubst_unary_left_fold (t, args, complain, in_decl);
17743 case UNARY_RIGHT_FOLD_EXPR:
17744 return tsubst_unary_right_fold (t, args, complain, in_decl);
17745 case BINARY_LEFT_FOLD_EXPR:
17746 return tsubst_binary_left_fold (t, args, complain, in_decl);
17747 case BINARY_RIGHT_FOLD_EXPR:
17748 return tsubst_binary_right_fold (t, args, complain, in_decl);
17749 case PREDICT_EXPR:
17750 return t;
17752 case DEBUG_BEGIN_STMT:
17753 /* ??? There's no point in copying it for now, but maybe some
17754 day it will contain more information, such as a pointer back
17755 to the containing function, inlined copy or so. */
17756 return t;
17758 case CO_AWAIT_EXPR:
17759 return tsubst_expr (t, args, complain, in_decl);
17761 default:
17762 /* We shouldn't get here, but keep going if !flag_checking. */
17763 if (flag_checking)
17764 gcc_unreachable ();
17765 return t;
17769 /* Helper function for tsubst_omp_clauses, used for instantiation of
17770 OMP_CLAUSE_DECL of clauses. */
17772 static tree
17773 tsubst_omp_clause_decl (tree decl, tree args, tsubst_flags_t complain,
17774 tree in_decl, tree *iterator_cache)
17776 if (decl == NULL_TREE || decl == ridpointers[RID_OMP_ALL_MEMORY])
17777 return decl;
17779 /* Handle OpenMP iterators. */
17780 if (TREE_CODE (decl) == TREE_LIST
17781 && TREE_PURPOSE (decl)
17782 && TREE_CODE (TREE_PURPOSE (decl)) == TREE_VEC)
17784 tree ret;
17785 if (iterator_cache[0] == TREE_PURPOSE (decl))
17786 ret = iterator_cache[1];
17787 else
17789 tree *tp = &ret;
17790 begin_scope (sk_omp, NULL);
17791 for (tree it = TREE_PURPOSE (decl); it; it = TREE_CHAIN (it))
17793 *tp = copy_node (it);
17794 TREE_VEC_ELT (*tp, 0)
17795 = tsubst_decl (TREE_VEC_ELT (it, 0), args, complain);
17796 DECL_CONTEXT (TREE_VEC_ELT (*tp, 0)) = current_function_decl;
17797 pushdecl (TREE_VEC_ELT (*tp, 0));
17798 TREE_VEC_ELT (*tp, 1)
17799 = tsubst_expr (TREE_VEC_ELT (it, 1), args, complain, in_decl);
17800 TREE_VEC_ELT (*tp, 2)
17801 = tsubst_expr (TREE_VEC_ELT (it, 2), args, complain, in_decl);
17802 TREE_VEC_ELT (*tp, 3)
17803 = tsubst_expr (TREE_VEC_ELT (it, 3), args, complain, in_decl);
17804 TREE_CHAIN (*tp) = NULL_TREE;
17805 tp = &TREE_CHAIN (*tp);
17807 TREE_VEC_ELT (ret, 5) = poplevel (1, 1, 0);
17808 iterator_cache[0] = TREE_PURPOSE (decl);
17809 iterator_cache[1] = ret;
17811 return build_tree_list (ret, tsubst_omp_clause_decl (TREE_VALUE (decl),
17812 args, complain,
17813 in_decl, NULL));
17816 /* Handle an OpenMP array section represented as a TREE_LIST (or
17817 OMP_CLAUSE_DOACROSS_KIND). An OMP_CLAUSE_DOACROSS (with a depend
17818 kind of OMP_CLAUSE_DOACROSS_SINK) can also be represented as a
17819 TREE_LIST. We can handle it exactly the same as an array section
17820 (purpose, value, and a chain), even though the nomenclature
17821 (low_bound, length, etc) is different. */
17822 if (TREE_CODE (decl) == TREE_LIST)
17824 tree low_bound
17825 = tsubst_expr (TREE_PURPOSE (decl), args, complain, in_decl);
17826 tree length = tsubst_expr (TREE_VALUE (decl), args, complain, in_decl);
17827 tree chain = tsubst_omp_clause_decl (TREE_CHAIN (decl), args, complain,
17828 in_decl, NULL);
17829 if (TREE_PURPOSE (decl) == low_bound
17830 && TREE_VALUE (decl) == length
17831 && TREE_CHAIN (decl) == chain)
17832 return decl;
17833 tree ret = tree_cons (low_bound, length, chain);
17834 OMP_CLAUSE_DOACROSS_SINK_NEGATIVE (ret)
17835 = OMP_CLAUSE_DOACROSS_SINK_NEGATIVE (decl);
17836 return ret;
17838 tree ret = tsubst_expr (decl, args, complain, in_decl);
17839 /* Undo convert_from_reference tsubst_expr could have called. */
17840 if (decl
17841 && REFERENCE_REF_P (ret)
17842 && !REFERENCE_REF_P (decl))
17843 ret = TREE_OPERAND (ret, 0);
17844 return ret;
17847 /* Like tsubst_copy, but specifically for OpenMP clauses. */
17849 static tree
17850 tsubst_omp_clauses (tree clauses, enum c_omp_region_type ort,
17851 tree args, tsubst_flags_t complain, tree in_decl)
17853 tree new_clauses = NULL_TREE, nc, oc;
17854 tree linear_no_step = NULL_TREE;
17855 tree iterator_cache[2] = { NULL_TREE, NULL_TREE };
17857 for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
17859 nc = copy_node (oc);
17860 OMP_CLAUSE_CHAIN (nc) = new_clauses;
17861 new_clauses = nc;
17863 switch (OMP_CLAUSE_CODE (nc))
17865 case OMP_CLAUSE_LASTPRIVATE:
17866 if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
17868 OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
17869 tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args,
17870 complain, in_decl);
17871 OMP_CLAUSE_LASTPRIVATE_STMT (nc)
17872 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
17874 /* FALLTHRU */
17875 case OMP_CLAUSE_PRIVATE:
17876 case OMP_CLAUSE_SHARED:
17877 case OMP_CLAUSE_FIRSTPRIVATE:
17878 case OMP_CLAUSE_COPYIN:
17879 case OMP_CLAUSE_COPYPRIVATE:
17880 case OMP_CLAUSE_UNIFORM:
17881 case OMP_CLAUSE_DEPEND:
17882 case OMP_CLAUSE_DOACROSS:
17883 case OMP_CLAUSE_AFFINITY:
17884 case OMP_CLAUSE_FROM:
17885 case OMP_CLAUSE_TO:
17886 case OMP_CLAUSE_MAP:
17887 case OMP_CLAUSE__CACHE_:
17888 case OMP_CLAUSE_NONTEMPORAL:
17889 case OMP_CLAUSE_USE_DEVICE_PTR:
17890 case OMP_CLAUSE_USE_DEVICE_ADDR:
17891 case OMP_CLAUSE_IS_DEVICE_PTR:
17892 case OMP_CLAUSE_HAS_DEVICE_ADDR:
17893 case OMP_CLAUSE_INCLUSIVE:
17894 case OMP_CLAUSE_EXCLUSIVE:
17895 OMP_CLAUSE_DECL (nc)
17896 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17897 in_decl, iterator_cache);
17898 break;
17899 case OMP_CLAUSE_NUM_TEAMS:
17900 if (OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (oc))
17901 OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (nc)
17902 = tsubst_expr (OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (oc), args,
17903 complain, in_decl);
17904 /* FALLTHRU */
17905 case OMP_CLAUSE_TILE:
17906 case OMP_CLAUSE_IF:
17907 case OMP_CLAUSE_NUM_THREADS:
17908 case OMP_CLAUSE_SCHEDULE:
17909 case OMP_CLAUSE_COLLAPSE:
17910 case OMP_CLAUSE_FINAL:
17911 case OMP_CLAUSE_DEVICE:
17912 case OMP_CLAUSE_DIST_SCHEDULE:
17913 case OMP_CLAUSE_THREAD_LIMIT:
17914 case OMP_CLAUSE_SAFELEN:
17915 case OMP_CLAUSE_SIMDLEN:
17916 case OMP_CLAUSE_NUM_TASKS:
17917 case OMP_CLAUSE_GRAINSIZE:
17918 case OMP_CLAUSE_PRIORITY:
17919 case OMP_CLAUSE_ORDERED:
17920 case OMP_CLAUSE_HINT:
17921 case OMP_CLAUSE_FILTER:
17922 case OMP_CLAUSE_NUM_GANGS:
17923 case OMP_CLAUSE_NUM_WORKERS:
17924 case OMP_CLAUSE_VECTOR_LENGTH:
17925 case OMP_CLAUSE_WORKER:
17926 case OMP_CLAUSE_VECTOR:
17927 case OMP_CLAUSE_ASYNC:
17928 case OMP_CLAUSE_WAIT:
17929 case OMP_CLAUSE_DETACH:
17930 OMP_CLAUSE_OPERAND (nc, 0)
17931 = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, in_decl);
17932 break;
17933 case OMP_CLAUSE_REDUCTION:
17934 case OMP_CLAUSE_IN_REDUCTION:
17935 case OMP_CLAUSE_TASK_REDUCTION:
17936 if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc))
17938 tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc);
17939 if (TREE_CODE (placeholder) == SCOPE_REF)
17941 tree scope = tsubst (TREE_OPERAND (placeholder, 0), args,
17942 complain, in_decl);
17943 OMP_CLAUSE_REDUCTION_PLACEHOLDER (nc)
17944 = build_qualified_name (NULL_TREE, scope,
17945 TREE_OPERAND (placeholder, 1),
17946 false);
17948 else
17949 gcc_assert (identifier_p (placeholder));
17951 OMP_CLAUSE_DECL (nc)
17952 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17953 in_decl, NULL);
17954 break;
17955 case OMP_CLAUSE_GANG:
17956 case OMP_CLAUSE_ALIGNED:
17957 OMP_CLAUSE_DECL (nc)
17958 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17959 in_decl, NULL);
17960 OMP_CLAUSE_OPERAND (nc, 1)
17961 = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 1), args, complain, in_decl);
17962 break;
17963 case OMP_CLAUSE_ALLOCATE:
17964 OMP_CLAUSE_DECL (nc)
17965 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17966 in_decl, NULL);
17967 OMP_CLAUSE_OPERAND (nc, 1)
17968 = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 1), args, complain, in_decl);
17969 OMP_CLAUSE_OPERAND (nc, 2)
17970 = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 2), args, complain, in_decl);
17971 break;
17972 case OMP_CLAUSE_LINEAR:
17973 OMP_CLAUSE_DECL (nc)
17974 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17975 in_decl, NULL);
17976 if (OMP_CLAUSE_LINEAR_STEP (oc) == NULL_TREE)
17978 gcc_assert (!linear_no_step);
17979 linear_no_step = nc;
17981 else if (OMP_CLAUSE_LINEAR_VARIABLE_STRIDE (oc))
17982 OMP_CLAUSE_LINEAR_STEP (nc)
17983 = tsubst_omp_clause_decl (OMP_CLAUSE_LINEAR_STEP (oc), args,
17984 complain, in_decl, NULL);
17985 else
17986 OMP_CLAUSE_LINEAR_STEP (nc)
17987 = tsubst_expr (OMP_CLAUSE_LINEAR_STEP (oc), args,
17988 complain, in_decl);
17989 break;
17990 case OMP_CLAUSE_NOWAIT:
17991 case OMP_CLAUSE_DEFAULT:
17992 case OMP_CLAUSE_UNTIED:
17993 case OMP_CLAUSE_MERGEABLE:
17994 case OMP_CLAUSE_INBRANCH:
17995 case OMP_CLAUSE_NOTINBRANCH:
17996 case OMP_CLAUSE_PROC_BIND:
17997 case OMP_CLAUSE_FOR:
17998 case OMP_CLAUSE_PARALLEL:
17999 case OMP_CLAUSE_SECTIONS:
18000 case OMP_CLAUSE_TASKGROUP:
18001 case OMP_CLAUSE_NOGROUP:
18002 case OMP_CLAUSE_THREADS:
18003 case OMP_CLAUSE_SIMD:
18004 case OMP_CLAUSE_DEFAULTMAP:
18005 case OMP_CLAUSE_ORDER:
18006 case OMP_CLAUSE_BIND:
18007 case OMP_CLAUSE_INDEPENDENT:
18008 case OMP_CLAUSE_AUTO:
18009 case OMP_CLAUSE_SEQ:
18010 case OMP_CLAUSE_IF_PRESENT:
18011 case OMP_CLAUSE_FINALIZE:
18012 case OMP_CLAUSE_NOHOST:
18013 break;
18014 default:
18015 gcc_unreachable ();
18017 if ((ort & C_ORT_OMP_DECLARE_SIMD) == C_ORT_OMP)
18018 switch (OMP_CLAUSE_CODE (nc))
18020 case OMP_CLAUSE_SHARED:
18021 case OMP_CLAUSE_PRIVATE:
18022 case OMP_CLAUSE_FIRSTPRIVATE:
18023 case OMP_CLAUSE_LASTPRIVATE:
18024 case OMP_CLAUSE_COPYPRIVATE:
18025 case OMP_CLAUSE_LINEAR:
18026 case OMP_CLAUSE_REDUCTION:
18027 case OMP_CLAUSE_IN_REDUCTION:
18028 case OMP_CLAUSE_TASK_REDUCTION:
18029 case OMP_CLAUSE_USE_DEVICE_PTR:
18030 case OMP_CLAUSE_USE_DEVICE_ADDR:
18031 case OMP_CLAUSE_IS_DEVICE_PTR:
18032 case OMP_CLAUSE_HAS_DEVICE_ADDR:
18033 case OMP_CLAUSE_INCLUSIVE:
18034 case OMP_CLAUSE_EXCLUSIVE:
18035 case OMP_CLAUSE_ALLOCATE:
18036 /* tsubst_expr on SCOPE_REF results in returning
18037 finish_non_static_data_member result. Undo that here. */
18038 if (TREE_CODE (OMP_CLAUSE_DECL (oc)) == SCOPE_REF
18039 && (TREE_CODE (TREE_OPERAND (OMP_CLAUSE_DECL (oc), 1))
18040 == IDENTIFIER_NODE))
18042 tree t = OMP_CLAUSE_DECL (nc);
18043 tree v = t;
18044 while (v)
18045 switch (TREE_CODE (v))
18047 case COMPONENT_REF:
18048 case MEM_REF:
18049 case INDIRECT_REF:
18050 CASE_CONVERT:
18051 case POINTER_PLUS_EXPR:
18052 v = TREE_OPERAND (v, 0);
18053 continue;
18054 case PARM_DECL:
18055 if (DECL_CONTEXT (v) == current_function_decl
18056 && DECL_ARTIFICIAL (v)
18057 && DECL_NAME (v) == this_identifier)
18058 OMP_CLAUSE_DECL (nc) = TREE_OPERAND (t, 1);
18059 /* FALLTHRU */
18060 default:
18061 v = NULL_TREE;
18062 break;
18065 else if (VAR_P (OMP_CLAUSE_DECL (oc))
18066 && DECL_HAS_VALUE_EXPR_P (OMP_CLAUSE_DECL (oc))
18067 && DECL_ARTIFICIAL (OMP_CLAUSE_DECL (oc))
18068 && DECL_LANG_SPECIFIC (OMP_CLAUSE_DECL (oc))
18069 && DECL_OMP_PRIVATIZED_MEMBER (OMP_CLAUSE_DECL (oc)))
18071 tree decl = OMP_CLAUSE_DECL (nc);
18072 if (VAR_P (decl))
18074 retrofit_lang_decl (decl);
18075 DECL_OMP_PRIVATIZED_MEMBER (decl) = 1;
18078 break;
18079 default:
18080 break;
18084 new_clauses = nreverse (new_clauses);
18085 if (ort != C_ORT_OMP_DECLARE_SIMD)
18087 new_clauses = finish_omp_clauses (new_clauses, ort);
18088 if (linear_no_step)
18089 for (nc = new_clauses; nc; nc = OMP_CLAUSE_CHAIN (nc))
18090 if (nc == linear_no_step)
18092 OMP_CLAUSE_LINEAR_STEP (nc) = NULL_TREE;
18093 break;
18096 return new_clauses;
18099 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes. */
18101 static tree
18102 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
18103 tree in_decl)
18105 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
18107 tree purpose, value, chain;
18109 if (t == NULL)
18110 return t;
18112 if (TREE_CODE (t) != TREE_LIST)
18113 return tsubst_copy_and_build (t, args, complain, in_decl);
18115 if (t == void_list_node)
18116 return t;
18118 purpose = TREE_PURPOSE (t);
18119 if (purpose)
18120 purpose = RECUR (purpose);
18121 value = TREE_VALUE (t);
18122 if (value)
18124 if (TREE_CODE (value) != LABEL_DECL)
18125 value = RECUR (value);
18126 else
18128 value = lookup_label (DECL_NAME (value));
18129 gcc_assert (TREE_CODE (value) == LABEL_DECL);
18130 TREE_USED (value) = 1;
18133 chain = TREE_CHAIN (t);
18134 if (chain && chain != void_type_node)
18135 chain = RECUR (chain);
18136 return tree_cons (purpose, value, chain);
18137 #undef RECUR
18140 /* Used to temporarily communicate the list of #pragma omp parallel
18141 clauses to #pragma omp for instantiation if they are combined
18142 together. */
18144 static tree *omp_parallel_combined_clauses;
18146 static tree tsubst_decomp_names (tree, tree, tree, tsubst_flags_t, tree,
18147 tree *, unsigned int *);
18149 /* Substitute one OMP_FOR iterator. */
18151 static bool
18152 tsubst_omp_for_iterator (tree t, int i, tree declv, tree &orig_declv,
18153 tree initv, tree condv, tree incrv, tree *clauses,
18154 tree args, tsubst_flags_t complain, tree in_decl)
18156 #define RECUR(NODE) \
18157 tsubst_expr ((NODE), args, complain, in_decl)
18158 tree decl, init, cond = NULL_TREE, incr = NULL_TREE;
18159 bool ret = false;
18161 init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
18162 gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
18164 decl = TREE_OPERAND (init, 0);
18165 init = TREE_OPERAND (init, 1);
18166 tree decl_expr = NULL_TREE;
18167 bool range_for = TREE_VEC_ELT (OMP_FOR_COND (t), i) == global_namespace;
18168 if (range_for)
18170 bool decomp = false;
18171 if (decl != error_mark_node && DECL_HAS_VALUE_EXPR_P (decl))
18173 tree v = DECL_VALUE_EXPR (decl);
18174 if (TREE_CODE (v) == ARRAY_REF
18175 && VAR_P (TREE_OPERAND (v, 0))
18176 && DECL_DECOMPOSITION_P (TREE_OPERAND (v, 0)))
18178 tree decomp_first = NULL_TREE;
18179 unsigned decomp_cnt = 0;
18180 tree d = tsubst_decl (TREE_OPERAND (v, 0), args, complain);
18181 maybe_push_decl (d);
18182 d = tsubst_decomp_names (d, TREE_OPERAND (v, 0), args, complain,
18183 in_decl, &decomp_first, &decomp_cnt);
18184 decomp = true;
18185 if (d == error_mark_node)
18186 decl = error_mark_node;
18187 else
18188 for (unsigned int i = 0; i < decomp_cnt; i++)
18190 if (!DECL_HAS_VALUE_EXPR_P (decomp_first))
18192 tree v = build_nt (ARRAY_REF, d,
18193 size_int (decomp_cnt - i - 1),
18194 NULL_TREE, NULL_TREE);
18195 SET_DECL_VALUE_EXPR (decomp_first, v);
18196 DECL_HAS_VALUE_EXPR_P (decomp_first) = 1;
18198 fit_decomposition_lang_decl (decomp_first, d);
18199 decomp_first = DECL_CHAIN (decomp_first);
18203 decl = tsubst_decl (decl, args, complain);
18204 if (!decomp)
18205 maybe_push_decl (decl);
18207 else if (init && TREE_CODE (init) == DECL_EXPR)
18209 /* We need to jump through some hoops to handle declarations in the
18210 init-statement, since we might need to handle auto deduction,
18211 but we need to keep control of initialization. */
18212 decl_expr = init;
18213 init = DECL_INITIAL (DECL_EXPR_DECL (init));
18214 decl = tsubst_decl (decl, args, complain);
18216 else
18218 if (TREE_CODE (decl) == SCOPE_REF)
18220 decl = RECUR (decl);
18221 if (TREE_CODE (decl) == COMPONENT_REF)
18223 tree v = decl;
18224 while (v)
18225 switch (TREE_CODE (v))
18227 case COMPONENT_REF:
18228 case MEM_REF:
18229 case INDIRECT_REF:
18230 CASE_CONVERT:
18231 case POINTER_PLUS_EXPR:
18232 v = TREE_OPERAND (v, 0);
18233 continue;
18234 case PARM_DECL:
18235 if (DECL_CONTEXT (v) == current_function_decl
18236 && DECL_ARTIFICIAL (v)
18237 && DECL_NAME (v) == this_identifier)
18239 decl = TREE_OPERAND (decl, 1);
18240 decl = omp_privatize_field (decl, false);
18242 /* FALLTHRU */
18243 default:
18244 v = NULL_TREE;
18245 break;
18249 else
18250 decl = RECUR (decl);
18252 if (init && TREE_CODE (init) == TREE_VEC)
18254 init = copy_node (init);
18255 TREE_VEC_ELT (init, 0)
18256 = tsubst_decl (TREE_VEC_ELT (init, 0), args, complain);
18257 TREE_VEC_ELT (init, 1) = RECUR (TREE_VEC_ELT (init, 1));
18258 TREE_VEC_ELT (init, 2) = RECUR (TREE_VEC_ELT (init, 2));
18260 else
18261 init = RECUR (init);
18263 if (orig_declv && OMP_FOR_ORIG_DECLS (t))
18265 tree o = TREE_VEC_ELT (OMP_FOR_ORIG_DECLS (t), i);
18266 if (TREE_CODE (o) == TREE_LIST)
18267 TREE_VEC_ELT (orig_declv, i)
18268 = tree_cons (RECUR (TREE_PURPOSE (o)),
18269 RECUR (TREE_VALUE (o)),
18270 NULL_TREE);
18271 else
18272 TREE_VEC_ELT (orig_declv, i) = RECUR (o);
18275 if (range_for)
18277 tree this_pre_body = NULL_TREE;
18278 tree orig_init = NULL_TREE;
18279 tree orig_decl = NULL_TREE;
18280 cp_convert_omp_range_for (this_pre_body, NULL, decl, orig_decl, init,
18281 orig_init, cond, incr);
18282 if (orig_decl)
18284 if (orig_declv == NULL_TREE)
18285 orig_declv = copy_node (declv);
18286 TREE_VEC_ELT (orig_declv, i) = orig_decl;
18287 ret = true;
18289 else if (orig_declv)
18290 TREE_VEC_ELT (orig_declv, i) = decl;
18293 tree auto_node = type_uses_auto (TREE_TYPE (decl));
18294 if (!range_for && auto_node && init)
18295 TREE_TYPE (decl)
18296 = do_auto_deduction (TREE_TYPE (decl), init, auto_node, complain);
18298 gcc_assert (!type_dependent_expression_p (decl));
18300 if (!CLASS_TYPE_P (TREE_TYPE (decl)) || range_for)
18302 if (decl_expr)
18304 /* Declare the variable, but don't let that initialize it. */
18305 tree init_sav = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
18306 DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL_TREE;
18307 RECUR (decl_expr);
18308 DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init_sav;
18311 if (!range_for)
18313 cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
18314 if (COMPARISON_CLASS_P (cond)
18315 && TREE_CODE (TREE_OPERAND (cond, 1)) == TREE_VEC)
18317 tree lhs = RECUR (TREE_OPERAND (cond, 0));
18318 tree rhs = copy_node (TREE_OPERAND (cond, 1));
18319 TREE_VEC_ELT (rhs, 0)
18320 = tsubst_decl (TREE_VEC_ELT (rhs, 0), args, complain);
18321 TREE_VEC_ELT (rhs, 1) = RECUR (TREE_VEC_ELT (rhs, 1));
18322 TREE_VEC_ELT (rhs, 2) = RECUR (TREE_VEC_ELT (rhs, 2));
18323 cond = build2 (TREE_CODE (cond), TREE_TYPE (cond),
18324 lhs, rhs);
18326 else
18327 cond = RECUR (cond);
18328 incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
18329 if (TREE_CODE (incr) == MODIFY_EXPR)
18331 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18332 tree rhs = RECUR (TREE_OPERAND (incr, 1));
18333 incr = build_x_modify_expr (EXPR_LOCATION (incr), lhs,
18334 NOP_EXPR, rhs, NULL_TREE, complain);
18336 else
18337 incr = RECUR (incr);
18338 if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
18339 TREE_VEC_ELT (orig_declv, i) = decl;
18341 TREE_VEC_ELT (declv, i) = decl;
18342 TREE_VEC_ELT (initv, i) = init;
18343 TREE_VEC_ELT (condv, i) = cond;
18344 TREE_VEC_ELT (incrv, i) = incr;
18345 return ret;
18348 if (decl_expr)
18350 /* Declare and initialize the variable. */
18351 RECUR (decl_expr);
18352 init = NULL_TREE;
18354 else if (init)
18356 tree *pc;
18357 int j;
18358 for (j = ((omp_parallel_combined_clauses == NULL
18359 || TREE_CODE (t) == OMP_LOOP) ? 1 : 0); j < 2; j++)
18361 for (pc = j ? clauses : omp_parallel_combined_clauses; *pc; )
18363 if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_PRIVATE
18364 && OMP_CLAUSE_DECL (*pc) == decl)
18365 break;
18366 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_LASTPRIVATE
18367 && OMP_CLAUSE_DECL (*pc) == decl)
18369 if (j)
18370 break;
18371 /* Move lastprivate (decl) clause to OMP_FOR_CLAUSES. */
18372 tree c = *pc;
18373 *pc = OMP_CLAUSE_CHAIN (c);
18374 OMP_CLAUSE_CHAIN (c) = *clauses;
18375 *clauses = c;
18377 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_FIRSTPRIVATE
18378 && OMP_CLAUSE_DECL (*pc) == decl)
18380 error ("iteration variable %qD should not be firstprivate",
18381 decl);
18382 *pc = OMP_CLAUSE_CHAIN (*pc);
18384 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_REDUCTION
18385 && OMP_CLAUSE_DECL (*pc) == decl)
18387 error ("iteration variable %qD should not be reduction",
18388 decl);
18389 *pc = OMP_CLAUSE_CHAIN (*pc);
18391 else
18392 pc = &OMP_CLAUSE_CHAIN (*pc);
18394 if (*pc)
18395 break;
18397 if (*pc == NULL_TREE)
18399 tree c = build_omp_clause (input_location,
18400 TREE_CODE (t) == OMP_LOOP
18401 ? OMP_CLAUSE_LASTPRIVATE
18402 : OMP_CLAUSE_PRIVATE);
18403 OMP_CLAUSE_DECL (c) = decl;
18404 c = finish_omp_clauses (c, C_ORT_OMP);
18405 if (c)
18407 OMP_CLAUSE_CHAIN (c) = *clauses;
18408 *clauses = c;
18412 cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
18413 if (COMPARISON_CLASS_P (cond))
18415 tree op0 = RECUR (TREE_OPERAND (cond, 0));
18416 tree op1 = RECUR (TREE_OPERAND (cond, 1));
18417 cond = build2 (TREE_CODE (cond), boolean_type_node, op0, op1);
18419 else
18420 cond = RECUR (cond);
18421 incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
18422 switch (TREE_CODE (incr))
18424 case PREINCREMENT_EXPR:
18425 case PREDECREMENT_EXPR:
18426 case POSTINCREMENT_EXPR:
18427 case POSTDECREMENT_EXPR:
18428 incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
18429 RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
18430 break;
18431 case MODIFY_EXPR:
18432 if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
18433 || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
18435 tree rhs = TREE_OPERAND (incr, 1);
18436 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18437 tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
18438 tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
18439 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18440 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
18441 rhs0, rhs1));
18443 else
18444 incr = RECUR (incr);
18445 break;
18446 case MODOP_EXPR:
18447 if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
18448 || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
18450 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18451 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18452 build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
18453 TREE_TYPE (decl), lhs,
18454 RECUR (TREE_OPERAND (incr, 2))));
18456 else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
18457 && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
18458 || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
18460 tree rhs = TREE_OPERAND (incr, 2);
18461 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18462 tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
18463 tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
18464 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18465 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
18466 rhs0, rhs1));
18468 else
18469 incr = RECUR (incr);
18470 break;
18471 default:
18472 incr = RECUR (incr);
18473 break;
18476 if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
18477 TREE_VEC_ELT (orig_declv, i) = decl;
18478 TREE_VEC_ELT (declv, i) = decl;
18479 TREE_VEC_ELT (initv, i) = init;
18480 TREE_VEC_ELT (condv, i) = cond;
18481 TREE_VEC_ELT (incrv, i) = incr;
18482 return false;
18483 #undef RECUR
18486 /* Helper function of tsubst_expr, find OMP_TEAMS inside
18487 of OMP_TARGET's body. */
18489 static tree
18490 tsubst_find_omp_teams (tree *tp, int *walk_subtrees, void *)
18492 *walk_subtrees = 0;
18493 switch (TREE_CODE (*tp))
18495 case OMP_TEAMS:
18496 return *tp;
18497 case BIND_EXPR:
18498 case STATEMENT_LIST:
18499 *walk_subtrees = 1;
18500 break;
18501 default:
18502 break;
18504 return NULL_TREE;
18507 /* Helper function for tsubst_expr. For decomposition declaration
18508 artificial base DECL, which is tsubsted PATTERN_DECL, tsubst
18509 also the corresponding decls representing the identifiers
18510 of the decomposition declaration. Return DECL if successful
18511 or error_mark_node otherwise, set *FIRST to the first decl
18512 in the list chained through DECL_CHAIN and *CNT to the number
18513 of such decls. */
18515 static tree
18516 tsubst_decomp_names (tree decl, tree pattern_decl, tree args,
18517 tsubst_flags_t complain, tree in_decl, tree *first,
18518 unsigned int *cnt)
18520 tree decl2, decl3, prev = decl;
18521 *cnt = 0;
18522 gcc_assert (DECL_NAME (decl) == NULL_TREE);
18523 for (decl2 = DECL_CHAIN (pattern_decl);
18524 decl2
18525 && VAR_P (decl2)
18526 && DECL_DECOMPOSITION_P (decl2)
18527 && DECL_NAME (decl2);
18528 decl2 = DECL_CHAIN (decl2))
18530 if (TREE_TYPE (decl2) == error_mark_node && *cnt == 0)
18532 gcc_assert (errorcount);
18533 return error_mark_node;
18535 (*cnt)++;
18536 gcc_assert (DECL_DECOMP_BASE (decl2) == pattern_decl);
18537 gcc_assert (DECL_HAS_VALUE_EXPR_P (decl2));
18538 tree v = DECL_VALUE_EXPR (decl2);
18539 DECL_HAS_VALUE_EXPR_P (decl2) = 0;
18540 SET_DECL_VALUE_EXPR (decl2, NULL_TREE);
18541 decl3 = tsubst (decl2, args, complain, in_decl);
18542 SET_DECL_VALUE_EXPR (decl2, v);
18543 DECL_HAS_VALUE_EXPR_P (decl2) = 1;
18544 if (VAR_P (decl3))
18545 DECL_TEMPLATE_INSTANTIATED (decl3) = 1;
18546 else
18548 gcc_assert (errorcount);
18549 decl = error_mark_node;
18550 continue;
18552 maybe_push_decl (decl3);
18553 if (error_operand_p (decl3))
18554 decl = error_mark_node;
18555 else if (decl != error_mark_node
18556 && DECL_CHAIN (decl3) != prev
18557 && decl != prev)
18559 gcc_assert (errorcount);
18560 decl = error_mark_node;
18562 else
18563 prev = decl3;
18565 *first = prev;
18566 return decl;
18569 /* Return the proper local_specialization for init-capture pack DECL. */
18571 static tree
18572 lookup_init_capture_pack (tree decl)
18574 /* We handle normal pack captures by forwarding to the specialization of the
18575 captured parameter. We can't do that for pack init-captures; we need them
18576 to have their own local_specialization. We created the individual
18577 VAR_DECLs (if any) under build_capture_proxy, and we need to collect them
18578 when we process the DECL_EXPR for the pack init-capture in the template.
18579 So, how do we find them? We don't know the capture proxy pack when
18580 building the individual resulting proxies, and we don't know the
18581 individual proxies when instantiating the pack. What we have in common is
18582 the FIELD_DECL.
18584 So...when we instantiate the FIELD_DECL, we stick the result in
18585 local_specializations. Then at the DECL_EXPR we look up that result, see
18586 how many elements it has, synthesize the names, and look them up. */
18588 tree cname = DECL_NAME (decl);
18589 tree val = DECL_VALUE_EXPR (decl);
18590 tree field = TREE_OPERAND (val, 1);
18591 gcc_assert (TREE_CODE (field) == FIELD_DECL);
18592 tree fpack = retrieve_local_specialization (field);
18593 if (fpack == error_mark_node)
18594 return error_mark_node;
18596 int len = 1;
18597 tree vec = NULL_TREE;
18598 tree r = NULL_TREE;
18599 if (TREE_CODE (fpack) == TREE_VEC)
18601 len = TREE_VEC_LENGTH (fpack);
18602 vec = make_tree_vec (len);
18603 r = make_node (NONTYPE_ARGUMENT_PACK);
18604 ARGUMENT_PACK_ARGS (r) = vec;
18606 for (int i = 0; i < len; ++i)
18608 tree ename = vec ? make_ith_pack_parameter_name (cname, i) : cname;
18609 tree elt = lookup_name (ename);
18610 if (vec)
18611 TREE_VEC_ELT (vec, i) = elt;
18612 else
18613 r = elt;
18615 return r;
18618 /* T is an operand of a template tree being substituted. Return whether
18619 T is dependent such that we should suppress some warnings that would
18620 make sense if the substituted expression were written directly, like
18621 template <int I> bool f() { return I == 2; }
18622 We don't want to warn when instantiating f that comparing two constants
18623 always has the same value.
18625 This is a more limited concept of dependence than instantiation-dependent;
18626 here we don't care whether substitution could fail. */
18628 static bool
18629 dependent_operand_p (tree t)
18631 while (TREE_CODE (t) == IMPLICIT_CONV_EXPR)
18632 t = TREE_OPERAND (t, 0);
18633 ++processing_template_decl;
18634 bool r = (potential_constant_expression (t)
18635 ? value_dependent_expression_p (t)
18636 : type_dependent_expression_p (t));
18637 --processing_template_decl;
18638 return r;
18641 /* Like tsubst_copy for expressions, etc. but also does semantic
18642 processing. */
18644 tree
18645 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
18647 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
18648 #define RECUR(NODE) \
18649 tsubst_expr ((NODE), args, complain, in_decl)
18651 tree stmt, tmp;
18652 tree r;
18653 location_t loc;
18655 if (t == NULL_TREE || t == error_mark_node)
18656 return t;
18658 loc = input_location;
18659 if (location_t eloc = cp_expr_location (t))
18660 input_location = eloc;
18661 if (STATEMENT_CODE_P (TREE_CODE (t)))
18662 current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
18664 switch (TREE_CODE (t))
18666 case STATEMENT_LIST:
18668 for (tree stmt : tsi_range (t))
18669 RECUR (stmt);
18670 break;
18673 case CTOR_INITIALIZER:
18674 finish_mem_initializers (tsubst_initializer_list
18675 (TREE_OPERAND (t, 0), args));
18676 break;
18678 case RETURN_EXPR:
18679 finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
18680 break;
18682 case CO_RETURN_EXPR:
18683 finish_co_return_stmt (input_location, RECUR (TREE_OPERAND (t, 0)));
18684 break;
18686 case CO_YIELD_EXPR:
18687 stmt = finish_co_yield_expr (input_location,
18688 RECUR (TREE_OPERAND (t, 0)));
18689 RETURN (stmt);
18691 case CO_AWAIT_EXPR:
18692 stmt = finish_co_await_expr (input_location,
18693 RECUR (TREE_OPERAND (t, 0)));
18694 RETURN (stmt);
18696 case EXPR_STMT:
18697 tmp = RECUR (EXPR_STMT_EXPR (t));
18698 if (EXPR_STMT_STMT_EXPR_RESULT (t))
18699 finish_stmt_expr_expr (tmp, cur_stmt_expr);
18700 else
18701 finish_expr_stmt (tmp);
18702 break;
18704 case USING_STMT:
18705 finish_using_directive (USING_STMT_NAMESPACE (t), /*attribs=*/NULL_TREE);
18706 break;
18708 case PRECONDITION_STMT:
18709 case POSTCONDITION_STMT:
18710 gcc_unreachable ();
18712 case ASSERTION_STMT:
18714 r = tsubst_contract (NULL_TREE, t, args, complain, in_decl);
18715 if (r != error_mark_node)
18716 add_stmt (r);
18717 RETURN (r);
18719 break;
18721 case DECL_EXPR:
18723 tree decl, pattern_decl;
18724 tree init;
18726 pattern_decl = decl = DECL_EXPR_DECL (t);
18727 if (TREE_CODE (decl) == LABEL_DECL)
18728 finish_label_decl (DECL_NAME (decl));
18729 else if (TREE_CODE (decl) == USING_DECL)
18731 tree scope = USING_DECL_SCOPE (decl);
18732 if (DECL_DEPENDENT_P (decl))
18734 scope = tsubst (scope, args, complain, in_decl);
18735 if (!MAYBE_CLASS_TYPE_P (scope)
18736 && TREE_CODE (scope) != ENUMERAL_TYPE)
18738 if (complain & tf_error)
18739 error_at (DECL_SOURCE_LOCATION (decl), "%qT is not a "
18740 "class, namespace, or enumeration", scope);
18741 return error_mark_node;
18743 finish_nonmember_using_decl (scope, DECL_NAME (decl));
18745 else
18747 /* This is a non-dependent using-decl, and we'll have
18748 used the names it found during template parsing. We do
18749 not want to do the lookup again, because we might not
18750 find the things we found then. */
18751 gcc_checking_assert (scope == tsubst (scope, args,
18752 complain, in_decl));
18753 /* We still need to push the bindings so that we can look up
18754 this name later. */
18755 push_using_decl_bindings (DECL_NAME (decl),
18756 USING_DECL_DECLS (decl));
18759 else if (is_capture_proxy (decl)
18760 && !DECL_TEMPLATE_INSTANTIATION (current_function_decl))
18762 /* We're in tsubst_lambda_expr, we've already inserted a new
18763 capture proxy, so look it up and register it. */
18764 tree inst;
18765 if (!DECL_PACK_P (decl))
18767 inst = lookup_name (DECL_NAME (decl), LOOK_where::BLOCK,
18768 LOOK_want::HIDDEN_LAMBDA);
18769 gcc_assert (inst != decl && is_capture_proxy (inst));
18771 else if (is_normal_capture_proxy (decl))
18773 inst = (retrieve_local_specialization
18774 (DECL_CAPTURED_VARIABLE (decl)));
18775 gcc_assert (TREE_CODE (inst) == NONTYPE_ARGUMENT_PACK
18776 || DECL_PACK_P (inst));
18778 else
18779 inst = lookup_init_capture_pack (decl);
18781 register_local_specialization (inst, decl);
18782 break;
18784 else if (DECL_PRETTY_FUNCTION_P (decl))
18785 decl = make_fname_decl (DECL_SOURCE_LOCATION (decl),
18786 DECL_NAME (decl),
18787 true/*DECL_PRETTY_FUNCTION_P (decl)*/);
18788 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
18789 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
18790 /* Don't copy the old closure; we'll create a new one in
18791 tsubst_lambda_expr. */
18792 break;
18793 else
18795 init = DECL_INITIAL (decl);
18796 decl = tsubst (decl, args, complain, in_decl);
18797 if (decl != error_mark_node)
18799 /* By marking the declaration as instantiated, we avoid
18800 trying to instantiate it. Since instantiate_decl can't
18801 handle local variables, and since we've already done
18802 all that needs to be done, that's the right thing to
18803 do. */
18804 if (VAR_P (decl))
18805 DECL_TEMPLATE_INSTANTIATED (decl) = 1;
18806 if (VAR_P (decl) && !DECL_NAME (decl)
18807 && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
18808 /* Anonymous aggregates are a special case. */
18809 finish_anon_union (decl);
18810 else if (is_capture_proxy (DECL_EXPR_DECL (t)))
18812 DECL_CONTEXT (decl) = current_function_decl;
18813 if (DECL_NAME (decl) == this_identifier)
18815 tree lam = DECL_CONTEXT (current_function_decl);
18816 lam = CLASSTYPE_LAMBDA_EXPR (lam);
18817 LAMBDA_EXPR_THIS_CAPTURE (lam) = decl;
18819 insert_capture_proxy (decl);
18821 else if (DECL_IMPLICIT_TYPEDEF_P (t))
18822 /* We already did a pushtag. */;
18823 else if (VAR_OR_FUNCTION_DECL_P (decl)
18824 && DECL_LOCAL_DECL_P (decl))
18826 if (TREE_CODE (DECL_CONTEXT (decl)) == FUNCTION_DECL)
18827 DECL_CONTEXT (decl) = NULL_TREE;
18828 decl = pushdecl (decl);
18829 if (TREE_CODE (decl) == FUNCTION_DECL
18830 && DECL_OMP_DECLARE_REDUCTION_P (decl)
18831 && cp_check_omp_declare_reduction (decl))
18832 instantiate_body (pattern_decl, args, decl, true);
18834 else
18836 bool const_init = false;
18837 unsigned int cnt = 0;
18838 tree first = NULL_TREE, ndecl = error_mark_node;
18839 tree asmspec_tree = NULL_TREE;
18840 maybe_push_decl (decl);
18842 if (VAR_P (decl)
18843 && DECL_DECOMPOSITION_P (decl)
18844 && TREE_TYPE (pattern_decl) != error_mark_node)
18845 ndecl = tsubst_decomp_names (decl, pattern_decl, args,
18846 complain, in_decl, &first,
18847 &cnt);
18849 init = tsubst_init (init, decl, args, complain, in_decl);
18851 if (VAR_P (decl))
18852 const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
18853 (pattern_decl));
18855 if (ndecl != error_mark_node)
18856 cp_maybe_mangle_decomp (ndecl, first, cnt);
18858 /* In a non-template function, VLA type declarations are
18859 handled in grokdeclarator; for templates, handle them
18860 now. */
18861 predeclare_vla (decl);
18863 if (VAR_P (decl) && DECL_HARD_REGISTER (pattern_decl))
18865 tree id = DECL_ASSEMBLER_NAME (pattern_decl);
18866 const char *asmspec = IDENTIFIER_POINTER (id);
18867 gcc_assert (asmspec[0] == '*');
18868 asmspec_tree
18869 = build_string (IDENTIFIER_LENGTH (id) - 1,
18870 asmspec + 1);
18871 TREE_TYPE (asmspec_tree) = char_array_type_node;
18874 cp_finish_decl (decl, init, const_init, asmspec_tree, 0);
18876 if (ndecl != error_mark_node)
18877 cp_finish_decomp (ndecl, first, cnt);
18882 break;
18885 case FOR_STMT:
18886 stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
18887 RECUR (FOR_INIT_STMT (t));
18888 finish_init_stmt (stmt);
18889 tmp = RECUR (FOR_COND (t));
18890 finish_for_cond (tmp, stmt, false, 0);
18891 tmp = RECUR (FOR_EXPR (t));
18892 finish_for_expr (tmp, stmt);
18894 bool prev = note_iteration_stmt_body_start ();
18895 RECUR (FOR_BODY (t));
18896 note_iteration_stmt_body_end (prev);
18898 finish_for_stmt (stmt);
18899 break;
18901 case RANGE_FOR_STMT:
18903 /* Construct another range_for, if this is not a final
18904 substitution (for inside a generic lambda of a
18905 template). Otherwise convert to a regular for. */
18906 tree decl, expr;
18907 stmt = (processing_template_decl
18908 ? begin_range_for_stmt (NULL_TREE, NULL_TREE)
18909 : begin_for_stmt (NULL_TREE, NULL_TREE));
18910 RECUR (RANGE_FOR_INIT_STMT (t));
18911 decl = RANGE_FOR_DECL (t);
18912 decl = tsubst (decl, args, complain, in_decl);
18913 maybe_push_decl (decl);
18914 expr = RECUR (RANGE_FOR_EXPR (t));
18916 tree decomp_first = NULL_TREE;
18917 unsigned decomp_cnt = 0;
18918 if (VAR_P (decl) && DECL_DECOMPOSITION_P (decl))
18919 decl = tsubst_decomp_names (decl, RANGE_FOR_DECL (t), args,
18920 complain, in_decl,
18921 &decomp_first, &decomp_cnt);
18923 if (processing_template_decl)
18925 RANGE_FOR_IVDEP (stmt) = RANGE_FOR_IVDEP (t);
18926 RANGE_FOR_UNROLL (stmt) = RANGE_FOR_UNROLL (t);
18927 finish_range_for_decl (stmt, decl, expr);
18928 if (decomp_first && decl != error_mark_node)
18929 cp_finish_decomp (decl, decomp_first, decomp_cnt);
18931 else
18933 unsigned short unroll = (RANGE_FOR_UNROLL (t)
18934 ? tree_to_uhwi (RANGE_FOR_UNROLL (t)) : 0);
18935 stmt = cp_convert_range_for (stmt, decl, expr,
18936 decomp_first, decomp_cnt,
18937 RANGE_FOR_IVDEP (t), unroll);
18940 bool prev = note_iteration_stmt_body_start ();
18941 RECUR (RANGE_FOR_BODY (t));
18942 note_iteration_stmt_body_end (prev);
18943 finish_for_stmt (stmt);
18945 break;
18947 case WHILE_STMT:
18948 stmt = begin_while_stmt ();
18949 tmp = RECUR (WHILE_COND (t));
18950 finish_while_stmt_cond (tmp, stmt, false, 0);
18952 bool prev = note_iteration_stmt_body_start ();
18953 RECUR (WHILE_BODY (t));
18954 note_iteration_stmt_body_end (prev);
18956 finish_while_stmt (stmt);
18957 break;
18959 case DO_STMT:
18960 stmt = begin_do_stmt ();
18962 bool prev = note_iteration_stmt_body_start ();
18963 RECUR (DO_BODY (t));
18964 note_iteration_stmt_body_end (prev);
18966 finish_do_body (stmt);
18967 tmp = RECUR (DO_COND (t));
18968 finish_do_stmt (tmp, stmt, false, 0);
18969 break;
18971 case IF_STMT:
18972 stmt = begin_if_stmt ();
18973 IF_STMT_CONSTEXPR_P (stmt) = IF_STMT_CONSTEXPR_P (t);
18974 IF_STMT_CONSTEVAL_P (stmt) = IF_STMT_CONSTEVAL_P (t);
18975 if (IF_STMT_CONSTEXPR_P (t))
18976 args = add_extra_args (IF_STMT_EXTRA_ARGS (t), args, complain, in_decl);
18978 tree cond = IF_COND (t);
18979 bool was_dep = dependent_operand_p (cond);
18980 cond = RECUR (cond);
18981 warning_sentinel s1(warn_address, was_dep);
18982 tmp = finish_if_stmt_cond (cond, stmt);
18984 if (IF_STMT_CONSTEXPR_P (t)
18985 && instantiation_dependent_expression_p (tmp))
18987 /* We're partially instantiating a generic lambda, but the condition
18988 of the constexpr if is still dependent. Don't substitute into the
18989 branches now, just remember the template arguments. */
18990 do_poplevel (IF_SCOPE (stmt));
18991 IF_COND (stmt) = IF_COND (t);
18992 THEN_CLAUSE (stmt) = THEN_CLAUSE (t);
18993 ELSE_CLAUSE (stmt) = ELSE_CLAUSE (t);
18994 IF_STMT_EXTRA_ARGS (stmt) = build_extra_args (t, args, complain);
18995 add_stmt (stmt);
18996 break;
18998 if (IF_STMT_CONSTEXPR_P (t) && integer_zerop (tmp))
18999 /* Don't instantiate the THEN_CLAUSE. */;
19000 else if (IF_STMT_CONSTEVAL_P (t))
19002 bool save_in_consteval_if_p = in_consteval_if_p;
19003 in_consteval_if_p = true;
19004 RECUR (THEN_CLAUSE (t));
19005 in_consteval_if_p = save_in_consteval_if_p;
19007 else
19009 tree folded = fold_non_dependent_expr (tmp, complain);
19010 bool inhibit = integer_zerop (folded);
19011 if (inhibit)
19012 ++c_inhibit_evaluation_warnings;
19013 RECUR (THEN_CLAUSE (t));
19014 if (inhibit)
19015 --c_inhibit_evaluation_warnings;
19017 finish_then_clause (stmt);
19019 if (IF_STMT_CONSTEXPR_P (t) && integer_nonzerop (tmp))
19020 /* Don't instantiate the ELSE_CLAUSE. */;
19021 else if (ELSE_CLAUSE (t))
19023 tree folded = fold_non_dependent_expr (tmp, complain);
19024 bool inhibit = integer_nonzerop (folded);
19025 begin_else_clause (stmt);
19026 if (inhibit)
19027 ++c_inhibit_evaluation_warnings;
19028 RECUR (ELSE_CLAUSE (t));
19029 if (inhibit)
19030 --c_inhibit_evaluation_warnings;
19031 finish_else_clause (stmt);
19034 finish_if_stmt (stmt);
19035 break;
19037 case BIND_EXPR:
19038 if (BIND_EXPR_BODY_BLOCK (t))
19039 stmt = begin_function_body ();
19040 else
19041 stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
19042 ? BCS_TRY_BLOCK : 0);
19044 RECUR (BIND_EXPR_BODY (t));
19046 if (BIND_EXPR_BODY_BLOCK (t))
19047 finish_function_body (stmt);
19048 else
19049 finish_compound_stmt (stmt);
19050 break;
19052 case BREAK_STMT:
19053 finish_break_stmt ();
19054 break;
19056 case CONTINUE_STMT:
19057 finish_continue_stmt ();
19058 break;
19060 case SWITCH_STMT:
19061 stmt = begin_switch_stmt ();
19062 tmp = RECUR (SWITCH_STMT_COND (t));
19063 finish_switch_cond (tmp, stmt);
19064 RECUR (SWITCH_STMT_BODY (t));
19065 finish_switch_stmt (stmt);
19066 break;
19068 case CASE_LABEL_EXPR:
19070 tree decl = CASE_LABEL (t);
19071 tree low = RECUR (CASE_LOW (t));
19072 tree high = RECUR (CASE_HIGH (t));
19073 tree l = finish_case_label (EXPR_LOCATION (t), low, high);
19074 if (l && TREE_CODE (l) == CASE_LABEL_EXPR)
19076 tree label = CASE_LABEL (l);
19077 FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
19078 if (DECL_ATTRIBUTES (decl) != NULL_TREE)
19079 cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
19082 break;
19084 case LABEL_EXPR:
19086 tree decl = LABEL_EXPR_LABEL (t);
19087 tree label;
19089 label = finish_label_stmt (DECL_NAME (decl));
19090 if (TREE_CODE (label) == LABEL_DECL)
19091 FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
19092 if (DECL_ATTRIBUTES (decl) != NULL_TREE)
19093 cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
19095 break;
19097 case GOTO_EXPR:
19098 tmp = GOTO_DESTINATION (t);
19099 if (TREE_CODE (tmp) != LABEL_DECL)
19100 /* Computed goto's must be tsubst'd into. On the other hand,
19101 non-computed gotos must not be; the identifier in question
19102 will have no binding. */
19103 tmp = RECUR (tmp);
19104 else
19105 tmp = DECL_NAME (tmp);
19106 finish_goto_stmt (tmp);
19107 break;
19109 case ASM_EXPR:
19111 tree string = RECUR (ASM_STRING (t));
19112 tree outputs = tsubst_copy_asm_operands (ASM_OUTPUTS (t), args,
19113 complain, in_decl);
19114 tree inputs = tsubst_copy_asm_operands (ASM_INPUTS (t), args,
19115 complain, in_decl);
19116 tree clobbers = tsubst_copy_asm_operands (ASM_CLOBBERS (t), args,
19117 complain, in_decl);
19118 tree labels = tsubst_copy_asm_operands (ASM_LABELS (t), args,
19119 complain, in_decl);
19120 tmp = finish_asm_stmt (EXPR_LOCATION (t), ASM_VOLATILE_P (t), string,
19121 outputs, inputs, clobbers, labels,
19122 ASM_INLINE_P (t));
19123 tree asm_expr = tmp;
19124 if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
19125 asm_expr = TREE_OPERAND (asm_expr, 0);
19126 ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
19128 break;
19130 case TRY_BLOCK:
19131 if (CLEANUP_P (t))
19133 stmt = begin_try_block ();
19134 RECUR (TRY_STMTS (t));
19135 finish_cleanup_try_block (stmt);
19136 finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
19138 else
19140 tree compound_stmt = NULL_TREE;
19142 if (FN_TRY_BLOCK_P (t))
19143 stmt = begin_function_try_block (&compound_stmt);
19144 else
19145 stmt = begin_try_block ();
19147 RECUR (TRY_STMTS (t));
19149 if (FN_TRY_BLOCK_P (t))
19150 finish_function_try_block (stmt);
19151 else
19152 finish_try_block (stmt);
19154 RECUR (TRY_HANDLERS (t));
19155 if (FN_TRY_BLOCK_P (t))
19156 finish_function_handler_sequence (stmt, compound_stmt);
19157 else
19158 finish_handler_sequence (stmt);
19160 break;
19162 case HANDLER:
19164 tree decl = HANDLER_PARMS (t);
19166 if (decl)
19168 decl = tsubst (decl, args, complain, in_decl);
19169 /* Prevent instantiate_decl from trying to instantiate
19170 this variable. We've already done all that needs to be
19171 done. */
19172 if (decl != error_mark_node)
19173 DECL_TEMPLATE_INSTANTIATED (decl) = 1;
19175 stmt = begin_handler ();
19176 finish_handler_parms (decl, stmt);
19177 RECUR (HANDLER_BODY (t));
19178 finish_handler (stmt);
19180 break;
19182 case TAG_DEFN:
19183 tmp = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
19184 if (CLASS_TYPE_P (tmp))
19186 /* Local classes are not independent templates; they are
19187 instantiated along with their containing function. And this
19188 way we don't have to deal with pushing out of one local class
19189 to instantiate a member of another local class. */
19190 /* Closures are handled by the LAMBDA_EXPR. */
19191 gcc_assert (!LAMBDA_TYPE_P (TREE_TYPE (t)));
19192 complete_type (tmp);
19193 for (tree fld = TYPE_FIELDS (tmp); fld; fld = DECL_CHAIN (fld))
19194 if ((VAR_P (fld)
19195 || (TREE_CODE (fld) == FUNCTION_DECL
19196 && !DECL_ARTIFICIAL (fld)))
19197 && DECL_TEMPLATE_INSTANTIATION (fld))
19198 instantiate_decl (fld, /*defer_ok=*/false,
19199 /*expl_inst_class=*/false);
19201 break;
19203 case STATIC_ASSERT:
19205 tree condition;
19207 ++c_inhibit_evaluation_warnings;
19208 condition = tsubst_expr (STATIC_ASSERT_CONDITION (t), args,
19209 complain, in_decl);
19210 --c_inhibit_evaluation_warnings;
19212 finish_static_assert (condition,
19213 STATIC_ASSERT_MESSAGE (t),
19214 STATIC_ASSERT_SOURCE_LOCATION (t),
19215 /*member_p=*/false, /*show_expr_p=*/true);
19217 break;
19219 case OACC_KERNELS:
19220 case OACC_PARALLEL:
19221 case OACC_SERIAL:
19222 tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_ACC, args, complain,
19223 in_decl);
19224 stmt = begin_omp_parallel ();
19225 RECUR (OMP_BODY (t));
19226 finish_omp_construct (TREE_CODE (t), stmt, tmp);
19227 break;
19229 case OMP_PARALLEL:
19230 r = push_omp_privatization_clauses (OMP_PARALLEL_COMBINED (t));
19231 tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t), C_ORT_OMP, args,
19232 complain, in_decl);
19233 if (OMP_PARALLEL_COMBINED (t))
19234 omp_parallel_combined_clauses = &tmp;
19235 stmt = begin_omp_parallel ();
19236 RECUR (OMP_PARALLEL_BODY (t));
19237 gcc_assert (omp_parallel_combined_clauses == NULL);
19238 OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
19239 = OMP_PARALLEL_COMBINED (t);
19240 pop_omp_privatization_clauses (r);
19241 break;
19243 case OMP_TASK:
19244 if (OMP_TASK_BODY (t) == NULL_TREE)
19246 tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
19247 complain, in_decl);
19248 t = copy_node (t);
19249 OMP_TASK_CLAUSES (t) = tmp;
19250 add_stmt (t);
19251 break;
19253 r = push_omp_privatization_clauses (false);
19254 tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
19255 complain, in_decl);
19256 stmt = begin_omp_task ();
19257 RECUR (OMP_TASK_BODY (t));
19258 finish_omp_task (tmp, stmt);
19259 pop_omp_privatization_clauses (r);
19260 break;
19262 case OMP_FOR:
19263 case OMP_LOOP:
19264 case OMP_SIMD:
19265 case OMP_DISTRIBUTE:
19266 case OMP_TASKLOOP:
19267 case OACC_LOOP:
19269 tree clauses, body, pre_body;
19270 tree declv = NULL_TREE, initv = NULL_TREE, condv = NULL_TREE;
19271 tree orig_declv = NULL_TREE;
19272 tree incrv = NULL_TREE;
19273 enum c_omp_region_type ort = C_ORT_OMP;
19274 bool any_range_for = false;
19275 int i;
19277 if (TREE_CODE (t) == OACC_LOOP)
19278 ort = C_ORT_ACC;
19280 r = push_omp_privatization_clauses (OMP_FOR_INIT (t) == NULL_TREE);
19281 clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t), ort, args, complain,
19282 in_decl);
19283 if (OMP_FOR_INIT (t) != NULL_TREE)
19285 declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19286 if (OMP_FOR_ORIG_DECLS (t))
19287 orig_declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19288 initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19289 condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19290 incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19293 keep_next_level (true);
19294 stmt = begin_omp_structured_block ();
19296 pre_body = push_stmt_list ();
19297 RECUR (OMP_FOR_PRE_BODY (t));
19298 pre_body = pop_stmt_list (pre_body);
19300 if (OMP_FOR_INIT (t) != NULL_TREE)
19301 for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
19302 any_range_for
19303 |= tsubst_omp_for_iterator (t, i, declv, orig_declv, initv,
19304 condv, incrv, &clauses, args,
19305 complain, in_decl);
19306 omp_parallel_combined_clauses = NULL;
19308 if (any_range_for)
19310 gcc_assert (orig_declv);
19311 body = begin_omp_structured_block ();
19312 for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
19313 if (TREE_VEC_ELT (orig_declv, i) != TREE_VEC_ELT (declv, i)
19314 && TREE_CODE (TREE_VEC_ELT (orig_declv, i)) == TREE_LIST
19315 && TREE_CHAIN (TREE_VEC_ELT (orig_declv, i)))
19316 cp_finish_omp_range_for (TREE_VEC_ELT (orig_declv, i),
19317 TREE_VEC_ELT (declv, i));
19319 else
19320 body = push_stmt_list ();
19321 RECUR (OMP_FOR_BODY (t));
19322 if (any_range_for)
19323 body = finish_omp_structured_block (body);
19324 else
19325 body = pop_stmt_list (body);
19327 if (OMP_FOR_INIT (t) != NULL_TREE)
19328 t = finish_omp_for (EXPR_LOCATION (t), TREE_CODE (t), declv,
19329 orig_declv, initv, condv, incrv, body, pre_body,
19330 NULL, clauses);
19331 else
19333 t = make_node (TREE_CODE (t));
19334 TREE_TYPE (t) = void_type_node;
19335 OMP_FOR_BODY (t) = body;
19336 OMP_FOR_PRE_BODY (t) = pre_body;
19337 OMP_FOR_CLAUSES (t) = clauses;
19338 SET_EXPR_LOCATION (t, EXPR_LOCATION (t));
19339 add_stmt (t);
19342 add_stmt (finish_omp_for_block (finish_omp_structured_block (stmt),
19343 t));
19344 pop_omp_privatization_clauses (r);
19346 break;
19348 case OMP_SECTIONS:
19349 case OMP_MASKED:
19350 omp_parallel_combined_clauses = NULL;
19351 /* FALLTHRU */
19352 case OMP_SINGLE:
19353 case OMP_SCOPE:
19354 case OMP_TEAMS:
19355 case OMP_CRITICAL:
19356 case OMP_TASKGROUP:
19357 case OMP_SCAN:
19358 r = push_omp_privatization_clauses (TREE_CODE (t) == OMP_TEAMS
19359 && OMP_TEAMS_COMBINED (t));
19360 tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_OMP, args, complain,
19361 in_decl);
19362 if (TREE_CODE (t) == OMP_TEAMS)
19364 keep_next_level (true);
19365 stmt = begin_omp_structured_block ();
19366 RECUR (OMP_BODY (t));
19367 stmt = finish_omp_structured_block (stmt);
19369 else
19371 stmt = push_stmt_list ();
19372 RECUR (OMP_BODY (t));
19373 stmt = pop_stmt_list (stmt);
19376 if (TREE_CODE (t) == OMP_CRITICAL
19377 && tmp != NULL_TREE
19378 && integer_nonzerop (OMP_CLAUSE_HINT_EXPR (tmp)))
19380 error_at (OMP_CLAUSE_LOCATION (tmp),
19381 "%<#pragma omp critical%> with %<hint%> clause requires "
19382 "a name, except when %<omp_sync_hint_none%> is used");
19383 RETURN (error_mark_node);
19385 t = copy_node (t);
19386 OMP_BODY (t) = stmt;
19387 OMP_CLAUSES (t) = tmp;
19388 add_stmt (t);
19389 pop_omp_privatization_clauses (r);
19390 break;
19392 case OMP_DEPOBJ:
19393 r = RECUR (OMP_DEPOBJ_DEPOBJ (t));
19394 if (OMP_DEPOBJ_CLAUSES (t) && OMP_DEPOBJ_CLAUSES (t) != error_mark_node)
19396 enum omp_clause_depend_kind kind = OMP_CLAUSE_DEPEND_INVALID;
19397 if (TREE_CODE (OMP_DEPOBJ_CLAUSES (t)) == OMP_CLAUSE)
19399 tmp = tsubst_omp_clauses (OMP_DEPOBJ_CLAUSES (t), C_ORT_OMP,
19400 args, complain, in_decl);
19401 if (tmp == NULL_TREE)
19402 tmp = error_mark_node;
19404 else
19406 kind = (enum omp_clause_depend_kind)
19407 tree_to_uhwi (OMP_DEPOBJ_CLAUSES (t));
19408 tmp = NULL_TREE;
19410 finish_omp_depobj (EXPR_LOCATION (t), r, kind, tmp);
19412 else
19413 finish_omp_depobj (EXPR_LOCATION (t), r,
19414 OMP_CLAUSE_DEPEND_INVALID,
19415 OMP_DEPOBJ_CLAUSES (t));
19416 break;
19418 case OACC_DATA:
19419 case OMP_TARGET_DATA:
19420 case OMP_TARGET:
19421 tmp = tsubst_omp_clauses (OMP_CLAUSES (t),
19422 TREE_CODE (t) == OACC_DATA
19423 ? C_ORT_ACC
19424 : TREE_CODE (t) == OMP_TARGET
19425 ? C_ORT_OMP_TARGET : C_ORT_OMP,
19426 args, complain, in_decl);
19427 keep_next_level (true);
19428 stmt = begin_omp_structured_block ();
19430 RECUR (OMP_BODY (t));
19431 stmt = finish_omp_structured_block (stmt);
19433 t = copy_node (t);
19434 OMP_BODY (t) = stmt;
19435 OMP_CLAUSES (t) = tmp;
19437 if (TREE_CODE (t) == OMP_TARGET)
19438 finish_omp_target_clauses (EXPR_LOCATION (t), OMP_BODY (t),
19439 &OMP_CLAUSES (t));
19441 if (TREE_CODE (t) == OMP_TARGET && OMP_TARGET_COMBINED (t))
19443 tree teams = cp_walk_tree (&stmt, tsubst_find_omp_teams, NULL, NULL);
19444 if (teams)
19445 /* For combined target teams, ensure the num_teams and
19446 thread_limit clause expressions are evaluated on the host,
19447 before entering the target construct. */
19448 for (tree c = OMP_TEAMS_CLAUSES (teams);
19449 c; c = OMP_CLAUSE_CHAIN (c))
19450 if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS
19451 || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_THREAD_LIMIT)
19452 for (int i = 0;
19453 i <= (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS); ++i)
19454 if (OMP_CLAUSE_OPERAND (c, i)
19455 && TREE_CODE (OMP_CLAUSE_OPERAND (c, i)) != INTEGER_CST)
19457 tree expr = OMP_CLAUSE_OPERAND (c, i);
19458 expr = force_target_expr (TREE_TYPE (expr), expr,
19459 tf_none);
19460 if (expr == error_mark_node)
19461 continue;
19462 tmp = TARGET_EXPR_SLOT (expr);
19463 add_stmt (expr);
19464 OMP_CLAUSE_OPERAND (c, i) = expr;
19465 tree tc = build_omp_clause (OMP_CLAUSE_LOCATION (c),
19466 OMP_CLAUSE_FIRSTPRIVATE);
19467 OMP_CLAUSE_DECL (tc) = tmp;
19468 OMP_CLAUSE_CHAIN (tc) = OMP_TARGET_CLAUSES (t);
19469 OMP_TARGET_CLAUSES (t) = tc;
19472 add_stmt (t);
19473 break;
19475 case OACC_DECLARE:
19476 t = copy_node (t);
19477 tmp = tsubst_omp_clauses (OACC_DECLARE_CLAUSES (t), C_ORT_ACC, args,
19478 complain, in_decl);
19479 OACC_DECLARE_CLAUSES (t) = tmp;
19480 add_stmt (t);
19481 break;
19483 case OMP_TARGET_UPDATE:
19484 case OMP_TARGET_ENTER_DATA:
19485 case OMP_TARGET_EXIT_DATA:
19486 tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_OMP, args,
19487 complain, in_decl);
19488 t = copy_node (t);
19489 OMP_STANDALONE_CLAUSES (t) = tmp;
19490 add_stmt (t);
19491 break;
19493 case OACC_CACHE:
19494 case OACC_ENTER_DATA:
19495 case OACC_EXIT_DATA:
19496 case OACC_UPDATE:
19497 tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_ACC, args,
19498 complain, in_decl);
19499 t = copy_node (t);
19500 OMP_STANDALONE_CLAUSES (t) = tmp;
19501 add_stmt (t);
19502 break;
19504 case OMP_ORDERED:
19505 tmp = tsubst_omp_clauses (OMP_ORDERED_CLAUSES (t), C_ORT_OMP, args,
19506 complain, in_decl);
19507 if (OMP_BODY (t))
19509 stmt = push_stmt_list ();
19510 RECUR (OMP_BODY (t));
19511 stmt = pop_stmt_list (stmt);
19513 else
19514 stmt = NULL_TREE;
19516 t = copy_node (t);
19517 OMP_BODY (t) = stmt;
19518 OMP_ORDERED_CLAUSES (t) = tmp;
19519 add_stmt (t);
19520 break;
19522 case OMP_MASTER:
19523 omp_parallel_combined_clauses = NULL;
19524 /* FALLTHRU */
19525 case OMP_SECTION:
19526 stmt = push_stmt_list ();
19527 RECUR (OMP_BODY (t));
19528 stmt = pop_stmt_list (stmt);
19530 t = copy_node (t);
19531 OMP_BODY (t) = stmt;
19532 add_stmt (t);
19533 break;
19535 case OMP_ATOMIC:
19536 gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
19537 tmp = NULL_TREE;
19538 if (TREE_CODE (TREE_OPERAND (t, 0)) == OMP_CLAUSE)
19539 tmp = tsubst_omp_clauses (TREE_OPERAND (t, 0), C_ORT_OMP, args,
19540 complain, in_decl);
19541 if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
19543 tree op1 = TREE_OPERAND (t, 1);
19544 tree rhs1 = NULL_TREE;
19545 tree r = NULL_TREE;
19546 tree lhs, rhs;
19547 if (TREE_CODE (op1) == COMPOUND_EXPR)
19549 rhs1 = RECUR (TREE_OPERAND (op1, 0));
19550 op1 = TREE_OPERAND (op1, 1);
19552 if (TREE_CODE (op1) == COND_EXPR)
19554 gcc_assert (rhs1 == NULL_TREE);
19555 tree c = TREE_OPERAND (op1, 0);
19556 if (TREE_CODE (c) == MODIFY_EXPR)
19558 r = RECUR (TREE_OPERAND (c, 0));
19559 c = TREE_OPERAND (c, 1);
19561 gcc_assert (TREE_CODE (c) == EQ_EXPR);
19562 rhs = RECUR (TREE_OPERAND (c, 1));
19563 lhs = RECUR (TREE_OPERAND (op1, 2));
19564 rhs1 = RECUR (TREE_OPERAND (op1, 1));
19566 else
19568 lhs = RECUR (TREE_OPERAND (op1, 0));
19569 rhs = RECUR (TREE_OPERAND (op1, 1));
19571 finish_omp_atomic (EXPR_LOCATION (t), OMP_ATOMIC, TREE_CODE (op1),
19572 lhs, rhs, NULL_TREE, NULL_TREE, rhs1, r,
19573 tmp, OMP_ATOMIC_MEMORY_ORDER (t),
19574 OMP_ATOMIC_WEAK (t));
19576 else
19578 tree op1 = TREE_OPERAND (t, 1);
19579 tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
19580 tree rhs1 = NULL_TREE, r = NULL_TREE;
19581 enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
19582 enum tree_code opcode = NOP_EXPR;
19583 if (code == OMP_ATOMIC_READ)
19585 v = RECUR (TREE_OPERAND (op1, 0));
19586 lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
19588 else if (code == OMP_ATOMIC_CAPTURE_OLD
19589 || code == OMP_ATOMIC_CAPTURE_NEW)
19591 tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
19592 v = RECUR (TREE_OPERAND (op1, 0));
19593 lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
19594 if (TREE_CODE (op11) == COMPOUND_EXPR)
19596 rhs1 = RECUR (TREE_OPERAND (op11, 0));
19597 op11 = TREE_OPERAND (op11, 1);
19599 if (TREE_CODE (op11) == COND_EXPR)
19601 gcc_assert (rhs1 == NULL_TREE);
19602 tree c = TREE_OPERAND (op11, 0);
19603 if (TREE_CODE (c) == MODIFY_EXPR)
19605 r = RECUR (TREE_OPERAND (c, 0));
19606 c = TREE_OPERAND (c, 1);
19608 gcc_assert (TREE_CODE (c) == EQ_EXPR);
19609 rhs = RECUR (TREE_OPERAND (c, 1));
19610 lhs = RECUR (TREE_OPERAND (op11, 2));
19611 rhs1 = RECUR (TREE_OPERAND (op11, 1));
19613 else
19615 lhs = RECUR (TREE_OPERAND (op11, 0));
19616 rhs = RECUR (TREE_OPERAND (op11, 1));
19618 opcode = TREE_CODE (op11);
19619 if (opcode == MODIFY_EXPR)
19620 opcode = NOP_EXPR;
19622 else
19624 code = OMP_ATOMIC;
19625 lhs = RECUR (TREE_OPERAND (op1, 0));
19626 rhs = RECUR (TREE_OPERAND (op1, 1));
19628 finish_omp_atomic (EXPR_LOCATION (t), code, opcode, lhs, rhs, v,
19629 lhs1, rhs1, r, tmp,
19630 OMP_ATOMIC_MEMORY_ORDER (t), OMP_ATOMIC_WEAK (t));
19632 break;
19634 case TRANSACTION_EXPR:
19636 int flags = 0;
19637 flags |= (TRANSACTION_EXPR_OUTER (t) ? TM_STMT_ATTR_OUTER : 0);
19638 flags |= (TRANSACTION_EXPR_RELAXED (t) ? TM_STMT_ATTR_RELAXED : 0);
19640 if (TRANSACTION_EXPR_IS_STMT (t))
19642 tree body = TRANSACTION_EXPR_BODY (t);
19643 tree noex = NULL_TREE;
19644 if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
19646 noex = MUST_NOT_THROW_COND (body);
19647 if (noex == NULL_TREE)
19648 noex = boolean_true_node;
19649 body = TREE_OPERAND (body, 0);
19651 stmt = begin_transaction_stmt (input_location, NULL, flags);
19652 RECUR (body);
19653 finish_transaction_stmt (stmt, NULL, flags, RECUR (noex));
19655 else
19657 stmt = build_transaction_expr (EXPR_LOCATION (t),
19658 RECUR (TRANSACTION_EXPR_BODY (t)),
19659 flags, NULL_TREE);
19660 RETURN (stmt);
19663 break;
19665 case MUST_NOT_THROW_EXPR:
19667 tree op0 = RECUR (TREE_OPERAND (t, 0));
19668 tree cond = RECUR (MUST_NOT_THROW_COND (t));
19669 RETURN (build_must_not_throw_expr (op0, cond));
19672 case EXPR_PACK_EXPANSION:
19673 error ("invalid use of pack expansion expression");
19674 RETURN (error_mark_node);
19676 case NONTYPE_ARGUMENT_PACK:
19677 error ("use %<...%> to expand argument pack");
19678 RETURN (error_mark_node);
19680 case COMPOUND_EXPR:
19681 tmp = RECUR (TREE_OPERAND (t, 0));
19682 if (tmp == NULL_TREE)
19683 /* If the first operand was a statement, we're done with it. */
19684 RETURN (RECUR (TREE_OPERAND (t, 1)));
19685 RETURN (build_x_compound_expr (EXPR_LOCATION (t), tmp,
19686 RECUR (TREE_OPERAND (t, 1)),
19687 templated_operator_saved_lookups (t),
19688 complain));
19690 case ANNOTATE_EXPR:
19691 tmp = RECUR (TREE_OPERAND (t, 0));
19692 RETURN (build3_loc (EXPR_LOCATION (t), ANNOTATE_EXPR,
19693 TREE_TYPE (tmp), tmp,
19694 RECUR (TREE_OPERAND (t, 1)),
19695 RECUR (TREE_OPERAND (t, 2))));
19697 case PREDICT_EXPR:
19698 RETURN (add_stmt (copy_node (t)));
19700 default:
19701 gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
19703 RETURN (tsubst_copy_and_build (t, args, complain, in_decl));
19706 RETURN (NULL_TREE);
19707 out:
19708 input_location = loc;
19709 return r;
19710 #undef RECUR
19711 #undef RETURN
19714 /* Instantiate the special body of the artificial DECL_OMP_DECLARE_REDUCTION
19715 function. For description of the body see comment above
19716 cp_parser_omp_declare_reduction_exprs. */
19718 static void
19719 tsubst_omp_udr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
19721 if (t == NULL_TREE || t == error_mark_node)
19722 return;
19724 gcc_assert (TREE_CODE (t) == STATEMENT_LIST && current_function_decl);
19726 tree_stmt_iterator tsi;
19727 int i;
19728 tree stmts[7];
19729 memset (stmts, 0, sizeof stmts);
19730 for (i = 0, tsi = tsi_start (t);
19731 i < 7 && !tsi_end_p (tsi);
19732 i++, tsi_next (&tsi))
19733 stmts[i] = tsi_stmt (tsi);
19734 gcc_assert (tsi_end_p (tsi));
19736 if (i >= 3)
19738 gcc_assert (TREE_CODE (stmts[0]) == DECL_EXPR
19739 && TREE_CODE (stmts[1]) == DECL_EXPR);
19740 tree omp_out = tsubst (DECL_EXPR_DECL (stmts[0]),
19741 args, complain, in_decl);
19742 tree omp_in = tsubst (DECL_EXPR_DECL (stmts[1]),
19743 args, complain, in_decl);
19744 /* tsubsting a local var_decl leaves DECL_CONTEXT null, as we
19745 expect to be pushing it. */
19746 DECL_CONTEXT (omp_out) = current_function_decl;
19747 DECL_CONTEXT (omp_in) = current_function_decl;
19748 keep_next_level (true);
19749 tree block = begin_omp_structured_block ();
19750 tsubst_expr (stmts[2], args, complain, in_decl);
19751 block = finish_omp_structured_block (block);
19752 block = maybe_cleanup_point_expr_void (block);
19753 add_decl_expr (omp_out);
19754 copy_warning (omp_out, DECL_EXPR_DECL (stmts[0]));
19755 add_decl_expr (omp_in);
19756 finish_expr_stmt (block);
19758 if (i >= 6)
19760 gcc_assert (TREE_CODE (stmts[3]) == DECL_EXPR
19761 && TREE_CODE (stmts[4]) == DECL_EXPR);
19762 tree omp_priv = tsubst (DECL_EXPR_DECL (stmts[3]),
19763 args, complain, in_decl);
19764 tree omp_orig = tsubst (DECL_EXPR_DECL (stmts[4]),
19765 args, complain, in_decl);
19766 DECL_CONTEXT (omp_priv) = current_function_decl;
19767 DECL_CONTEXT (omp_orig) = current_function_decl;
19768 keep_next_level (true);
19769 tree block = begin_omp_structured_block ();
19770 tsubst_expr (stmts[5], args, complain, in_decl);
19771 block = finish_omp_structured_block (block);
19772 block = maybe_cleanup_point_expr_void (block);
19773 cp_walk_tree (&block, cp_remove_omp_priv_cleanup_stmt, omp_priv, NULL);
19774 add_decl_expr (omp_priv);
19775 add_decl_expr (omp_orig);
19776 finish_expr_stmt (block);
19777 if (i == 7)
19778 add_decl_expr (omp_orig);
19782 /* T is a postfix-expression that is not being used in a function
19783 call. Return the substituted version of T. */
19785 static tree
19786 tsubst_non_call_postfix_expression (tree t, tree args,
19787 tsubst_flags_t complain,
19788 tree in_decl)
19790 if (TREE_CODE (t) == SCOPE_REF)
19791 t = tsubst_qualified_id (t, args, complain, in_decl,
19792 /*done=*/false, /*address_p=*/false);
19793 else
19794 t = tsubst_copy_and_build (t, args, complain, in_decl);
19796 return t;
19799 /* Subroutine of tsubst_lambda_expr: add the FIELD/INIT capture pair to the
19800 LAMBDA_EXPR_CAPTURE_LIST passed in LIST. Do deduction for a previously
19801 dependent init-capture. */
19803 static void
19804 prepend_one_capture (tree field, tree init, tree &list,
19805 tsubst_flags_t complain)
19807 if (tree auto_node = type_uses_auto (TREE_TYPE (field)))
19809 tree type = NULL_TREE;
19810 if (!init)
19812 if (complain & tf_error)
19813 error ("empty initializer in lambda init-capture");
19814 init = error_mark_node;
19816 else if (TREE_CODE (init) == TREE_LIST)
19817 init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
19818 if (!type)
19819 type = do_auto_deduction (TREE_TYPE (field), init, auto_node, complain);
19820 TREE_TYPE (field) = type;
19821 cp_apply_type_quals_to_decl (cp_type_quals (type), field);
19823 list = tree_cons (field, init, list);
19826 /* T is a LAMBDA_EXPR. Generate a new LAMBDA_EXPR for the current
19827 instantiation context. Instantiating a pack expansion containing a lambda
19828 might result in multiple lambdas all based on the same lambda in the
19829 template. */
19831 tree
19832 tsubst_lambda_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
19834 tree oldfn = lambda_function (t);
19835 in_decl = oldfn;
19837 tree r = build_lambda_expr ();
19839 LAMBDA_EXPR_LOCATION (r)
19840 = LAMBDA_EXPR_LOCATION (t);
19841 LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
19842 = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
19843 LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
19844 if (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
19845 LAMBDA_EXPR_REGEN_INFO (r)
19846 = build_template_info (t, add_to_template_args (TI_ARGS (ti),
19847 preserve_args (args)));
19848 else
19849 LAMBDA_EXPR_REGEN_INFO (r)
19850 = build_template_info (t, preserve_args (args));
19852 gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
19853 && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
19855 vec<tree,va_gc>* field_packs = NULL;
19857 for (tree cap = LAMBDA_EXPR_CAPTURE_LIST (t); cap;
19858 cap = TREE_CHAIN (cap))
19860 tree ofield = TREE_PURPOSE (cap);
19861 tree init = TREE_VALUE (cap);
19862 if (PACK_EXPANSION_P (init))
19863 init = tsubst_pack_expansion (init, args, complain, in_decl);
19864 else
19865 init = tsubst_copy_and_build (init, args, complain, in_decl);
19867 if (init == error_mark_node)
19868 return error_mark_node;
19870 if (init && TREE_CODE (init) == TREE_LIST)
19871 init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
19873 if (!processing_template_decl
19874 && init && TREE_CODE (init) != TREE_VEC
19875 && variably_modified_type_p (TREE_TYPE (init), NULL_TREE))
19877 /* For a VLA, simply tsubsting the field type won't work, we need to
19878 go through add_capture again. XXX do we want to do this for all
19879 captures? */
19880 tree name = (get_identifier
19881 (IDENTIFIER_POINTER (DECL_NAME (ofield)) + 2));
19882 tree ftype = TREE_TYPE (ofield);
19883 bool by_ref = (TYPE_REF_P (ftype)
19884 || (TREE_CODE (ftype) == DECLTYPE_TYPE
19885 && DECLTYPE_FOR_REF_CAPTURE (ftype)));
19886 add_capture (r, name, init, by_ref, !DECL_NORMAL_CAPTURE_P (ofield));
19887 continue;
19890 if (PACK_EXPANSION_P (ofield))
19891 ofield = PACK_EXPANSION_PATTERN (ofield);
19892 tree field = tsubst_decl (ofield, args, complain);
19894 if (DECL_PACK_P (ofield) && !DECL_NORMAL_CAPTURE_P (ofield))
19896 /* Remember these for when we've pushed local_specializations. */
19897 vec_safe_push (field_packs, ofield);
19898 vec_safe_push (field_packs, field);
19901 if (field == error_mark_node)
19902 return error_mark_node;
19904 if (TREE_CODE (field) == TREE_VEC)
19906 int len = TREE_VEC_LENGTH (field);
19907 gcc_assert (TREE_CODE (init) == TREE_VEC
19908 && TREE_VEC_LENGTH (init) == len);
19909 for (int i = 0; i < len; ++i)
19910 prepend_one_capture (TREE_VEC_ELT (field, i),
19911 TREE_VEC_ELT (init, i),
19912 LAMBDA_EXPR_CAPTURE_LIST (r),
19913 complain);
19915 else
19917 prepend_one_capture (field, init, LAMBDA_EXPR_CAPTURE_LIST (r),
19918 complain);
19920 if (id_equal (DECL_NAME (field), "__this"))
19921 LAMBDA_EXPR_THIS_CAPTURE (r) = field;
19925 tree type = begin_lambda_type (r);
19926 if (type == error_mark_node)
19927 return error_mark_node;
19929 if (LAMBDA_EXPR_EXTRA_SCOPE (t))
19930 record_lambda_scope (r);
19931 else if (TYPE_NAMESPACE_SCOPE_P (TREE_TYPE (t)))
19932 /* If we're pushed into another scope (PR105652), fix it. */
19933 TYPE_CONTEXT (type) = DECL_CONTEXT (TYPE_NAME (type))
19934 = TYPE_CONTEXT (TREE_TYPE (t));
19935 record_lambda_scope_discriminator (r);
19937 /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set. */
19938 determine_visibility (TYPE_NAME (type));
19940 register_capture_members (LAMBDA_EXPR_CAPTURE_LIST (r));
19942 tree oldtmpl = (generic_lambda_fn_p (oldfn)
19943 ? DECL_TI_TEMPLATE (oldfn)
19944 : NULL_TREE);
19946 tree fntype = static_fn_type (oldfn);
19947 if (oldtmpl)
19948 ++processing_template_decl;
19949 fntype = tsubst (fntype, args, complain, in_decl);
19950 if (oldtmpl)
19951 --processing_template_decl;
19953 if (fntype == error_mark_node)
19954 r = error_mark_node;
19955 else
19957 /* The body of a lambda-expression is not a subexpression of the
19958 enclosing expression. Parms are to have DECL_CHAIN tsubsted,
19959 which would be skipped if cp_unevaluated_operand. */
19960 cp_evaluated ev;
19962 /* Fix the type of 'this'. */
19963 fntype = build_memfn_type (fntype, type,
19964 type_memfn_quals (fntype),
19965 type_memfn_rqual (fntype));
19966 tree inst = (oldtmpl
19967 ? tsubst_template_decl (oldtmpl, args, complain, fntype)
19968 : tsubst_function_decl (oldfn, args, complain, fntype));
19969 if (inst == error_mark_node)
19971 r = error_mark_node;
19972 goto out;
19974 finish_member_declaration (inst);
19975 record_lambda_scope_sig_discriminator (r, inst);
19977 tree fn = oldtmpl ? DECL_TEMPLATE_RESULT (inst) : inst;
19979 /* Let finish_function set this. */
19980 DECL_DECLARED_CONSTEXPR_P (fn) = false;
19982 bool nested = cfun;
19983 if (nested)
19984 push_function_context ();
19985 else
19986 /* Still increment function_depth so that we don't GC in the
19987 middle of an expression. */
19988 ++function_depth;
19990 local_specialization_stack s (lss_copy);
19992 bool save_in_consteval_if_p = in_consteval_if_p;
19993 in_consteval_if_p = false;
19995 tree body = start_lambda_function (fn, r);
19997 /* Now record them for lookup_init_capture_pack. */
19998 int fplen = vec_safe_length (field_packs);
19999 for (int i = 0; i < fplen; )
20001 tree pack = (*field_packs)[i++];
20002 tree inst = (*field_packs)[i++];
20003 register_local_specialization (inst, pack);
20005 release_tree_vector (field_packs);
20007 register_parameter_specializations (oldfn, fn);
20009 if (oldtmpl)
20011 /* We might not partially instantiate some parts of the function, so
20012 copy these flags from the original template. */
20013 language_function *ol = DECL_STRUCT_FUNCTION (oldfn)->language;
20014 current_function_returns_value = ol->returns_value;
20015 current_function_returns_null = ol->returns_null;
20016 current_function_returns_abnormally = ol->returns_abnormally;
20017 current_function_infinite_loop = ol->infinite_loop;
20020 /* [temp.deduct] A lambda-expression appearing in a function type or a
20021 template parameter is not considered part of the immediate context for
20022 the purposes of template argument deduction. */
20023 complain = tf_warning_or_error;
20025 tree saved = DECL_SAVED_TREE (oldfn);
20026 if (TREE_CODE (saved) == BIND_EXPR && BIND_EXPR_BODY_BLOCK (saved))
20027 /* We already have a body block from start_lambda_function, we don't
20028 need another to confuse NRV (91217). */
20029 saved = BIND_EXPR_BODY (saved);
20031 tsubst_expr (saved, args, complain, r);
20033 finish_lambda_function (body);
20035 in_consteval_if_p = save_in_consteval_if_p;
20037 if (nested)
20038 pop_function_context ();
20039 else
20040 --function_depth;
20042 /* The capture list was built up in reverse order; fix that now. */
20043 LAMBDA_EXPR_CAPTURE_LIST (r)
20044 = nreverse (LAMBDA_EXPR_CAPTURE_LIST (r));
20046 LAMBDA_EXPR_THIS_CAPTURE (r) = NULL_TREE;
20048 maybe_add_lambda_conv_op (type);
20051 out:
20052 finish_struct (type, /*attr*/NULL_TREE);
20054 insert_pending_capture_proxies ();
20056 return r;
20059 /* Subroutine of maybe_fold_fn_template_args. */
20061 static bool
20062 fold_targs_r (tree targs, tsubst_flags_t complain)
20064 int len = TREE_VEC_LENGTH (targs);
20065 for (int i = 0; i < len; ++i)
20067 tree &elt = TREE_VEC_ELT (targs, i);
20068 if (!elt || TYPE_P (elt)
20069 || TREE_CODE (elt) == TEMPLATE_DECL)
20070 continue;
20071 if (TREE_CODE (elt) == NONTYPE_ARGUMENT_PACK)
20073 if (!fold_targs_r (ARGUMENT_PACK_ARGS (elt), complain))
20074 return false;
20076 else if (/* We can only safely preevaluate scalar prvalues. */
20077 SCALAR_TYPE_P (TREE_TYPE (elt))
20078 && !glvalue_p (elt)
20079 && !TREE_CONSTANT (elt))
20081 elt = cxx_constant_value (elt, complain);
20082 if (elt == error_mark_node)
20083 return false;
20087 return true;
20090 /* Try to do constant evaluation of any explicit template arguments in FN
20091 before overload resolution, to get any errors only once. Return true iff
20092 we didn't have any problems folding. */
20094 static bool
20095 maybe_fold_fn_template_args (tree fn, tsubst_flags_t complain)
20097 if (processing_template_decl || fn == NULL_TREE)
20098 return true;
20099 if (fn == error_mark_node)
20100 return false;
20101 if (TREE_CODE (fn) == OFFSET_REF
20102 || TREE_CODE (fn) == COMPONENT_REF)
20103 fn = TREE_OPERAND (fn, 1);
20104 if (BASELINK_P (fn))
20105 fn = BASELINK_FUNCTIONS (fn);
20106 if (TREE_CODE (fn) != TEMPLATE_ID_EXPR)
20107 return true;
20108 tree targs = TREE_OPERAND (fn, 1);
20109 if (targs == NULL_TREE)
20110 return true;
20111 if (targs == error_mark_node)
20112 return false;
20113 return fold_targs_r (targs, complain);
20116 /* Helper function for tsubst_copy_and_build CALL_EXPR and ARRAY_REF
20117 handling. */
20119 static void
20120 tsubst_copy_and_build_call_args (tree t, tree args, tsubst_flags_t complain,
20121 tree in_decl, releasing_vec &call_args)
20123 unsigned int nargs = call_expr_nargs (t);
20124 for (unsigned int i = 0; i < nargs; ++i)
20126 tree arg = CALL_EXPR_ARG (t, i);
20128 if (!PACK_EXPANSION_P (arg))
20129 vec_safe_push (call_args,
20130 tsubst_copy_and_build (arg, args, complain, in_decl));
20131 else
20133 /* Expand the pack expansion and push each entry onto CALL_ARGS. */
20134 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
20135 if (TREE_CODE (arg) == TREE_VEC)
20137 unsigned int len, j;
20139 len = TREE_VEC_LENGTH (arg);
20140 for (j = 0; j < len; ++j)
20142 tree value = TREE_VEC_ELT (arg, j);
20143 if (value != NULL_TREE)
20144 value = convert_from_reference (value);
20145 vec_safe_push (call_args, value);
20148 else
20149 /* A partial substitution. Add one entry. */
20150 vec_safe_push (call_args, arg);
20155 /* Like tsubst but deals with expressions and performs semantic
20156 analysis. */
20158 tree
20159 tsubst_copy_and_build (tree t,
20160 tree args,
20161 tsubst_flags_t complain,
20162 tree in_decl)
20164 #define RETURN(EXP) do { retval = (EXP); goto out; } while(0)
20165 #define RECUR(NODE) \
20166 tsubst_copy_and_build (NODE, args, complain, in_decl)
20168 tree retval, op1;
20169 location_t save_loc;
20171 if (t == NULL_TREE || t == error_mark_node)
20172 return t;
20174 save_loc = input_location;
20175 if (location_t eloc = cp_expr_location (t))
20176 input_location = eloc;
20178 /* N3276 decltype magic only applies to calls at the top level or on the
20179 right side of a comma. */
20180 tsubst_flags_t decltype_flag = (complain & tf_decltype);
20181 complain &= ~tf_decltype;
20183 switch (TREE_CODE (t))
20185 case USING_DECL:
20186 t = DECL_NAME (t);
20187 /* Fall through. */
20188 case IDENTIFIER_NODE:
20190 tree decl;
20191 cp_id_kind idk;
20192 const char *error_msg;
20194 if (IDENTIFIER_CONV_OP_P (t))
20196 tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20197 t = make_conv_op_name (new_type);
20200 /* Look up the name. */
20201 decl = lookup_name (t);
20203 /* By convention, expressions use ERROR_MARK_NODE to indicate
20204 failure, not NULL_TREE. */
20205 if (decl == NULL_TREE)
20206 decl = error_mark_node;
20208 decl = finish_id_expression (t, decl, NULL_TREE,
20209 &idk,
20210 /*i_c_e_p=*/false,
20211 /*allow_i_c_e_p=*/true,
20212 /*non_i_c_e_p=*/nullptr,
20213 /*template_p=*/false,
20214 /*done=*/true,
20215 /*address_p=*/false,
20216 /*template_arg_p=*/false,
20217 &error_msg,
20218 input_location);
20219 if (error_msg)
20220 error (error_msg);
20221 if (identifier_p (decl))
20223 if (complain & tf_error)
20224 unqualified_name_lookup_error (decl);
20225 decl = error_mark_node;
20227 RETURN (decl);
20230 case TEMPLATE_ID_EXPR:
20232 tree object;
20233 tree templ = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
20234 complain, in_decl);
20235 tree targs = TREE_OPERAND (t, 1);
20237 if (targs)
20238 targs = tsubst_template_args (targs, args, complain, in_decl);
20239 if (targs == error_mark_node)
20240 RETURN (error_mark_node);
20242 if (TREE_CODE (templ) == SCOPE_REF)
20244 tree name = TREE_OPERAND (templ, 1);
20245 tree tid = lookup_template_function (name, targs);
20246 TREE_OPERAND (templ, 1) = tid;
20247 RETURN (templ);
20250 if (concept_definition_p (templ))
20252 tree check = build_concept_check (templ, targs, complain);
20253 if (check == error_mark_node)
20254 RETURN (error_mark_node);
20256 tree id = unpack_concept_check (check);
20258 /* If we built a function concept check, return the underlying
20259 template-id. So we can evaluate it as a function call. */
20260 if (function_concept_p (TREE_OPERAND (id, 0)))
20261 RETURN (id);
20263 RETURN (check);
20266 if (variable_template_p (templ))
20268 tree r = lookup_and_finish_template_variable (templ, targs,
20269 complain);
20270 r = maybe_wrap_with_location (r, EXPR_LOCATION (t));
20271 RETURN (r);
20274 if (TREE_CODE (templ) == COMPONENT_REF)
20276 object = TREE_OPERAND (templ, 0);
20277 templ = TREE_OPERAND (templ, 1);
20279 else
20280 object = NULL_TREE;
20282 tree tid = lookup_template_function (templ, targs);
20283 protected_set_expr_location (tid, EXPR_LOCATION (t));
20285 if (object)
20286 RETURN (build3 (COMPONENT_REF, TREE_TYPE (tid),
20287 object, tid, NULL_TREE));
20288 else if (identifier_p (templ))
20290 /* C++20 P0846: we can encounter an IDENTIFIER_NODE here when
20291 name lookup found nothing when parsing the template name. */
20292 gcc_assert (cxx_dialect >= cxx20 || seen_error ());
20293 RETURN (tid);
20295 else
20296 RETURN (baselink_for_fns (tid));
20299 case INDIRECT_REF:
20301 tree r = RECUR (TREE_OPERAND (t, 0));
20303 if (REFERENCE_REF_P (t))
20305 /* A type conversion to reference type will be enclosed in
20306 such an indirect ref, but the substitution of the cast
20307 will have also added such an indirect ref. */
20308 r = convert_from_reference (r);
20310 else
20311 r = build_x_indirect_ref (input_location, r, RO_UNARY_STAR,
20312 templated_operator_saved_lookups (t),
20313 complain|decltype_flag);
20315 if (REF_PARENTHESIZED_P (t))
20316 r = force_paren_expr (r);
20318 RETURN (r);
20321 case NOP_EXPR:
20323 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20324 tree op0 = RECUR (TREE_OPERAND (t, 0));
20325 RETURN (build_nop (type, op0));
20328 case IMPLICIT_CONV_EXPR:
20330 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20331 tree expr = RECUR (TREE_OPERAND (t, 0));
20332 if (dependent_type_p (type) || type_dependent_expression_p (expr))
20334 retval = copy_node (t);
20335 TREE_TYPE (retval) = type;
20336 TREE_OPERAND (retval, 0) = expr;
20337 RETURN (retval);
20339 if (IMPLICIT_CONV_EXPR_NONTYPE_ARG (t))
20340 /* We'll pass this to convert_nontype_argument again, we don't need
20341 to actually perform any conversion here. */
20342 RETURN (expr);
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 PREDECREMENT_EXPR:
20422 case PREINCREMENT_EXPR:
20423 case NEGATE_EXPR:
20424 case BIT_NOT_EXPR:
20425 case ABS_EXPR:
20426 case TRUTH_NOT_EXPR:
20427 case UNARY_PLUS_EXPR: /* Unary + */
20428 case REALPART_EXPR:
20429 case IMAGPART_EXPR:
20430 RETURN (build_x_unary_op (input_location, TREE_CODE (t),
20431 RECUR (TREE_OPERAND (t, 0)),
20432 templated_operator_saved_lookups (t),
20433 complain|decltype_flag));
20435 case EXCESS_PRECISION_EXPR:
20437 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20438 tree op0 = RECUR (TREE_OPERAND (t, 0));
20439 if (TREE_CODE (op0) == EXCESS_PRECISION_EXPR)
20440 RETURN (op0);
20441 RETURN (build1_loc (EXPR_LOCATION (t), EXCESS_PRECISION_EXPR,
20442 type, op0));
20445 case FIX_TRUNC_EXPR:
20446 /* convert_like should have created an IMPLICIT_CONV_EXPR. */
20447 gcc_unreachable ();
20449 case ADDR_EXPR:
20450 op1 = TREE_OPERAND (t, 0);
20451 if (TREE_CODE (op1) == LABEL_DECL)
20452 RETURN (finish_label_address_expr (DECL_NAME (op1),
20453 EXPR_LOCATION (op1)));
20454 if (TREE_CODE (op1) == SCOPE_REF)
20455 op1 = tsubst_qualified_id (op1, args, complain, in_decl,
20456 /*done=*/true, /*address_p=*/true);
20457 else
20458 op1 = tsubst_non_call_postfix_expression (op1, args, complain,
20459 in_decl);
20460 RETURN (build_x_unary_op (input_location, ADDR_EXPR, op1,
20461 templated_operator_saved_lookups (t),
20462 complain|decltype_flag));
20464 case PLUS_EXPR:
20465 case MINUS_EXPR:
20466 case MULT_EXPR:
20467 case TRUNC_DIV_EXPR:
20468 case CEIL_DIV_EXPR:
20469 case FLOOR_DIV_EXPR:
20470 case ROUND_DIV_EXPR:
20471 case EXACT_DIV_EXPR:
20472 case BIT_AND_EXPR:
20473 case BIT_IOR_EXPR:
20474 case BIT_XOR_EXPR:
20475 case TRUNC_MOD_EXPR:
20476 case FLOOR_MOD_EXPR:
20477 case TRUTH_ANDIF_EXPR:
20478 case TRUTH_ORIF_EXPR:
20479 case TRUTH_AND_EXPR:
20480 case TRUTH_OR_EXPR:
20481 case RSHIFT_EXPR:
20482 case LSHIFT_EXPR:
20483 case EQ_EXPR:
20484 case NE_EXPR:
20485 case MAX_EXPR:
20486 case MIN_EXPR:
20487 case LE_EXPR:
20488 case GE_EXPR:
20489 case LT_EXPR:
20490 case GT_EXPR:
20491 case SPACESHIP_EXPR:
20492 case MEMBER_REF:
20493 case DOTSTAR_EXPR:
20495 /* If either OP0 or OP1 was value- or type-dependent, suppress
20496 warnings that depend on the range of the types involved. */
20497 tree op0 = TREE_OPERAND (t, 0);
20498 tree op1 = TREE_OPERAND (t, 1);
20499 const bool was_dep = (dependent_operand_p (op0)
20500 || dependent_operand_p (op1));
20501 op0 = RECUR (op0);
20502 op1 = RECUR (op1);
20504 warning_sentinel s1(warn_type_limits, was_dep);
20505 warning_sentinel s2(warn_div_by_zero, was_dep);
20506 warning_sentinel s3(warn_logical_op, was_dep);
20507 warning_sentinel s4(warn_tautological_compare, was_dep);
20508 warning_sentinel s5(warn_address, was_dep);
20510 tree r = build_x_binary_op
20511 (input_location, TREE_CODE (t),
20512 op0,
20513 (warning_suppressed_p (TREE_OPERAND (t, 0))
20514 ? ERROR_MARK
20515 : TREE_CODE (TREE_OPERAND (t, 0))),
20516 op1,
20517 (warning_suppressed_p (TREE_OPERAND (t, 1))
20518 ? ERROR_MARK
20519 : TREE_CODE (TREE_OPERAND (t, 1))),
20520 templated_operator_saved_lookups (t),
20521 /*overload=*/NULL,
20522 complain|decltype_flag);
20523 if (EXPR_P (r))
20524 copy_warning (r, t);
20526 RETURN (r);
20529 case POINTER_PLUS_EXPR:
20531 tree op0 = RECUR (TREE_OPERAND (t, 0));
20532 if (op0 == error_mark_node)
20533 RETURN (error_mark_node);
20534 tree op1 = RECUR (TREE_OPERAND (t, 1));
20535 if (op1 == error_mark_node)
20536 RETURN (error_mark_node);
20537 RETURN (fold_build_pointer_plus (op0, op1));
20540 case SCOPE_REF:
20541 RETURN (tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
20542 /*address_p=*/false));
20544 case BASELINK:
20545 RETURN (tsubst_baselink (t, current_nonlambda_class_type (),
20546 args, complain, in_decl));
20548 case ARRAY_REF:
20549 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20550 args, complain, in_decl);
20551 if (TREE_CODE (TREE_OPERAND (t, 1)) == CALL_EXPR
20552 && (CALL_EXPR_FN (TREE_OPERAND (t, 1))
20553 == ovl_op_identifier (ARRAY_REF)))
20555 tree c = TREE_OPERAND (t, 1);
20556 releasing_vec index_exp_list;
20557 tsubst_copy_and_build_call_args (c, args, complain, in_decl,
20558 index_exp_list);
20560 tree r;
20561 if (vec_safe_length (index_exp_list) == 1
20562 && !PACK_EXPANSION_P (index_exp_list[0]))
20563 r = grok_array_decl (EXPR_LOCATION (t), op1,
20564 index_exp_list[0], NULL,
20565 complain | decltype_flag);
20566 else
20567 r = grok_array_decl (EXPR_LOCATION (t), op1,
20568 NULL_TREE, &index_exp_list,
20569 complain | decltype_flag);
20570 RETURN (r);
20572 RETURN (build_x_array_ref (EXPR_LOCATION (t), op1,
20573 RECUR (TREE_OPERAND (t, 1)),
20574 complain|decltype_flag));
20576 case SIZEOF_EXPR:
20577 if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
20578 || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
20579 RETURN (tsubst_copy (t, args, complain, in_decl));
20580 /* Fall through */
20582 case ALIGNOF_EXPR:
20584 tree r;
20586 op1 = TREE_OPERAND (t, 0);
20587 if (TREE_CODE (t) == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (t))
20588 op1 = TREE_TYPE (op1);
20589 bool std_alignof = (TREE_CODE (t) == ALIGNOF_EXPR
20590 && ALIGNOF_EXPR_STD_P (t));
20591 if (!args)
20593 /* When there are no ARGS, we are trying to evaluate a
20594 non-dependent expression from the parser. Trying to do
20595 the substitutions may not work. */
20596 if (!TYPE_P (op1))
20597 op1 = TREE_TYPE (op1);
20599 else
20601 ++cp_unevaluated_operand;
20602 ++c_inhibit_evaluation_warnings;
20603 if (TYPE_P (op1))
20604 op1 = tsubst (op1, args, complain, in_decl);
20605 else
20606 op1 = tsubst_copy_and_build (op1, args, complain, in_decl);
20607 --cp_unevaluated_operand;
20608 --c_inhibit_evaluation_warnings;
20610 if (TYPE_P (op1))
20611 r = cxx_sizeof_or_alignof_type (input_location,
20612 op1, TREE_CODE (t), std_alignof,
20613 complain & tf_error);
20614 else
20615 r = cxx_sizeof_or_alignof_expr (input_location,
20616 op1, TREE_CODE (t), std_alignof,
20617 complain & tf_error);
20618 if (TREE_CODE (t) == SIZEOF_EXPR && r != error_mark_node)
20620 if (TREE_CODE (r) != SIZEOF_EXPR || TYPE_P (op1))
20622 if (!processing_template_decl && TYPE_P (op1))
20624 r = build_min (SIZEOF_EXPR, size_type_node,
20625 build1 (NOP_EXPR, op1, error_mark_node));
20626 SIZEOF_EXPR_TYPE_P (r) = 1;
20628 else
20629 r = build_min (SIZEOF_EXPR, size_type_node, op1);
20630 TREE_SIDE_EFFECTS (r) = 0;
20631 TREE_READONLY (r) = 1;
20633 SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
20635 RETURN (r);
20638 case AT_ENCODE_EXPR:
20640 op1 = TREE_OPERAND (t, 0);
20641 ++cp_unevaluated_operand;
20642 ++c_inhibit_evaluation_warnings;
20643 op1 = tsubst_copy_and_build (op1, args, complain, in_decl);
20644 --cp_unevaluated_operand;
20645 --c_inhibit_evaluation_warnings;
20646 RETURN (objc_build_encode_expr (op1));
20649 case NOEXCEPT_EXPR:
20650 op1 = TREE_OPERAND (t, 0);
20651 ++cp_unevaluated_operand;
20652 ++c_inhibit_evaluation_warnings;
20653 ++cp_noexcept_operand;
20654 op1 = tsubst_copy_and_build (op1, args, complain, in_decl);
20655 --cp_unevaluated_operand;
20656 --c_inhibit_evaluation_warnings;
20657 --cp_noexcept_operand;
20658 RETURN (finish_noexcept_expr (op1, complain));
20660 case MODOP_EXPR:
20662 warning_sentinel s(warn_div_by_zero);
20663 tree lhs = RECUR (TREE_OPERAND (t, 0));
20664 tree rhs = RECUR (TREE_OPERAND (t, 2));
20666 tree r = build_x_modify_expr
20667 (EXPR_LOCATION (t), lhs, TREE_CODE (TREE_OPERAND (t, 1)), rhs,
20668 templated_operator_saved_lookups (t),
20669 complain|decltype_flag);
20670 /* TREE_NO_WARNING must be set if either the expression was
20671 parenthesized or it uses an operator such as >>= rather
20672 than plain assignment. In the former case, it was already
20673 set and must be copied. In the latter case,
20674 build_x_modify_expr sets it and it must not be reset
20675 here. */
20676 if (warning_suppressed_p (t, OPT_Wparentheses))
20677 suppress_warning (r, OPT_Wparentheses);
20679 RETURN (r);
20682 case ARROW_EXPR:
20683 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20684 args, complain, in_decl);
20685 /* Remember that there was a reference to this entity. */
20686 if (DECL_P (op1)
20687 && !mark_used (op1, complain) && !(complain & tf_error))
20688 RETURN (error_mark_node);
20689 RETURN (build_x_arrow (input_location, op1, complain));
20691 case NEW_EXPR:
20693 tree placement = RECUR (TREE_OPERAND (t, 0));
20694 tree init = RECUR (TREE_OPERAND (t, 3));
20695 vec<tree, va_gc> *placement_vec;
20696 vec<tree, va_gc> *init_vec;
20697 tree ret;
20698 location_t loc = EXPR_LOCATION (t);
20700 if (placement == NULL_TREE)
20701 placement_vec = NULL;
20702 else if (placement == error_mark_node)
20703 RETURN (error_mark_node);
20704 else
20706 placement_vec = make_tree_vector ();
20707 for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
20708 vec_safe_push (placement_vec, TREE_VALUE (placement));
20711 /* If there was an initializer in the original tree, but it
20712 instantiated to an empty list, then we should pass a
20713 non-NULL empty vector to tell build_new that it was an
20714 empty initializer() rather than no initializer. This can
20715 only happen when the initializer is a pack expansion whose
20716 parameter packs are of length zero. */
20717 if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
20718 init_vec = NULL;
20719 else if (init == error_mark_node)
20720 RETURN (error_mark_node);
20721 else
20723 init_vec = make_tree_vector ();
20724 if (init == void_node)
20725 gcc_assert (init_vec != NULL);
20726 else
20728 for (; init != NULL_TREE; init = TREE_CHAIN (init))
20729 vec_safe_push (init_vec, TREE_VALUE (init));
20733 /* Avoid passing an enclosing decl to valid_array_size_p. */
20734 in_decl = NULL_TREE;
20736 tree op1 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
20737 tree op2 = RECUR (TREE_OPERAND (t, 2));
20738 ret = build_new (loc, &placement_vec, op1, op2,
20739 &init_vec, NEW_EXPR_USE_GLOBAL (t),
20740 complain);
20742 if (placement_vec != NULL)
20743 release_tree_vector (placement_vec);
20744 if (init_vec != NULL)
20745 release_tree_vector (init_vec);
20747 RETURN (ret);
20750 case DELETE_EXPR:
20752 tree op0 = RECUR (TREE_OPERAND (t, 0));
20753 tree op1 = RECUR (TREE_OPERAND (t, 1));
20754 RETURN (delete_sanity (input_location, op0, op1,
20755 DELETE_EXPR_USE_VEC (t),
20756 DELETE_EXPR_USE_GLOBAL (t),
20757 complain));
20760 case COMPOUND_EXPR:
20762 tree op0 = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
20763 complain & ~tf_decltype, in_decl);
20764 RETURN (build_x_compound_expr (EXPR_LOCATION (t),
20765 op0,
20766 RECUR (TREE_OPERAND (t, 1)),
20767 templated_operator_saved_lookups (t),
20768 complain|decltype_flag));
20771 case CALL_EXPR:
20773 tree function;
20774 unsigned int nargs;
20775 bool qualified_p;
20776 bool koenig_p;
20777 tree ret;
20779 function = CALL_EXPR_FN (t);
20780 /* Internal function with no arguments. */
20781 if (function == NULL_TREE && call_expr_nargs (t) == 0)
20782 RETURN (t);
20784 /* When we parsed the expression, we determined whether or
20785 not Koenig lookup should be performed. */
20786 koenig_p = KOENIG_LOOKUP_P (t);
20787 if (function == NULL_TREE)
20789 koenig_p = false;
20790 qualified_p = false;
20792 else if (TREE_CODE (function) == SCOPE_REF)
20794 qualified_p = true;
20795 function = tsubst_qualified_id (function, args, complain, in_decl,
20796 /*done=*/false,
20797 /*address_p=*/false);
20799 else if (koenig_p
20800 && (identifier_p (function)
20801 || (TREE_CODE (function) == TEMPLATE_ID_EXPR
20802 && identifier_p (TREE_OPERAND (function, 0)))))
20804 /* Do nothing; calling tsubst_copy_and_build on an identifier
20805 would incorrectly perform unqualified lookup again.
20807 Note that we can also have an IDENTIFIER_NODE if the earlier
20808 unqualified lookup found a dependent local extern declaration
20809 (as per finish_call_expr); in that case koenig_p will be false
20810 and we do want to do the lookup again to find the substituted
20811 declaration. */
20812 qualified_p = false;
20814 if (TREE_CODE (function) == TEMPLATE_ID_EXPR)
20815 /* Use tsubst_copy to substitute through the template arguments
20816 of the template-id without performing unqualified lookup of
20817 the template name. */
20818 function = tsubst_copy (function, args, complain, in_decl);
20820 else
20822 if (TREE_CODE (function) == COMPONENT_REF)
20824 tree op = TREE_OPERAND (function, 1);
20826 qualified_p = (TREE_CODE (op) == SCOPE_REF
20827 || (BASELINK_P (op)
20828 && BASELINK_QUALIFIED_P (op)));
20830 else
20831 qualified_p = false;
20833 if (TREE_CODE (function) == ADDR_EXPR
20834 && TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL)
20835 /* Avoid error about taking the address of a constructor. */
20836 function = TREE_OPERAND (function, 0);
20838 tsubst_flags_t subcomplain = complain;
20839 if (koenig_p && TREE_CODE (function) == FUNCTION_DECL)
20840 /* When KOENIG_P, we don't want to mark_used the callee before
20841 augmenting the overload set via ADL, so during this initial
20842 substitution we disable mark_used by setting tf_conv (68942). */
20843 subcomplain |= tf_conv;
20844 function = tsubst_copy_and_build (function, args, subcomplain, in_decl);
20846 if (BASELINK_P (function))
20847 qualified_p = true;
20850 nargs = call_expr_nargs (t);
20851 releasing_vec call_args;
20852 tsubst_copy_and_build_call_args (t, args, complain, in_decl,
20853 call_args);
20855 /* Stripped-down processing for a call in a thunk. Specifically, in
20856 the thunk template for a generic lambda. */
20857 if (call_from_lambda_thunk_p (t))
20859 /* Now that we've expanded any packs, the number of call args
20860 might be different. */
20861 unsigned int cargs = call_args->length ();
20862 tree thisarg = NULL_TREE;
20863 if (TREE_CODE (function) == COMPONENT_REF)
20865 thisarg = TREE_OPERAND (function, 0);
20866 if (TREE_CODE (thisarg) == INDIRECT_REF)
20867 thisarg = TREE_OPERAND (thisarg, 0);
20868 function = TREE_OPERAND (function, 1);
20869 if (TREE_CODE (function) == BASELINK)
20870 function = BASELINK_FUNCTIONS (function);
20872 /* We aren't going to do normal overload resolution, so force the
20873 template-id to resolve. */
20874 function = resolve_nondeduced_context (function, complain);
20875 for (unsigned i = 0; i < cargs; ++i)
20877 /* In a thunk, pass through args directly, without any
20878 conversions. */
20879 tree arg = (*call_args)[i];
20880 while (TREE_CODE (arg) != PARM_DECL)
20881 arg = TREE_OPERAND (arg, 0);
20882 (*call_args)[i] = arg;
20884 if (thisarg)
20886 /* If there are no other args, just push 'this'. */
20887 if (cargs == 0)
20888 vec_safe_push (call_args, thisarg);
20889 else
20891 /* Otherwise, shift the other args over to make room. */
20892 tree last = (*call_args)[cargs - 1];
20893 vec_safe_push (call_args, last);
20894 for (int i = cargs - 1; i > 0; --i)
20895 (*call_args)[i] = (*call_args)[i - 1];
20896 (*call_args)[0] = thisarg;
20899 ret = build_call_a (function, call_args->length (),
20900 call_args->address ());
20901 /* The thunk location is not interesting. */
20902 SET_EXPR_LOCATION (ret, UNKNOWN_LOCATION);
20903 CALL_FROM_THUNK_P (ret) = true;
20904 if (CLASS_TYPE_P (TREE_TYPE (ret)))
20905 CALL_EXPR_RETURN_SLOT_OPT (ret) = true;
20907 RETURN (ret);
20910 /* We do not perform argument-dependent lookup if normal
20911 lookup finds a non-function, in accordance with the
20912 resolution of DR 218. */
20913 if (koenig_p
20914 && ((is_overloaded_fn (function)
20915 /* If lookup found a member function, the Koenig lookup is
20916 not appropriate, even if an unqualified-name was used
20917 to denote the function. */
20918 && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
20919 || identifier_p (function)
20920 /* C++20 P0846: Lookup found nothing. */
20921 || (TREE_CODE (function) == TEMPLATE_ID_EXPR
20922 && identifier_p (TREE_OPERAND (function, 0))))
20923 /* Only do this when substitution turns a dependent call
20924 into a non-dependent call. */
20925 && type_dependent_expression_p_push (t)
20926 && !any_type_dependent_arguments_p (call_args))
20927 function = perform_koenig_lookup (function, call_args, tf_none);
20929 if (function != NULL_TREE
20930 && (identifier_p (function)
20931 || (TREE_CODE (function) == TEMPLATE_ID_EXPR
20932 && identifier_p (TREE_OPERAND (function, 0))
20933 && !any_dependent_template_arguments_p (TREE_OPERAND
20934 (function, 1))))
20935 && !any_type_dependent_arguments_p (call_args))
20937 bool template_id_p = (TREE_CODE (function) == TEMPLATE_ID_EXPR);
20938 if (template_id_p)
20939 function = TREE_OPERAND (function, 0);
20940 if (koenig_p && (complain & tf_warning_or_error))
20942 /* For backwards compatibility and good diagnostics, try
20943 the unqualified lookup again if we aren't in SFINAE
20944 context. */
20945 tree unq = tsubst_copy_and_build (function, args,
20946 complain, in_decl);
20947 if (unq == error_mark_node)
20948 RETURN (error_mark_node);
20950 if (unq != function)
20952 char const *const msg
20953 = G_("%qD was not declared in this scope, "
20954 "and no declarations were found by "
20955 "argument-dependent lookup at the point "
20956 "of instantiation");
20958 bool in_lambda = (current_class_type
20959 && LAMBDA_TYPE_P (current_class_type));
20960 /* In a lambda fn, we have to be careful to not
20961 introduce new this captures. Legacy code can't
20962 be using lambdas anyway, so it's ok to be
20963 stricter. Be strict with C++20 template-id ADL too.
20964 And be strict if we're already failing anyway. */
20965 bool strict = in_lambda || template_id_p || seen_error();
20966 bool diag = true;
20967 if (strict)
20968 error_at (cp_expr_loc_or_input_loc (t),
20969 msg, function);
20970 else
20971 diag = permerror (cp_expr_loc_or_input_loc (t),
20972 msg, function);
20973 if (diag)
20975 tree fn = unq;
20977 if (INDIRECT_REF_P (fn))
20978 fn = TREE_OPERAND (fn, 0);
20979 if (is_overloaded_fn (fn))
20980 fn = get_first_fn (fn);
20982 if (!DECL_P (fn))
20983 /* Can't say anything more. */;
20984 else if (DECL_CLASS_SCOPE_P (fn))
20986 location_t loc = cp_expr_loc_or_input_loc (t);
20987 inform (loc,
20988 "declarations in dependent base %qT are "
20989 "not found by unqualified lookup",
20990 DECL_CLASS_CONTEXT (fn));
20991 if (current_class_ptr)
20992 inform (loc,
20993 "use %<this->%D%> instead", function);
20994 else
20995 inform (loc,
20996 "use %<%T::%D%> instead",
20997 current_class_name, function);
20999 else
21000 inform (DECL_SOURCE_LOCATION (fn),
21001 "%qD declared here, later in the "
21002 "translation unit", fn);
21003 if (strict)
21004 RETURN (error_mark_node);
21007 function = unq;
21010 if (identifier_p (function))
21012 if (complain & tf_error)
21013 unqualified_name_lookup_error (function);
21014 RETURN (error_mark_node);
21018 /* Remember that there was a reference to this entity. */
21019 if (function != NULL_TREE)
21021 tree inner = function;
21022 if (TREE_CODE (inner) == ADDR_EXPR
21023 && TREE_CODE (TREE_OPERAND (inner, 0)) == FUNCTION_DECL)
21024 /* We should already have called mark_used when taking the
21025 address of this function, but do so again anyway to make
21026 sure it's odr-used: at worst this is a no-op, but if we
21027 obtained this FUNCTION_DECL as part of ahead-of-time overload
21028 resolution then that call to mark_used wouldn't have marked it
21029 odr-used yet (53164). */
21030 inner = TREE_OPERAND (inner, 0);
21031 if (DECL_P (inner)
21032 && !mark_used (inner, complain) && !(complain & tf_error))
21033 RETURN (error_mark_node);
21036 if (!maybe_fold_fn_template_args (function, complain))
21037 return error_mark_node;
21039 /* Put back tf_decltype for the actual call. */
21040 complain |= decltype_flag;
21042 if (function == NULL_TREE)
21043 switch (CALL_EXPR_IFN (t))
21045 case IFN_LAUNDER:
21046 gcc_assert (nargs == 1);
21047 if (vec_safe_length (call_args) != 1)
21049 error_at (cp_expr_loc_or_input_loc (t),
21050 "wrong number of arguments to "
21051 "%<__builtin_launder%>");
21052 ret = error_mark_node;
21054 else
21055 ret = finish_builtin_launder (cp_expr_loc_or_input_loc (t),
21056 (*call_args)[0], complain);
21057 break;
21059 case IFN_VEC_CONVERT:
21060 gcc_assert (nargs == 1);
21061 if (vec_safe_length (call_args) != 1)
21063 error_at (cp_expr_loc_or_input_loc (t),
21064 "wrong number of arguments to "
21065 "%<__builtin_convertvector%>");
21066 ret = error_mark_node;
21067 break;
21069 ret = cp_build_vec_convert ((*call_args)[0], input_location,
21070 tsubst (TREE_TYPE (t), args,
21071 complain, in_decl),
21072 complain);
21073 if (TREE_CODE (ret) == VIEW_CONVERT_EXPR)
21074 RETURN (ret);
21075 break;
21077 case IFN_SHUFFLEVECTOR:
21079 ret = build_x_shufflevector (input_location, call_args,
21080 complain);
21081 if (ret != error_mark_node)
21082 RETURN (ret);
21083 break;
21086 case IFN_ASSUME:
21087 gcc_assert (nargs == 1);
21088 if (vec_safe_length (call_args) != 1)
21090 error_at (cp_expr_loc_or_input_loc (t),
21091 "wrong number of arguments to "
21092 "%<assume%> attribute");
21093 ret = error_mark_node;
21095 else
21097 tree &arg = (*call_args)[0];
21098 if (!type_dependent_expression_p (arg))
21099 arg = contextual_conv_bool (arg, tf_warning_or_error);
21100 if (error_operand_p (arg))
21102 ret = error_mark_node;
21103 break;
21105 ret = build_assume_call (EXPR_LOCATION (t), arg);
21106 RETURN (ret);
21108 break;
21110 default:
21111 /* Unsupported internal function with arguments. */
21112 gcc_unreachable ();
21114 else if (TREE_CODE (function) == OFFSET_REF
21115 || TREE_CODE (function) == DOTSTAR_EXPR
21116 || TREE_CODE (function) == MEMBER_REF)
21117 ret = build_offset_ref_call_from_tree (function, &call_args,
21118 complain);
21119 else if (TREE_CODE (function) == COMPONENT_REF)
21121 tree instance = TREE_OPERAND (function, 0);
21122 tree fn = TREE_OPERAND (function, 1);
21124 if (processing_template_decl
21125 && (type_dependent_expression_p (instance)
21126 || (!BASELINK_P (fn)
21127 && TREE_CODE (fn) != FIELD_DECL)
21128 || type_dependent_expression_p (fn)
21129 || any_type_dependent_arguments_p (call_args)))
21130 ret = build_min_nt_call_vec (function, call_args);
21131 else if (!BASELINK_P (fn))
21132 ret = finish_call_expr (function, &call_args,
21133 /*disallow_virtual=*/false,
21134 /*koenig_p=*/false,
21135 complain);
21136 else
21137 ret = (build_new_method_call
21138 (instance, fn,
21139 &call_args, NULL_TREE,
21140 qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
21141 /*fn_p=*/NULL,
21142 complain));
21144 else if (concept_check_p (function))
21146 /* FUNCTION is a template-id referring to a concept definition. */
21147 tree id = unpack_concept_check (function);
21148 tree tmpl = TREE_OPERAND (id, 0);
21149 tree args = TREE_OPERAND (id, 1);
21151 /* Calls to standard and variable concepts should have been
21152 previously diagnosed. */
21153 gcc_assert (function_concept_p (tmpl));
21155 /* Ensure the result is wrapped as a call expression. */
21156 ret = build_concept_check (tmpl, args, tf_warning_or_error);
21158 else
21159 ret = finish_call_expr (function, &call_args,
21160 /*disallow_virtual=*/qualified_p,
21161 koenig_p,
21162 complain);
21164 if (ret != error_mark_node)
21166 bool op = CALL_EXPR_OPERATOR_SYNTAX (t);
21167 bool ord = CALL_EXPR_ORDERED_ARGS (t);
21168 bool rev = CALL_EXPR_REVERSE_ARGS (t);
21169 if (op || ord || rev)
21170 if (tree call = extract_call_expr (ret))
21172 CALL_EXPR_OPERATOR_SYNTAX (call) = op;
21173 CALL_EXPR_ORDERED_ARGS (call) = ord;
21174 CALL_EXPR_REVERSE_ARGS (call) = rev;
21176 if (warning_suppressed_p (t, OPT_Wpessimizing_move))
21177 /* This also suppresses -Wredundant-move. */
21178 suppress_warning (ret, OPT_Wpessimizing_move);
21181 RETURN (ret);
21184 case COND_EXPR:
21186 tree cond = RECUR (TREE_OPERAND (t, 0));
21187 cond = mark_rvalue_use (cond);
21188 tree folded_cond = fold_non_dependent_expr (cond, complain);
21189 tree exp1, exp2;
21191 if (TREE_CODE (folded_cond) == INTEGER_CST)
21193 if (integer_zerop (folded_cond))
21195 ++c_inhibit_evaluation_warnings;
21196 exp1 = RECUR (TREE_OPERAND (t, 1));
21197 --c_inhibit_evaluation_warnings;
21198 exp2 = RECUR (TREE_OPERAND (t, 2));
21200 else
21202 exp1 = RECUR (TREE_OPERAND (t, 1));
21203 ++c_inhibit_evaluation_warnings;
21204 exp2 = RECUR (TREE_OPERAND (t, 2));
21205 --c_inhibit_evaluation_warnings;
21207 cond = folded_cond;
21209 else
21211 exp1 = RECUR (TREE_OPERAND (t, 1));
21212 exp2 = RECUR (TREE_OPERAND (t, 2));
21215 warning_sentinel s(warn_duplicated_branches);
21216 RETURN (build_x_conditional_expr (EXPR_LOCATION (t),
21217 cond, exp1, exp2, complain));
21220 case PSEUDO_DTOR_EXPR:
21222 tree op0 = RECUR (TREE_OPERAND (t, 0));
21223 tree op1 = RECUR (TREE_OPERAND (t, 1));
21224 tree op2 = tsubst (TREE_OPERAND (t, 2), args, complain, in_decl);
21225 RETURN (finish_pseudo_destructor_expr (op0, op1, op2,
21226 input_location));
21229 case TREE_LIST:
21230 RETURN (tsubst_tree_list (t, args, complain, in_decl));
21232 case COMPONENT_REF:
21234 tree object;
21235 tree object_type;
21236 tree member;
21237 tree r;
21239 object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
21240 args, complain, in_decl);
21241 /* Remember that there was a reference to this entity. */
21242 if (DECL_P (object)
21243 && !mark_used (object, complain) && !(complain & tf_error))
21244 RETURN (error_mark_node);
21245 object_type = TREE_TYPE (object);
21247 member = TREE_OPERAND (t, 1);
21248 if (BASELINK_P (member))
21249 member = tsubst_baselink (member,
21250 non_reference (TREE_TYPE (object)),
21251 args, complain, in_decl);
21252 else
21253 member = tsubst_copy (member, args, complain, in_decl);
21254 if (member == error_mark_node)
21255 RETURN (error_mark_node);
21257 if (object_type && TYPE_PTRMEMFUNC_P (object_type)
21258 && TREE_CODE (member) == FIELD_DECL)
21260 r = build_ptrmemfunc_access_expr (object, DECL_NAME (member));
21261 RETURN (r);
21263 else if (TREE_CODE (member) == FIELD_DECL)
21265 r = finish_non_static_data_member (member, object, NULL_TREE,
21266 complain);
21267 if (TREE_CODE (r) == COMPONENT_REF)
21268 REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
21269 RETURN (r);
21271 else if (type_dependent_expression_p (object))
21272 /* We can't do much here. */;
21273 else if (!CLASS_TYPE_P (object_type))
21275 if (scalarish_type_p (object_type))
21277 tree s = NULL_TREE;
21278 tree dtor = member;
21280 if (TREE_CODE (dtor) == SCOPE_REF)
21282 s = TREE_OPERAND (dtor, 0);
21283 dtor = TREE_OPERAND (dtor, 1);
21285 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
21287 dtor = TREE_OPERAND (dtor, 0);
21288 if (TYPE_P (dtor))
21289 RETURN (finish_pseudo_destructor_expr
21290 (object, s, dtor, input_location));
21294 else if (TREE_CODE (member) == SCOPE_REF
21295 && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
21297 /* Lookup the template functions now that we know what the
21298 scope is. */
21299 tree scope = TREE_OPERAND (member, 0);
21300 tree tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
21301 tree args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
21302 member = lookup_qualified_name (scope, tmpl, LOOK_want::NORMAL,
21303 /*complain=*/false);
21304 if (BASELINK_P (member))
21306 BASELINK_FUNCTIONS (member)
21307 = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
21308 args);
21309 member = (adjust_result_of_qualified_name_lookup
21310 (member, BINFO_TYPE (BASELINK_BINFO (member)),
21311 object_type));
21313 else
21315 qualified_name_lookup_error (scope, tmpl, member,
21316 input_location);
21317 RETURN (error_mark_node);
21320 else if (TREE_CODE (member) == SCOPE_REF
21321 && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
21322 && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
21324 if (complain & tf_error)
21326 if (TYPE_P (TREE_OPERAND (member, 0)))
21327 error ("%qT is not a class or namespace",
21328 TREE_OPERAND (member, 0));
21329 else
21330 error ("%qD is not a class or namespace",
21331 TREE_OPERAND (member, 0));
21333 RETURN (error_mark_node);
21336 r = finish_class_member_access_expr (object, member,
21337 /*template_p=*/false,
21338 complain);
21339 if (TREE_CODE (r) == COMPONENT_REF)
21340 REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
21341 RETURN (r);
21344 case THROW_EXPR:
21345 RETURN (build_throw
21346 (input_location, RECUR (TREE_OPERAND (t, 0))));
21348 case CONSTRUCTOR:
21350 vec<constructor_elt, va_gc> *n;
21351 constructor_elt *ce;
21352 unsigned HOST_WIDE_INT idx;
21353 bool process_index_p;
21354 int newlen;
21355 bool need_copy_p = false;
21356 tree r;
21358 tsubst_flags_t tcomplain = complain;
21359 if (COMPOUND_LITERAL_P (t))
21360 tcomplain |= tf_tst_ok;
21361 tree type = tsubst (TREE_TYPE (t), args, tcomplain, in_decl);
21362 if (type == error_mark_node)
21363 RETURN (error_mark_node);
21365 /* We do not want to process the index of aggregate
21366 initializers as they are identifier nodes which will be
21367 looked up by digest_init. */
21368 process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
21370 if (null_member_pointer_value_p (t))
21372 gcc_assert (same_type_p (type, TREE_TYPE (t)));
21373 RETURN (t);
21376 n = vec_safe_copy (CONSTRUCTOR_ELTS (t));
21377 newlen = vec_safe_length (n);
21378 FOR_EACH_VEC_SAFE_ELT (n, idx, ce)
21380 if (ce->index && process_index_p
21381 /* An identifier index is looked up in the type
21382 being initialized, not the current scope. */
21383 && TREE_CODE (ce->index) != IDENTIFIER_NODE)
21384 ce->index = RECUR (ce->index);
21386 if (PACK_EXPANSION_P (ce->value))
21388 /* Substitute into the pack expansion. */
21389 ce->value = tsubst_pack_expansion (ce->value, args, complain,
21390 in_decl);
21392 if (ce->value == error_mark_node
21393 || PACK_EXPANSION_P (ce->value))
21395 else if (TREE_VEC_LENGTH (ce->value) == 1)
21396 /* Just move the argument into place. */
21397 ce->value = TREE_VEC_ELT (ce->value, 0);
21398 else
21400 /* Update the length of the final CONSTRUCTOR
21401 arguments vector, and note that we will need to
21402 copy.*/
21403 newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
21404 need_copy_p = true;
21407 else
21408 ce->value = RECUR (ce->value);
21411 if (need_copy_p)
21413 vec<constructor_elt, va_gc> *old_n = n;
21415 vec_alloc (n, newlen);
21416 FOR_EACH_VEC_ELT (*old_n, idx, ce)
21418 if (TREE_CODE (ce->value) == TREE_VEC)
21420 int i, len = TREE_VEC_LENGTH (ce->value);
21421 for (i = 0; i < len; ++i)
21422 CONSTRUCTOR_APPEND_ELT (n, 0,
21423 TREE_VEC_ELT (ce->value, i));
21425 else
21426 CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
21430 r = build_constructor (init_list_type_node, n);
21431 CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
21432 CONSTRUCTOR_IS_DESIGNATED_INIT (r)
21433 = CONSTRUCTOR_IS_DESIGNATED_INIT (t);
21435 if (TREE_HAS_CONSTRUCTOR (t))
21437 fcl_t cl = fcl_functional;
21438 if (CONSTRUCTOR_C99_COMPOUND_LITERAL (t))
21439 cl = fcl_c99;
21440 RETURN (finish_compound_literal (type, r, complain, cl));
21443 TREE_TYPE (r) = type;
21444 RETURN (r);
21447 case TYPEID_EXPR:
21449 tree operand_0 = TREE_OPERAND (t, 0);
21450 if (TYPE_P (operand_0))
21452 operand_0 = tsubst (operand_0, args, complain, in_decl);
21453 RETURN (get_typeid (operand_0, complain));
21455 else
21457 operand_0 = RECUR (operand_0);
21458 RETURN (build_typeid (operand_0, complain));
21462 case VAR_DECL:
21463 if (!args)
21464 RETURN (t);
21465 /* Fall through */
21467 case PARM_DECL:
21469 tree r = tsubst_copy (t, args, complain, in_decl);
21470 /* ??? We're doing a subset of finish_id_expression here. */
21471 if (tree wrap = maybe_get_tls_wrapper_call (r))
21472 /* Replace an evaluated use of the thread_local variable with
21473 a call to its wrapper. */
21474 r = wrap;
21475 else if (outer_automatic_var_p (r))
21476 r = process_outer_var_ref (r, complain);
21478 if (!TYPE_REF_P (TREE_TYPE (t)))
21479 /* If the original type was a reference, we'll be wrapped in
21480 the appropriate INDIRECT_REF. */
21481 r = convert_from_reference (r);
21482 RETURN (r);
21485 case VA_ARG_EXPR:
21487 tree op0 = RECUR (TREE_OPERAND (t, 0));
21488 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
21489 RETURN (build_x_va_arg (EXPR_LOCATION (t), op0, type));
21492 case OFFSETOF_EXPR:
21494 tree object_ptr
21495 = tsubst_copy_and_build (TREE_OPERAND (t, 1), args,
21496 complain, in_decl);
21497 RETURN (finish_offsetof (object_ptr,
21498 RECUR (TREE_OPERAND (t, 0)),
21499 EXPR_LOCATION (t)));
21502 case ADDRESSOF_EXPR:
21503 RETURN (cp_build_addressof (EXPR_LOCATION (t),
21504 RECUR (TREE_OPERAND (t, 0)), complain));
21506 case TRAIT_EXPR:
21508 tree type1 = tsubst (TRAIT_EXPR_TYPE1 (t), args,
21509 complain, in_decl);
21510 tree type2 = tsubst (TRAIT_EXPR_TYPE2 (t), args,
21511 complain, in_decl);
21512 RETURN (finish_trait_expr (TRAIT_EXPR_LOCATION (t),
21513 TRAIT_EXPR_KIND (t), type1, type2));
21516 case STMT_EXPR:
21518 tree old_stmt_expr = cur_stmt_expr;
21519 tree stmt_expr = begin_stmt_expr ();
21521 cur_stmt_expr = stmt_expr;
21522 tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl);
21523 stmt_expr = finish_stmt_expr (stmt_expr, false);
21524 cur_stmt_expr = old_stmt_expr;
21526 /* If the resulting list of expression statement is empty,
21527 fold it further into void_node. */
21528 if (empty_expr_stmt_p (stmt_expr))
21529 stmt_expr = void_node;
21531 RETURN (stmt_expr);
21534 case LAMBDA_EXPR:
21536 if (complain & tf_partial)
21538 /* We don't have a full set of template arguments yet; don't touch
21539 the lambda at all. */
21540 gcc_assert (processing_template_decl);
21541 return t;
21543 tree r = tsubst_lambda_expr (t, args, complain, in_decl);
21545 RETURN (build_lambda_object (r));
21548 case TRANSACTION_EXPR:
21549 RETURN (tsubst_expr (t, args, complain, in_decl));
21551 case PAREN_EXPR:
21552 if (REF_PARENTHESIZED_P (t))
21553 RETURN (finish_parenthesized_expr (RECUR (TREE_OPERAND (t, 0))));
21554 else
21555 /* Recreate the PAREN_EXPR from __builtin_assoc_barrier. */
21557 tree op0 = RECUR (TREE_OPERAND (t, 0));
21558 RETURN (build1_loc (input_location, PAREN_EXPR,
21559 TREE_TYPE (op0), op0));
21562 case VEC_PERM_EXPR:
21564 tree op0 = RECUR (TREE_OPERAND (t, 0));
21565 tree op1 = RECUR (TREE_OPERAND (t, 1));
21566 tree op2 = RECUR (TREE_OPERAND (t, 2));
21567 RETURN (build_x_vec_perm_expr (input_location, op0, op1, op2,
21568 complain));
21571 case REQUIRES_EXPR:
21573 tree r = tsubst_requires_expr (t, args, tf_none, in_decl);
21574 RETURN (r);
21577 case RANGE_EXPR:
21578 /* No need to substitute further, a RANGE_EXPR will always be built
21579 with constant operands. */
21580 RETURN (t);
21582 case NON_LVALUE_EXPR:
21583 case VIEW_CONVERT_EXPR:
21584 if (location_wrapper_p (t))
21585 /* We need to do this here as well as in tsubst_copy so we get the
21586 other tsubst_copy_and_build semantics for a PARM_DECL operand. */
21587 RETURN (maybe_wrap_with_location (RECUR (TREE_OPERAND (t, 0)),
21588 EXPR_LOCATION (t)));
21589 /* fallthrough. */
21591 default:
21592 /* Handle Objective-C++ constructs, if appropriate. */
21594 tree subst
21595 = objcp_tsubst_copy_and_build (t, args, complain, in_decl);
21596 if (subst)
21597 RETURN (subst);
21599 RETURN (tsubst_copy (t, args, complain, in_decl));
21602 #undef RECUR
21603 #undef RETURN
21604 out:
21605 input_location = save_loc;
21606 return retval;
21609 /* Verify that the instantiated ARGS are valid. For type arguments,
21610 make sure that the type's linkage is ok. For non-type arguments,
21611 make sure they are constants if they are integral or enumerations.
21612 Emit an error under control of COMPLAIN, and return TRUE on error. */
21614 static bool
21615 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
21617 if (dependent_template_arg_p (t))
21618 return false;
21619 if (ARGUMENT_PACK_P (t))
21621 tree vec = ARGUMENT_PACK_ARGS (t);
21622 int len = TREE_VEC_LENGTH (vec);
21623 bool result = false;
21624 int i;
21626 for (i = 0; i < len; ++i)
21627 if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
21628 result = true;
21629 return result;
21631 else if (TYPE_P (t))
21633 /* [basic.link]: A name with no linkage (notably, the name
21634 of a class or enumeration declared in a local scope)
21635 shall not be used to declare an entity with linkage.
21636 This implies that names with no linkage cannot be used as
21637 template arguments
21639 DR 757 relaxes this restriction for C++0x. */
21640 tree nt = (cxx_dialect > cxx98 ? NULL_TREE
21641 : no_linkage_check (t, /*relaxed_p=*/false));
21643 if (nt)
21645 /* DR 488 makes use of a type with no linkage cause
21646 type deduction to fail. */
21647 if (complain & tf_error)
21649 if (TYPE_UNNAMED_P (nt))
21650 error ("%qT is/uses unnamed type", t);
21651 else
21652 error ("template argument for %qD uses local type %qT",
21653 tmpl, t);
21655 return true;
21657 /* In order to avoid all sorts of complications, we do not
21658 allow variably-modified types as template arguments. */
21659 else if (variably_modified_type_p (t, NULL_TREE))
21661 if (complain & tf_error)
21662 error ("%qT is a variably modified type", t);
21663 return true;
21666 /* Class template and alias template arguments should be OK. */
21667 else if (DECL_TYPE_TEMPLATE_P (t))
21669 /* A non-type argument of integral or enumerated type must be a
21670 constant. */
21671 else if (TREE_TYPE (t)
21672 && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
21673 && !REFERENCE_REF_P (t)
21674 && !TREE_CONSTANT (t))
21676 if (complain & tf_error)
21677 error ("integral expression %qE is not constant", t);
21678 return true;
21680 return false;
21683 static bool
21684 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
21686 int ix, len = DECL_NTPARMS (tmpl);
21687 bool result = false;
21689 for (ix = 0; ix != len; ix++)
21691 if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
21692 result = true;
21694 if (result && (complain & tf_error))
21695 error (" trying to instantiate %qD", tmpl);
21696 return result;
21699 /* We're out of SFINAE context now, so generate diagnostics for the access
21700 errors we saw earlier when instantiating D from TMPL and ARGS. */
21702 static void
21703 recheck_decl_substitution (tree d, tree tmpl, tree args)
21705 tree pattern = DECL_TEMPLATE_RESULT (tmpl);
21706 tree type = TREE_TYPE (pattern);
21707 location_t loc = input_location;
21709 push_access_scope (d);
21710 push_deferring_access_checks (dk_no_deferred);
21711 input_location = DECL_SOURCE_LOCATION (pattern);
21712 tsubst (type, args, tf_warning_or_error, d);
21713 input_location = loc;
21714 pop_deferring_access_checks ();
21715 pop_access_scope (d);
21718 /* Instantiate the indicated variable, function, or alias template TMPL with
21719 the template arguments in TARG_PTR. */
21721 tree
21722 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
21724 auto_timevar tv (TV_TEMPLATE_INST);
21726 tree targ_ptr = orig_args;
21727 tree fndecl;
21728 tree gen_tmpl;
21729 tree spec;
21730 bool access_ok = true;
21732 if (tmpl == error_mark_node)
21733 return error_mark_node;
21735 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
21737 if (modules_p ())
21738 lazy_load_pendings (tmpl);
21740 /* If this function is a clone, handle it specially. */
21741 if (DECL_CLONED_FUNCTION_P (tmpl))
21743 tree spec;
21744 tree clone;
21746 /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
21747 DECL_CLONED_FUNCTION. */
21748 spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
21749 targ_ptr, complain);
21750 if (spec == error_mark_node)
21751 return error_mark_node;
21753 /* Look for the clone. */
21754 FOR_EACH_CLONE (clone, spec)
21755 if (DECL_NAME (clone) == DECL_NAME (tmpl))
21756 return clone;
21757 /* We should always have found the clone by now. */
21758 gcc_unreachable ();
21759 return NULL_TREE;
21762 if (targ_ptr == error_mark_node)
21763 return error_mark_node;
21765 /* Check to see if we already have this specialization. */
21766 gen_tmpl = most_general_template (tmpl);
21767 if (TMPL_ARGS_DEPTH (targ_ptr)
21768 < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)))
21769 /* targ_ptr only has the innermost template args, so add the outer ones
21770 from tmpl, which could be either a partial instantiation or gen_tmpl (in
21771 the case of a non-dependent call within a template definition). */
21772 targ_ptr = (add_outermost_template_args
21773 (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (tmpl)),
21774 targ_ptr));
21776 /* It would be nice to avoid hashing here and then again in tsubst_decl,
21777 but it doesn't seem to be on the hot path. */
21778 spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
21780 gcc_checking_assert (tmpl == gen_tmpl
21781 || ((fndecl
21782 = retrieve_specialization (tmpl, orig_args, 0))
21783 == spec)
21784 || fndecl == NULL_TREE);
21786 if (spec != NULL_TREE)
21788 if (FNDECL_HAS_ACCESS_ERRORS (spec))
21790 if (complain & tf_error)
21791 recheck_decl_substitution (spec, gen_tmpl, targ_ptr);
21792 return error_mark_node;
21794 return spec;
21797 if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
21798 complain))
21799 return error_mark_node;
21801 /* We are building a FUNCTION_DECL, during which the access of its
21802 parameters and return types have to be checked. However this
21803 FUNCTION_DECL which is the desired context for access checking
21804 is not built yet. We solve this chicken-and-egg problem by
21805 deferring all checks until we have the FUNCTION_DECL. */
21806 push_deferring_access_checks (dk_deferred);
21808 /* Instantiation of the function happens in the context of the function
21809 template, not the context of the overload resolution we're doing. */
21810 push_to_top_level ();
21811 /* If there are dependent arguments, e.g. because we're doing partial
21812 ordering, make sure processing_template_decl stays set. */
21813 if (uses_template_parms (targ_ptr))
21814 ++processing_template_decl;
21815 if (DECL_CLASS_SCOPE_P (gen_tmpl))
21817 tree ctx;
21818 if (!uses_template_parms (DECL_CONTEXT (tmpl)))
21819 /* If the context of the partially instantiated template is
21820 already non-dependent, then we might as well use it. */
21821 ctx = DECL_CONTEXT (tmpl);
21822 else
21823 ctx = tsubst_aggr_type (DECL_CONTEXT (gen_tmpl), targ_ptr,
21824 complain, gen_tmpl, true);
21825 push_nested_class (ctx);
21828 tree pattern = DECL_TEMPLATE_RESULT (gen_tmpl);
21830 fndecl = NULL_TREE;
21831 if (VAR_P (pattern))
21833 /* We need to determine if we're using a partial or explicit
21834 specialization now, because the type of the variable could be
21835 different. */
21836 tree tid = lookup_template_variable (tmpl, targ_ptr);
21837 tree elt = most_specialized_partial_spec (tid, complain);
21838 if (elt == error_mark_node)
21839 pattern = error_mark_node;
21840 else if (elt)
21842 tree partial_tmpl = TREE_VALUE (elt);
21843 tree partial_args = TREE_PURPOSE (elt);
21844 tree partial_pat = DECL_TEMPLATE_RESULT (partial_tmpl);
21845 fndecl = tsubst (partial_pat, partial_args, complain, gen_tmpl);
21849 /* Substitute template parameters to obtain the specialization. */
21850 if (fndecl == NULL_TREE)
21851 fndecl = tsubst (pattern, targ_ptr, complain, gen_tmpl);
21852 if (DECL_CLASS_SCOPE_P (gen_tmpl))
21853 pop_nested_class ();
21854 pop_from_top_level ();
21856 if (fndecl == error_mark_node)
21858 pop_deferring_access_checks ();
21859 return error_mark_node;
21862 /* The DECL_TI_TEMPLATE should always be the immediate parent
21863 template, not the most general template. */
21864 DECL_TI_TEMPLATE (fndecl) = tmpl;
21865 DECL_TI_ARGS (fndecl) = targ_ptr;
21867 set_instantiating_module (fndecl);
21869 /* Now we know the specialization, compute access previously
21870 deferred. Do no access control for inheriting constructors,
21871 as we already checked access for the inherited constructor. */
21872 if (!(flag_new_inheriting_ctors
21873 && DECL_INHERITED_CTOR (fndecl)))
21875 push_access_scope (fndecl);
21876 if (!perform_deferred_access_checks (complain))
21877 access_ok = false;
21878 pop_access_scope (fndecl);
21880 pop_deferring_access_checks ();
21882 /* If we've just instantiated the main entry point for a function,
21883 instantiate all the alternate entry points as well. We do this
21884 by cloning the instantiation of the main entry point, not by
21885 instantiating the template clones. */
21886 if (tree chain = DECL_CHAIN (gen_tmpl))
21887 if (DECL_P (chain) && DECL_CLONED_FUNCTION_P (chain))
21888 clone_cdtor (fndecl, /*update_methods=*/false);
21890 if (!access_ok)
21892 if (!(complain & tf_error))
21894 /* Remember to reinstantiate when we're out of SFINAE so the user
21895 can see the errors. */
21896 FNDECL_HAS_ACCESS_ERRORS (fndecl) = true;
21898 return error_mark_node;
21901 return fndecl;
21904 /* Instantiate the alias template TMPL with ARGS. Also push a template
21905 instantiation level, which instantiate_template doesn't do because
21906 functions and variables have sufficient context established by the
21907 callers. */
21909 static tree
21910 instantiate_alias_template (tree tmpl, tree args, tsubst_flags_t complain)
21912 if (tmpl == error_mark_node || args == error_mark_node)
21913 return error_mark_node;
21915 args = coerce_template_parms (DECL_TEMPLATE_PARMS (tmpl),
21916 args, tmpl, complain);
21918 /* FIXME check for satisfaction in check_instantiated_args. */
21919 if (flag_concepts
21920 && !any_dependent_template_arguments_p (args)
21921 && !constraints_satisfied_p (tmpl, args))
21923 if (complain & tf_error)
21925 auto_diagnostic_group d;
21926 error ("template constraint failure for %qD", tmpl);
21927 diagnose_constraints (input_location, tmpl, args);
21929 return error_mark_node;
21932 if (!push_tinst_level (tmpl, args))
21933 return error_mark_node;
21934 tree r = instantiate_template (tmpl, args, complain);
21935 pop_tinst_level ();
21937 if (tree d = dependent_alias_template_spec_p (TREE_TYPE (r), nt_opaque))
21939 /* An alias template specialization can be dependent
21940 even if its underlying type is not. */
21941 TYPE_DEPENDENT_P (d) = true;
21942 TYPE_DEPENDENT_P_VALID (d) = true;
21943 /* Sometimes a dependent alias spec is equivalent to its expansion,
21944 sometimes not. So always use structural_comptypes. */
21945 SET_TYPE_STRUCTURAL_EQUALITY (d);
21948 return r;
21951 /* PARM is a template parameter pack for FN. Returns true iff
21952 PARM is used in a deducible way in the argument list of FN. */
21954 static bool
21955 pack_deducible_p (tree parm, tree fn)
21957 tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
21958 for (; t; t = TREE_CHAIN (t))
21960 tree type = TREE_VALUE (t);
21961 tree packs;
21962 if (!PACK_EXPANSION_P (type))
21963 continue;
21964 for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
21965 packs; packs = TREE_CHAIN (packs))
21966 if (template_args_equal (TREE_VALUE (packs), parm))
21968 /* The template parameter pack is used in a function parameter
21969 pack. If this is the end of the parameter list, the
21970 template parameter pack is deducible. */
21971 if (TREE_CHAIN (t) == void_list_node)
21972 return true;
21973 else
21974 /* Otherwise, not. Well, it could be deduced from
21975 a non-pack parameter, but doing so would end up with
21976 a deduction mismatch, so don't bother. */
21977 return false;
21980 /* The template parameter pack isn't used in any function parameter
21981 packs, but it might be used deeper, e.g. tuple<Args...>. */
21982 return true;
21985 /* Subroutine of fn_type_unification: check non-dependent parms for
21986 convertibility. */
21988 static int
21989 check_non_deducible_conversions (tree parms, const tree *args, unsigned nargs,
21990 tree fn, unification_kind_t strict, int flags,
21991 struct conversion **convs, bool explain_p)
21993 /* Non-constructor methods need to leave a conversion for 'this', which
21994 isn't included in nargs here. */
21995 unsigned offset = (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
21996 && !DECL_CONSTRUCTOR_P (fn));
21998 for (unsigned ia = 0;
21999 parms && parms != void_list_node && ia < nargs; )
22001 tree parm = TREE_VALUE (parms);
22003 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
22004 && (!TREE_CHAIN (parms)
22005 || TREE_CHAIN (parms) == void_list_node))
22006 /* For a function parameter pack that occurs at the end of the
22007 parameter-declaration-list, the type A of each remaining
22008 argument of the call is compared with the type P of the
22009 declarator-id of the function parameter pack. */
22010 break;
22012 parms = TREE_CHAIN (parms);
22014 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
22015 /* For a function parameter pack that does not occur at the
22016 end of the parameter-declaration-list, the type of the
22017 parameter pack is a non-deduced context. */
22018 continue;
22020 if (!uses_template_parms (parm))
22022 tree arg = args[ia];
22023 conversion **conv_p = convs ? &convs[ia+offset] : NULL;
22024 int lflags = conv_flags (ia, nargs, fn, arg, flags);
22026 if (check_non_deducible_conversion (parm, arg, strict, lflags,
22027 conv_p, explain_p))
22028 return 1;
22031 ++ia;
22034 return 0;
22037 /* The FN is a TEMPLATE_DECL for a function. ARGS is an array with
22038 NARGS elements of the arguments that are being used when calling
22039 it. TARGS is a vector into which the deduced template arguments
22040 are placed.
22042 Returns either a FUNCTION_DECL for the matching specialization of FN or
22043 NULL_TREE if no suitable specialization can be found. If EXPLAIN_P is
22044 true, diagnostics will be printed to explain why it failed.
22046 If FN is a conversion operator, or we are trying to produce a specific
22047 specialization, RETURN_TYPE is the return type desired.
22049 The EXPLICIT_TARGS are explicit template arguments provided via a
22050 template-id.
22052 The parameter STRICT is one of:
22054 DEDUCE_CALL:
22055 We are deducing arguments for a function call, as in
22056 [temp.deduct.call]. If RETURN_TYPE is non-null, we are
22057 deducing arguments for a call to the result of a conversion
22058 function template, as in [over.call.object].
22060 DEDUCE_CONV:
22061 We are deducing arguments for a conversion function, as in
22062 [temp.deduct.conv].
22064 DEDUCE_EXACT:
22065 We are deducing arguments when doing an explicit instantiation
22066 as in [temp.explicit], when determining an explicit specialization
22067 as in [temp.expl.spec], or when taking the address of a function
22068 template, as in [temp.deduct.funcaddr]. */
22070 tree
22071 fn_type_unification (tree fn,
22072 tree explicit_targs,
22073 tree targs,
22074 const tree *args,
22075 unsigned int nargs,
22076 tree return_type,
22077 unification_kind_t strict,
22078 int flags,
22079 struct conversion **convs,
22080 bool explain_p,
22081 bool decltype_p)
22083 tree parms;
22084 tree fntype;
22085 tree decl = NULL_TREE;
22086 tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
22087 bool ok;
22088 static int deduction_depth;
22089 /* type_unification_real will pass back any access checks from default
22090 template argument substitution. */
22091 vec<deferred_access_check, va_gc> *checks = NULL;
22092 /* We don't have all the template args yet. */
22093 bool incomplete = true;
22095 tree orig_fn = fn;
22096 if (flag_new_inheriting_ctors)
22097 fn = strip_inheriting_ctors (fn);
22099 tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
22100 tree r = error_mark_node;
22102 tree full_targs = targs;
22103 if (TMPL_ARGS_DEPTH (targs)
22104 < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (fn)))
22105 full_targs = (add_outermost_template_args
22106 (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (fn)),
22107 targs));
22109 if (decltype_p)
22110 complain |= tf_decltype;
22112 /* In C++0x, it's possible to have a function template whose type depends
22113 on itself recursively. This is most obvious with decltype, but can also
22114 occur with enumeration scope (c++/48969). So we need to catch infinite
22115 recursion and reject the substitution at deduction time; this function
22116 will return error_mark_node for any repeated substitution.
22118 This also catches excessive recursion such as when f<N> depends on
22119 f<N-1> across all integers, and returns error_mark_node for all the
22120 substitutions back up to the initial one.
22122 This is, of course, not reentrant. */
22123 if (excessive_deduction_depth)
22124 return error_mark_node;
22125 ++deduction_depth;
22127 gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
22129 fntype = TREE_TYPE (fn);
22130 if (explicit_targs)
22132 /* [temp.deduct]
22134 The specified template arguments must match the template
22135 parameters in kind (i.e., type, nontype, template), and there
22136 must not be more arguments than there are parameters;
22137 otherwise type deduction fails.
22139 Nontype arguments must match the types of the corresponding
22140 nontype template parameters, or must be convertible to the
22141 types of the corresponding nontype parameters as specified in
22142 _temp.arg.nontype_, otherwise type deduction fails.
22144 All references in the function type of the function template
22145 to the corresponding template parameters are replaced by the
22146 specified template argument values. If a substitution in a
22147 template parameter or in the function type of the function
22148 template results in an invalid type, type deduction fails. */
22149 int i, len = TREE_VEC_LENGTH (tparms);
22150 location_t loc = input_location;
22151 incomplete = false;
22153 if (explicit_targs == error_mark_node)
22154 goto fail;
22156 if (TMPL_ARGS_DEPTH (explicit_targs)
22157 < TMPL_ARGS_DEPTH (full_targs))
22158 explicit_targs = add_outermost_template_args (full_targs,
22159 explicit_targs);
22161 /* Adjust any explicit template arguments before entering the
22162 substitution context. */
22163 explicit_targs
22164 = (coerce_template_parms (tparms, explicit_targs, fn,
22165 complain|tf_partial,
22166 /*require_all_args=*/false));
22167 if (explicit_targs == error_mark_node)
22168 goto fail;
22170 /* Substitute the explicit args into the function type. This is
22171 necessary so that, for instance, explicitly declared function
22172 arguments can match null pointed constants. If we were given
22173 an incomplete set of explicit args, we must not do semantic
22174 processing during substitution as we could create partial
22175 instantiations. */
22176 for (i = 0; i < len; i++)
22178 tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
22179 bool parameter_pack = false;
22180 tree targ = TREE_VEC_ELT (explicit_targs, i);
22182 /* Dig out the actual parm. */
22183 if (TREE_CODE (parm) == TYPE_DECL
22184 || TREE_CODE (parm) == TEMPLATE_DECL)
22186 parm = TREE_TYPE (parm);
22187 parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
22189 else if (TREE_CODE (parm) == PARM_DECL)
22191 parm = DECL_INITIAL (parm);
22192 parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
22195 if (targ == NULL_TREE)
22196 /* No explicit argument for this template parameter. */
22197 incomplete = true;
22198 else if (parameter_pack && pack_deducible_p (parm, fn))
22200 /* Mark the argument pack as "incomplete". We could
22201 still deduce more arguments during unification.
22202 We remove this mark in type_unification_real. */
22203 ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
22204 ARGUMENT_PACK_EXPLICIT_ARGS (targ)
22205 = ARGUMENT_PACK_ARGS (targ);
22207 /* We have some incomplete argument packs. */
22208 incomplete = true;
22212 if (incomplete)
22214 if (!push_tinst_level (fn, explicit_targs))
22216 excessive_deduction_depth = true;
22217 goto fail;
22219 ++processing_template_decl;
22220 input_location = DECL_SOURCE_LOCATION (fn);
22221 /* Ignore any access checks; we'll see them again in
22222 instantiate_template and they might have the wrong
22223 access path at this point. */
22224 push_deferring_access_checks (dk_deferred);
22225 tsubst_flags_t ecomplain = complain | tf_partial | tf_fndecl_type;
22226 fntype = tsubst (TREE_TYPE (fn), explicit_targs, ecomplain, NULL_TREE);
22227 pop_deferring_access_checks ();
22228 input_location = loc;
22229 --processing_template_decl;
22230 pop_tinst_level ();
22232 if (fntype == error_mark_node)
22233 goto fail;
22236 /* Place the explicitly specified arguments in TARGS. */
22237 explicit_targs = INNERMOST_TEMPLATE_ARGS (explicit_targs);
22238 for (i = NUM_TMPL_ARGS (explicit_targs); i--;)
22239 TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (explicit_targs, i);
22240 if (!incomplete && CHECKING_P
22241 && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
22242 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
22243 (targs, NUM_TMPL_ARGS (explicit_targs));
22246 if (return_type && strict != DEDUCE_CALL)
22248 tree *new_args = XALLOCAVEC (tree, nargs + 1);
22249 new_args[0] = return_type;
22250 memcpy (new_args + 1, args, nargs * sizeof (tree));
22251 args = new_args;
22252 ++nargs;
22255 if (!incomplete)
22256 goto deduced;
22258 /* Never do unification on the 'this' parameter. */
22259 parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
22261 if (return_type && strict == DEDUCE_CALL)
22263 /* We're deducing for a call to the result of a template conversion
22264 function. The parms we really want are in return_type. */
22265 if (INDIRECT_TYPE_P (return_type))
22266 return_type = TREE_TYPE (return_type);
22267 parms = TYPE_ARG_TYPES (return_type);
22269 else if (return_type)
22271 parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
22274 /* We allow incomplete unification without an error message here
22275 because the standard doesn't seem to explicitly prohibit it. Our
22276 callers must be ready to deal with unification failures in any
22277 event. */
22279 /* If we aren't explaining yet, push tinst context so we can see where
22280 any errors (e.g. from class instantiations triggered by instantiation
22281 of default template arguments) come from. If we are explaining, this
22282 context is redundant. */
22283 if (!explain_p && !push_tinst_level (fn, targs))
22285 excessive_deduction_depth = true;
22286 goto fail;
22289 ok = !type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
22290 full_targs, parms, args, nargs, /*subr=*/0,
22291 strict, &checks, explain_p);
22292 if (!explain_p)
22293 pop_tinst_level ();
22294 if (!ok)
22295 goto fail;
22297 /* Now that we have bindings for all of the template arguments,
22298 ensure that the arguments deduced for the template template
22299 parameters have compatible template parameter lists. We cannot
22300 check this property before we have deduced all template
22301 arguments, because the template parameter types of a template
22302 template parameter might depend on prior template parameters
22303 deduced after the template template parameter. The following
22304 ill-formed example illustrates this issue:
22306 template<typename T, template<T> class C> void f(C<5>, T);
22308 template<int N> struct X {};
22310 void g() {
22311 f(X<5>(), 5l); // error: template argument deduction fails
22314 The template parameter list of 'C' depends on the template type
22315 parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
22316 'long'. Thus, we can't check that 'C' cannot bind to 'X' at the
22317 time that we deduce 'C'. */
22318 if (!template_template_parm_bindings_ok_p
22319 (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
22321 unify_inconsistent_template_template_parameters (explain_p);
22322 goto fail;
22325 deduced:
22327 /* CWG2369: Check satisfaction before non-deducible conversions. */
22328 if (!constraints_satisfied_p (fn, targs))
22330 if (explain_p)
22331 diagnose_constraints (DECL_SOURCE_LOCATION (fn), fn, targs);
22332 goto fail;
22335 /* DR 1391: All parameters have args, now check non-dependent parms for
22336 convertibility. We don't do this if all args were explicitly specified,
22337 as the standard says that we substitute explicit args immediately. */
22338 if (incomplete
22339 && check_non_deducible_conversions (parms, args, nargs, fn, strict, flags,
22340 convs, explain_p))
22341 goto fail;
22343 /* All is well so far. Now, check:
22345 [temp.deduct]
22347 When all template arguments have been deduced, all uses of
22348 template parameters in nondeduced contexts are replaced with
22349 the corresponding deduced argument values. If the
22350 substitution results in an invalid type, as described above,
22351 type deduction fails. */
22352 if (!push_tinst_level (fn, targs))
22354 excessive_deduction_depth = true;
22355 goto fail;
22358 /* Also collect access checks from the instantiation. */
22359 reopen_deferring_access_checks (checks);
22361 decl = instantiate_template (fn, targs, complain);
22363 checks = get_deferred_access_checks ();
22364 pop_deferring_access_checks ();
22366 pop_tinst_level ();
22368 if (decl == error_mark_node)
22369 goto fail;
22371 /* Now perform any access checks encountered during substitution. */
22372 push_access_scope (decl);
22373 ok = perform_access_checks (checks, complain);
22374 pop_access_scope (decl);
22375 if (!ok)
22376 goto fail;
22378 /* If we're looking for an exact match, check that what we got
22379 is indeed an exact match. It might not be if some template
22380 parameters are used in non-deduced contexts. But don't check
22381 for an exact match if we have dependent template arguments;
22382 in that case we're doing partial ordering, and we already know
22383 that we have two candidates that will provide the actual type. */
22384 if (strict == DEDUCE_EXACT && !any_dependent_template_arguments_p (targs))
22386 tree substed = TREE_TYPE (decl);
22387 unsigned int i;
22389 tree sarg
22390 = skip_artificial_parms_for (decl, TYPE_ARG_TYPES (substed));
22391 if (return_type)
22392 sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
22393 for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
22394 if (!same_type_p (args[i], TREE_VALUE (sarg)))
22396 unify_type_mismatch (explain_p, args[i],
22397 TREE_VALUE (sarg));
22398 goto fail;
22400 if ((i < nargs || sarg)
22401 /* add_candidates uses DEDUCE_EXACT for x.operator foo(), but args
22402 doesn't contain the trailing void, and conv fns are always (). */
22403 && !DECL_CONV_FN_P (decl))
22405 unsigned nsargs = i + list_length (sarg);
22406 unify_arity (explain_p, nargs, nsargs);
22407 goto fail;
22411 /* After doing deduction with the inherited constructor, actually return an
22412 instantiation of the inheriting constructor. */
22413 if (orig_fn != fn)
22414 decl = instantiate_template (orig_fn, targs, complain);
22416 r = decl;
22418 fail:
22419 --deduction_depth;
22420 if (excessive_deduction_depth)
22422 if (deduction_depth == 0)
22423 /* Reset once we're all the way out. */
22424 excessive_deduction_depth = false;
22427 return r;
22430 /* Returns true iff PARM is a forwarding reference in the context of
22431 template argument deduction for TMPL. */
22433 static bool
22434 forwarding_reference_p (tree parm, tree tmpl)
22436 /* [temp.deduct.call], "A forwarding reference is an rvalue reference to a
22437 cv-unqualified template parameter ..." */
22438 if (TYPE_REF_P (parm)
22439 && TYPE_REF_IS_RVALUE (parm)
22440 && TREE_CODE (TREE_TYPE (parm)) == TEMPLATE_TYPE_PARM
22441 && cp_type_quals (TREE_TYPE (parm)) == TYPE_UNQUALIFIED)
22443 parm = TREE_TYPE (parm);
22444 /* [temp.deduct.call], "... that does not represent a template parameter
22445 of a class template (during class template argument deduction)." */
22446 if (tmpl
22447 && deduction_guide_p (tmpl)
22448 && DECL_ARTIFICIAL (tmpl))
22450 /* Since the template parameters of a synthesized guide consist of
22451 the template parameters of the class template followed by those of
22452 the constructor (if any), we can tell if PARM represents a template
22453 parameter of the class template by comparing its index with the
22454 arity of the class template. */
22455 tree ctmpl = CLASSTYPE_TI_TEMPLATE (TREE_TYPE (TREE_TYPE (tmpl)));
22456 if (TEMPLATE_TYPE_IDX (parm)
22457 < TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (ctmpl)))
22458 return false;
22460 return true;
22462 return false;
22465 /* Adjust types before performing type deduction, as described in
22466 [temp.deduct.call] and [temp.deduct.conv]. The rules in these two
22467 sections are symmetric. PARM is the type of a function parameter
22468 or the return type of the conversion function. ARG is the type of
22469 the argument passed to the call, or the type of the value
22470 initialized with the result of the conversion function.
22471 ARG_EXPR is the original argument expression, which may be null. */
22473 static int
22474 maybe_adjust_types_for_deduction (tree tparms,
22475 unification_kind_t strict,
22476 tree* parm,
22477 tree* arg,
22478 tree arg_expr)
22480 int result = 0;
22482 switch (strict)
22484 case DEDUCE_CALL:
22485 break;
22487 case DEDUCE_CONV:
22488 /* Swap PARM and ARG throughout the remainder of this
22489 function; the handling is precisely symmetric since PARM
22490 will initialize ARG rather than vice versa. */
22491 std::swap (parm, arg);
22492 break;
22494 case DEDUCE_EXACT:
22495 /* Core issue #873: Do the DR606 thing (see below) for these cases,
22496 too, but here handle it by stripping the reference from PARM
22497 rather than by adding it to ARG. */
22498 if (forwarding_reference_p (*parm, TPARMS_PRIMARY_TEMPLATE (tparms))
22499 && TYPE_REF_P (*arg)
22500 && !TYPE_REF_IS_RVALUE (*arg))
22501 *parm = TREE_TYPE (*parm);
22502 /* Nothing else to do in this case. */
22503 return 0;
22505 default:
22506 gcc_unreachable ();
22509 if (!TYPE_REF_P (*parm))
22511 /* [temp.deduct.call]
22513 If P is not a reference type:
22515 --If A is an array type, the pointer type produced by the
22516 array-to-pointer standard conversion (_conv.array_) is
22517 used in place of A for type deduction; otherwise,
22519 --If A is a function type, the pointer type produced by
22520 the function-to-pointer standard conversion
22521 (_conv.func_) is used in place of A for type deduction;
22522 otherwise,
22524 --If A is a cv-qualified type, the top level
22525 cv-qualifiers of A's type are ignored for type
22526 deduction. */
22527 if (TREE_CODE (*arg) == ARRAY_TYPE)
22528 *arg = build_pointer_type (TREE_TYPE (*arg));
22529 else if (TREE_CODE (*arg) == FUNCTION_TYPE)
22530 *arg = build_pointer_type (*arg);
22531 else
22532 *arg = TYPE_MAIN_VARIANT (*arg);
22535 /* [temp.deduct.call], "If P is a forwarding reference and the argument is
22536 an lvalue, the type 'lvalue reference to A' is used in place of A for
22537 type deduction." */
22538 if (forwarding_reference_p (*parm, TPARMS_PRIMARY_TEMPLATE (tparms))
22539 && (arg_expr ? lvalue_p (arg_expr)
22540 /* try_one_overload doesn't provide an arg_expr, but
22541 functions are always lvalues. */
22542 : TREE_CODE (*arg) == FUNCTION_TYPE))
22543 *arg = build_reference_type (*arg);
22545 /* [temp.deduct.call]
22547 If P is a cv-qualified type, the top level cv-qualifiers
22548 of P's type are ignored for type deduction. If P is a
22549 reference type, the type referred to by P is used for
22550 type deduction. */
22551 *parm = TYPE_MAIN_VARIANT (*parm);
22552 if (TYPE_REF_P (*parm))
22554 *parm = TREE_TYPE (*parm);
22555 result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
22558 /* DR 322. For conversion deduction, remove a reference type on parm
22559 too (which has been swapped into ARG). */
22560 if (strict == DEDUCE_CONV && TYPE_REF_P (*arg))
22561 *arg = TREE_TYPE (*arg);
22563 return result;
22566 /* Subroutine of fn_type_unification. PARM is a function parameter of a
22567 template which doesn't contain any deducible template parameters; check if
22568 ARG is a suitable match for it. STRICT, FLAGS and EXPLAIN_P are as in
22569 unify_one_argument. */
22571 static int
22572 check_non_deducible_conversion (tree parm, tree arg, unification_kind_t strict,
22573 int flags, struct conversion **conv_p,
22574 bool explain_p)
22576 tree type;
22578 if (!TYPE_P (arg))
22579 type = TREE_TYPE (arg);
22580 else
22581 type = arg;
22583 if (same_type_p (parm, type))
22584 return unify_success (explain_p);
22586 tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
22587 if (strict == DEDUCE_CONV)
22589 if (can_convert_arg (type, parm, NULL_TREE, flags, complain))
22590 return unify_success (explain_p);
22592 else if (strict == DEDUCE_CALL)
22594 bool ok = false;
22595 tree conv_arg = TYPE_P (arg) ? NULL_TREE : arg;
22596 if (conv_p)
22597 /* Avoid recalculating this in add_function_candidate. */
22598 ok = (*conv_p
22599 = good_conversion (parm, type, conv_arg, flags, complain));
22600 else
22601 ok = can_convert_arg (parm, type, conv_arg, flags, complain);
22602 if (ok)
22603 return unify_success (explain_p);
22606 if (strict == DEDUCE_EXACT)
22607 return unify_type_mismatch (explain_p, parm, arg);
22608 else
22609 return unify_arg_conversion (explain_p, parm, type, arg);
22612 static bool uses_deducible_template_parms (tree type);
22614 /* Returns true iff the expression EXPR is one from which a template
22615 argument can be deduced. In other words, if it's an undecorated
22616 use of a template non-type parameter. */
22618 static bool
22619 deducible_expression (tree expr)
22621 /* Strip implicit conversions and implicit INDIRECT_REFs. */
22622 while (CONVERT_EXPR_P (expr)
22623 || TREE_CODE (expr) == VIEW_CONVERT_EXPR
22624 || REFERENCE_REF_P (expr))
22625 expr = TREE_OPERAND (expr, 0);
22626 return (TREE_CODE (expr) == TEMPLATE_PARM_INDEX);
22629 /* Returns true iff the array domain DOMAIN uses a template parameter in a
22630 deducible way; that is, if it has a max value of <PARM> - 1. */
22632 static bool
22633 deducible_array_bound (tree domain)
22635 if (domain == NULL_TREE)
22636 return false;
22638 tree max = TYPE_MAX_VALUE (domain);
22639 if (TREE_CODE (max) != MINUS_EXPR)
22640 return false;
22642 return deducible_expression (TREE_OPERAND (max, 0));
22645 /* Returns true iff the template arguments ARGS use a template parameter
22646 in a deducible way. */
22648 static bool
22649 deducible_template_args (tree args)
22651 for (tree elt : tree_vec_range (args))
22653 bool deducible;
22654 if (ARGUMENT_PACK_P (elt))
22655 deducible = deducible_template_args (ARGUMENT_PACK_ARGS (elt));
22656 else
22658 if (PACK_EXPANSION_P (elt))
22659 elt = PACK_EXPANSION_PATTERN (elt);
22660 if (TREE_CODE (elt) == TEMPLATE_TEMPLATE_PARM)
22661 deducible = true;
22662 else if (TYPE_P (elt))
22663 deducible = uses_deducible_template_parms (elt);
22664 else
22665 deducible = deducible_expression (elt);
22667 if (deducible)
22668 return true;
22670 return false;
22673 /* Returns true iff TYPE contains any deducible references to template
22674 parameters, as per 14.8.2.5. */
22676 static bool
22677 uses_deducible_template_parms (tree type)
22679 if (PACK_EXPANSION_P (type))
22680 type = PACK_EXPANSION_PATTERN (type);
22682 /* T
22683 cv-list T
22684 TT<T>
22685 TT<i>
22686 TT<> */
22687 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
22688 || TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
22689 return true;
22691 /* T*
22693 T&& */
22694 if (INDIRECT_TYPE_P (type))
22695 return uses_deducible_template_parms (TREE_TYPE (type));
22697 /* T[integer-constant ]
22698 type [i] */
22699 if (TREE_CODE (type) == ARRAY_TYPE)
22700 return (uses_deducible_template_parms (TREE_TYPE (type))
22701 || deducible_array_bound (TYPE_DOMAIN (type)));
22703 /* T type ::*
22704 type T::*
22705 T T::*
22706 T (type ::*)()
22707 type (T::*)()
22708 type (type ::*)(T)
22709 type (T::*)(T)
22710 T (type ::*)(T)
22711 T (T::*)()
22712 T (T::*)(T) */
22713 if (TYPE_PTRMEM_P (type))
22714 return (uses_deducible_template_parms (TYPE_PTRMEM_CLASS_TYPE (type))
22715 || (uses_deducible_template_parms
22716 (TYPE_PTRMEM_POINTED_TO_TYPE (type))));
22718 /* template-name <T> (where template-name refers to a class template)
22719 template-name <i> (where template-name refers to a class template) */
22720 if (CLASS_TYPE_P (type)
22721 && CLASSTYPE_TEMPLATE_INFO (type)
22722 && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type)))
22723 return deducible_template_args (INNERMOST_TEMPLATE_ARGS
22724 (CLASSTYPE_TI_ARGS (type)));
22726 /* type (T)
22728 T(T) */
22729 if (FUNC_OR_METHOD_TYPE_P (type))
22731 if (uses_deducible_template_parms (TREE_TYPE (type)))
22732 return true;
22733 tree parm = TYPE_ARG_TYPES (type);
22734 if (TREE_CODE (type) == METHOD_TYPE)
22735 parm = TREE_CHAIN (parm);
22736 for (; parm; parm = TREE_CHAIN (parm))
22737 if (uses_deducible_template_parms (TREE_VALUE (parm)))
22738 return true;
22739 if (flag_noexcept_type
22740 && TYPE_RAISES_EXCEPTIONS (type)
22741 && TREE_PURPOSE (TYPE_RAISES_EXCEPTIONS (type))
22742 && deducible_expression (TREE_PURPOSE (TYPE_RAISES_EXCEPTIONS (type))))
22743 return true;
22746 return false;
22749 /* Subroutine of type_unification_real and unify_pack_expansion to
22750 handle unification of a single P/A pair. Parameters are as
22751 for those functions. */
22753 static int
22754 unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
22755 int subr, unification_kind_t strict,
22756 bool explain_p)
22758 tree arg_expr = NULL_TREE;
22759 int arg_strict;
22761 if (arg == error_mark_node || parm == error_mark_node)
22762 return unify_invalid (explain_p);
22763 if (arg == unknown_type_node)
22764 /* We can't deduce anything from this, but we might get all the
22765 template args from other function args. */
22766 return unify_success (explain_p);
22768 /* Implicit conversions (Clause 4) will be performed on a function
22769 argument to convert it to the type of the corresponding function
22770 parameter if the parameter type contains no template-parameters that
22771 participate in template argument deduction. */
22772 if (strict != DEDUCE_EXACT
22773 && TYPE_P (parm) && !uses_deducible_template_parms (parm))
22774 /* For function parameters with no deducible template parameters,
22775 just return. We'll check non-dependent conversions later. */
22776 return unify_success (explain_p);
22778 switch (strict)
22780 case DEDUCE_CALL:
22781 arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
22782 | UNIFY_ALLOW_MORE_CV_QUAL
22783 | UNIFY_ALLOW_DERIVED);
22784 break;
22786 case DEDUCE_CONV:
22787 arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
22788 break;
22790 case DEDUCE_EXACT:
22791 arg_strict = UNIFY_ALLOW_NONE;
22792 break;
22794 default:
22795 gcc_unreachable ();
22798 /* We only do these transformations if this is the top-level
22799 parameter_type_list in a call or declaration matching; in other
22800 situations (nested function declarators, template argument lists) we
22801 won't be comparing a type to an expression, and we don't do any type
22802 adjustments. */
22803 if (!subr)
22805 if (!TYPE_P (arg))
22807 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
22808 if (type_unknown_p (arg))
22810 /* [temp.deduct.type] A template-argument can be
22811 deduced from a pointer to function or pointer
22812 to member function argument if the set of
22813 overloaded functions does not contain function
22814 templates and at most one of a set of
22815 overloaded functions provides a unique
22816 match. */
22817 resolve_overloaded_unification (tparms, targs, parm,
22818 arg, strict,
22819 arg_strict, explain_p);
22820 /* If a unique match was not found, this is a
22821 non-deduced context, so we still succeed. */
22822 return unify_success (explain_p);
22825 arg_expr = arg;
22826 arg = unlowered_expr_type (arg);
22827 if (arg == error_mark_node)
22828 return unify_invalid (explain_p);
22831 arg_strict |= maybe_adjust_types_for_deduction (tparms, strict,
22832 &parm, &arg, arg_expr);
22834 else
22835 if ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
22836 != (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL))
22837 return unify_template_argument_mismatch (explain_p, parm, arg);
22839 /* For deduction from an init-list we need the actual list. */
22840 if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
22841 arg = arg_expr;
22842 return unify (tparms, targs, parm, arg, arg_strict, explain_p);
22845 /* for_each_template_parm callback that always returns 0. */
22847 static int
22848 zero_r (tree, void *)
22850 return 0;
22853 /* for_each_template_parm any_fn callback to handle deduction of a template
22854 type argument from the type of an array bound. */
22856 static int
22857 array_deduction_r (tree t, void *data)
22859 tree_pair_p d = (tree_pair_p)data;
22860 tree &tparms = d->purpose;
22861 tree &targs = d->value;
22863 if (TREE_CODE (t) == ARRAY_TYPE)
22864 if (tree dom = TYPE_DOMAIN (t))
22865 if (tree max = TYPE_MAX_VALUE (dom))
22867 if (TREE_CODE (max) == MINUS_EXPR)
22868 max = TREE_OPERAND (max, 0);
22869 if (TREE_CODE (max) == TEMPLATE_PARM_INDEX)
22870 unify (tparms, targs, TREE_TYPE (max), size_type_node,
22871 UNIFY_ALLOW_NONE, /*explain*/false);
22874 /* Keep walking. */
22875 return 0;
22878 /* Try to deduce any not-yet-deduced template type arguments from the type of
22879 an array bound. This is handled separately from unify because 14.8.2.5 says
22880 "The type of a type parameter is only deduced from an array bound if it is
22881 not otherwise deduced." */
22883 static void
22884 try_array_deduction (tree tparms, tree targs, tree parm)
22886 tree_pair_s data = { tparms, targs };
22887 hash_set<tree> visited;
22888 for_each_template_parm (parm, zero_r, &data, &visited,
22889 /*nondeduced*/false, array_deduction_r);
22892 /* Most parms like fn_type_unification.
22894 If SUBR is 1, we're being called recursively (to unify the
22895 arguments of a function or method parameter of a function
22896 template).
22898 CHECKS is a pointer to a vector of access checks encountered while
22899 substituting default template arguments. */
22901 static int
22902 type_unification_real (tree tparms,
22903 tree full_targs,
22904 tree xparms,
22905 const tree *xargs,
22906 unsigned int xnargs,
22907 int subr,
22908 unification_kind_t strict,
22909 vec<deferred_access_check, va_gc> **checks,
22910 bool explain_p)
22912 tree parm, arg;
22913 int i;
22914 int ntparms = TREE_VEC_LENGTH (tparms);
22915 int saw_undeduced = 0;
22916 tree parms;
22917 const tree *args;
22918 unsigned int nargs;
22919 unsigned int ia;
22921 gcc_assert (TREE_CODE (tparms) == TREE_VEC);
22922 gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
22923 gcc_assert (ntparms > 0);
22925 tree targs = INNERMOST_TEMPLATE_ARGS (full_targs);
22927 /* Reset the number of non-defaulted template arguments contained
22928 in TARGS. */
22929 NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
22931 again:
22932 parms = xparms;
22933 args = xargs;
22934 nargs = xnargs;
22936 /* Only fn_type_unification cares about terminal void. */
22937 if (nargs && args[nargs-1] == void_type_node)
22938 --nargs;
22940 ia = 0;
22941 while (parms && parms != void_list_node
22942 && ia < nargs)
22944 parm = TREE_VALUE (parms);
22946 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
22947 && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
22948 /* For a function parameter pack that occurs at the end of the
22949 parameter-declaration-list, the type A of each remaining
22950 argument of the call is compared with the type P of the
22951 declarator-id of the function parameter pack. */
22952 break;
22954 parms = TREE_CHAIN (parms);
22956 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
22957 /* For a function parameter pack that does not occur at the
22958 end of the parameter-declaration-list, the type of the
22959 parameter pack is a non-deduced context. */
22960 continue;
22962 arg = args[ia];
22963 ++ia;
22965 if (unify_one_argument (tparms, full_targs, parm, arg, subr, strict,
22966 explain_p))
22967 return 1;
22970 if (parms
22971 && parms != void_list_node
22972 && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
22974 /* Unify the remaining arguments with the pack expansion type. */
22975 tree argvec;
22976 tree parmvec = make_tree_vec (1);
22978 /* Allocate a TREE_VEC and copy in all of the arguments */
22979 argvec = make_tree_vec (nargs - ia);
22980 for (i = 0; ia < nargs; ++ia, ++i)
22981 TREE_VEC_ELT (argvec, i) = args[ia];
22983 /* Copy the parameter into parmvec. */
22984 TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
22985 if (unify_pack_expansion (tparms, full_targs, parmvec, argvec, strict,
22986 /*subr=*/subr, explain_p))
22987 return 1;
22989 /* Advance to the end of the list of parameters. */
22990 parms = TREE_CHAIN (parms);
22993 /* Fail if we've reached the end of the parm list, and more args
22994 are present, and the parm list isn't variadic. */
22995 if (ia < nargs && parms == void_list_node)
22996 return unify_too_many_arguments (explain_p, nargs, ia);
22997 /* Fail if parms are left and they don't have default values and
22998 they aren't all deduced as empty packs (c++/57397). This is
22999 consistent with sufficient_parms_p. */
23000 if (parms && parms != void_list_node
23001 && TREE_PURPOSE (parms) == NULL_TREE)
23003 unsigned int count = nargs;
23004 tree p = parms;
23005 bool type_pack_p;
23008 type_pack_p = TREE_CODE (TREE_VALUE (p)) == TYPE_PACK_EXPANSION;
23009 if (!type_pack_p)
23010 count++;
23011 p = TREE_CHAIN (p);
23013 while (p && p != void_list_node);
23014 if (count != nargs)
23015 return unify_too_few_arguments (explain_p, ia, count,
23016 type_pack_p);
23019 if (!subr)
23021 tsubst_flags_t complain = (explain_p
23022 ? tf_warning_or_error
23023 : tf_none);
23024 bool tried_array_deduction = (cxx_dialect < cxx17);
23026 for (i = 0; i < ntparms; i++)
23028 tree targ = TREE_VEC_ELT (targs, i);
23029 tree tparm = TREE_VEC_ELT (tparms, i);
23031 /* Clear the "incomplete" flags on all argument packs now so that
23032 substituting them into later default arguments works. */
23033 if (targ && ARGUMENT_PACK_P (targ))
23035 ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
23036 ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
23039 if (targ || tparm == error_mark_node)
23040 continue;
23041 tparm = TREE_VALUE (tparm);
23043 if (TREE_CODE (tparm) == TYPE_DECL
23044 && !tried_array_deduction)
23046 try_array_deduction (tparms, targs, xparms);
23047 tried_array_deduction = true;
23048 if (TREE_VEC_ELT (targs, i))
23049 continue;
23052 /* If this is an undeduced nontype parameter that depends on
23053 a type parameter, try another pass; its type may have been
23054 deduced from a later argument than the one from which
23055 this parameter can be deduced. */
23056 if (TREE_CODE (tparm) == PARM_DECL
23057 && !is_auto (TREE_TYPE (tparm))
23058 && uses_template_parms (TREE_TYPE (tparm))
23059 && saw_undeduced < 2)
23061 saw_undeduced = 1;
23062 continue;
23065 /* Core issue #226 (C++0x) [temp.deduct]:
23067 If a template argument has not been deduced, its
23068 default template argument, if any, is used.
23070 When we are in C++98 mode, TREE_PURPOSE will either
23071 be NULL_TREE or ERROR_MARK_NODE, so we do not need
23072 to explicitly check cxx_dialect here. */
23073 if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
23074 /* OK, there is a default argument. Wait until after the
23075 conversion check to do substitution. */
23076 continue;
23078 /* If the type parameter is a parameter pack, then it will
23079 be deduced to an empty parameter pack. */
23080 if (template_parameter_pack_p (tparm))
23082 tree arg;
23084 if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
23086 arg = make_node (NONTYPE_ARGUMENT_PACK);
23087 TREE_CONSTANT (arg) = 1;
23089 else
23090 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
23092 ARGUMENT_PACK_ARGS (arg) = make_tree_vec (0);
23094 TREE_VEC_ELT (targs, i) = arg;
23095 continue;
23098 return unify_parameter_deduction_failure (explain_p, tparm);
23101 /* Now substitute into the default template arguments. */
23102 for (i = 0; i < ntparms; i++)
23104 tree targ = TREE_VEC_ELT (targs, i);
23105 tree tparm = TREE_VEC_ELT (tparms, i);
23107 if (targ || tparm == error_mark_node)
23108 continue;
23109 tree parm = TREE_VALUE (tparm);
23110 tree arg = TREE_PURPOSE (tparm);
23111 reopen_deferring_access_checks (*checks);
23112 location_t save_loc = input_location;
23113 if (DECL_P (parm))
23114 input_location = DECL_SOURCE_LOCATION (parm);
23116 if (saw_undeduced == 1
23117 && TREE_CODE (parm) == PARM_DECL
23118 && !is_auto (TREE_TYPE (parm))
23119 && uses_template_parms (TREE_TYPE (parm)))
23121 /* The type of this non-type parameter depends on undeduced
23122 parameters. Don't try to use its default argument yet,
23123 since we might deduce an argument for it on the next pass,
23124 but do check whether the arguments we already have cause
23125 substitution failure, so that that happens before we try
23126 later default arguments (78489). */
23127 ++processing_template_decl;
23128 tree type = tsubst (TREE_TYPE (parm), full_targs, complain,
23129 NULL_TREE);
23130 --processing_template_decl;
23131 if (type == error_mark_node)
23132 arg = error_mark_node;
23133 else
23134 arg = NULL_TREE;
23136 else
23138 /* Even if the call is happening in template context, getting
23139 here means it's non-dependent, and a default argument is
23140 considered a separate definition under [temp.decls], so we can
23141 do this substitution without processing_template_decl. This
23142 is important if the default argument contains something that
23143 might be instantiation-dependent like access (87480). */
23144 processing_template_decl_sentinel s;
23145 tree substed = NULL_TREE;
23146 if (saw_undeduced == 1)
23148 /* First instatiate in template context, in case we still
23149 depend on undeduced template parameters. */
23150 ++processing_template_decl;
23151 substed = tsubst_template_arg (arg, full_targs, complain,
23152 NULL_TREE);
23153 --processing_template_decl;
23154 if (substed != error_mark_node
23155 && !uses_template_parms (substed))
23156 /* We replaced all the tparms, substitute again out of
23157 template context. */
23158 substed = NULL_TREE;
23160 if (!substed)
23161 substed = tsubst_template_arg (arg, full_targs, complain,
23162 NULL_TREE);
23164 if (!uses_template_parms (substed))
23165 arg = convert_template_argument (parm, substed, full_targs,
23166 complain, i, NULL_TREE);
23167 else if (saw_undeduced == 1)
23168 arg = NULL_TREE;
23169 else
23170 arg = error_mark_node;
23173 input_location = save_loc;
23174 *checks = get_deferred_access_checks ();
23175 pop_deferring_access_checks ();
23177 if (arg == error_mark_node)
23178 return 1;
23179 else if (arg)
23181 TREE_VEC_ELT (targs, i) = arg;
23182 /* The position of the first default template argument,
23183 is also the number of non-defaulted arguments in TARGS.
23184 Record that. */
23185 if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
23186 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
23190 if (saw_undeduced++ == 1)
23191 goto again;
23194 if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
23195 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
23197 return unify_success (explain_p);
23200 /* Subroutine of type_unification_real. Args are like the variables
23201 at the call site. ARG is an overloaded function (or template-id);
23202 we try deducing template args from each of the overloads, and if
23203 only one succeeds, we go with that. Modifies TARGS and returns
23204 true on success. */
23206 static bool
23207 resolve_overloaded_unification (tree tparms,
23208 tree targs,
23209 tree parm,
23210 tree arg,
23211 unification_kind_t strict,
23212 int sub_strict,
23213 bool explain_p)
23215 tree tempargs = copy_node (targs);
23216 int good = 0;
23217 tree goodfn = NULL_TREE;
23218 bool addr_p;
23220 if (TREE_CODE (arg) == ADDR_EXPR)
23222 arg = TREE_OPERAND (arg, 0);
23223 addr_p = true;
23225 else
23226 addr_p = false;
23228 if (TREE_CODE (arg) == COMPONENT_REF)
23229 /* Handle `&x' where `x' is some static or non-static member
23230 function name. */
23231 arg = TREE_OPERAND (arg, 1);
23233 if (TREE_CODE (arg) == OFFSET_REF)
23234 arg = TREE_OPERAND (arg, 1);
23236 /* Strip baselink information. */
23237 if (BASELINK_P (arg))
23238 arg = BASELINK_FUNCTIONS (arg);
23240 if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
23242 /* If we got some explicit template args, we need to plug them into
23243 the affected templates before we try to unify, in case the
23244 explicit args will completely resolve the templates in question. */
23246 int ok = 0;
23247 tree expl_subargs = TREE_OPERAND (arg, 1);
23248 arg = TREE_OPERAND (arg, 0);
23250 for (lkp_iterator iter (arg); iter; ++iter)
23252 tree fn = *iter;
23253 tree subargs, elem;
23255 if (TREE_CODE (fn) != TEMPLATE_DECL)
23256 continue;
23258 subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
23259 expl_subargs, NULL_TREE, tf_none);
23260 if (subargs != error_mark_node
23261 && !any_dependent_template_arguments_p (subargs))
23263 fn = instantiate_template (fn, subargs, tf_none);
23264 if (!constraints_satisfied_p (fn))
23265 continue;
23266 if (undeduced_auto_decl (fn))
23268 /* Instantiate the function to deduce its return type. */
23269 ++function_depth;
23270 instantiate_decl (fn, /*defer*/false, /*class*/false);
23271 --function_depth;
23274 if (flag_noexcept_type)
23275 maybe_instantiate_noexcept (fn, tf_none);
23277 elem = TREE_TYPE (fn);
23278 if (try_one_overload (tparms, targs, tempargs, parm,
23279 elem, strict, sub_strict, addr_p, explain_p)
23280 && (!goodfn || !same_type_p (goodfn, elem)))
23282 goodfn = elem;
23283 ++good;
23286 else if (subargs)
23287 ++ok;
23289 /* If no templates (or more than one) are fully resolved by the
23290 explicit arguments, this template-id is a non-deduced context; it
23291 could still be OK if we deduce all template arguments for the
23292 enclosing call through other arguments. */
23293 if (good != 1)
23294 good = ok;
23296 else if (!OVL_P (arg))
23297 /* If ARG is, for example, "(0, &f)" then its type will be unknown
23298 -- but the deduction does not succeed because the expression is
23299 not just the function on its own. */
23300 return false;
23301 else
23302 for (lkp_iterator iter (arg); iter; ++iter)
23304 tree fn = *iter;
23305 if (try_one_overload (tparms, targs, tempargs, parm, TREE_TYPE (fn),
23306 strict, sub_strict, addr_p, explain_p)
23307 && (!goodfn || !decls_match (goodfn, fn)))
23309 goodfn = fn;
23310 ++good;
23314 /* [temp.deduct.type] A template-argument can be deduced from a pointer
23315 to function or pointer to member function argument if the set of
23316 overloaded functions does not contain function templates and at most
23317 one of a set of overloaded functions provides a unique match.
23319 So if we found multiple possibilities, we return success but don't
23320 deduce anything. */
23322 if (good == 1)
23324 int i = TREE_VEC_LENGTH (targs);
23325 for (; i--; )
23326 if (TREE_VEC_ELT (tempargs, i))
23328 tree old = TREE_VEC_ELT (targs, i);
23329 tree new_ = TREE_VEC_ELT (tempargs, i);
23330 if (new_ && old && ARGUMENT_PACK_P (old)
23331 && ARGUMENT_PACK_EXPLICIT_ARGS (old))
23332 /* Don't forget explicit template arguments in a pack. */
23333 ARGUMENT_PACK_EXPLICIT_ARGS (new_)
23334 = ARGUMENT_PACK_EXPLICIT_ARGS (old);
23335 TREE_VEC_ELT (targs, i) = new_;
23338 if (good)
23339 return true;
23341 return false;
23344 /* Core DR 115: In contexts where deduction is done and fails, or in
23345 contexts where deduction is not done, if a template argument list is
23346 specified and it, along with any default template arguments, identifies
23347 a single function template specialization, then the template-id is an
23348 lvalue for the function template specialization. */
23350 tree
23351 resolve_nondeduced_context (tree orig_expr, tsubst_flags_t complain)
23353 tree expr, offset, baselink;
23354 bool addr;
23356 if (!type_unknown_p (orig_expr))
23357 return orig_expr;
23359 expr = orig_expr;
23360 addr = false;
23361 offset = NULL_TREE;
23362 baselink = NULL_TREE;
23364 if (TREE_CODE (expr) == ADDR_EXPR)
23366 expr = TREE_OPERAND (expr, 0);
23367 addr = true;
23369 if (TREE_CODE (expr) == OFFSET_REF)
23371 offset = expr;
23372 expr = TREE_OPERAND (expr, 1);
23374 if (BASELINK_P (expr))
23376 baselink = expr;
23377 expr = BASELINK_FUNCTIONS (expr);
23380 if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
23382 int good = 0;
23383 tree goodfn = NULL_TREE;
23385 /* If we got some explicit template args, we need to plug them into
23386 the affected templates before we try to unify, in case the
23387 explicit args will completely resolve the templates in question. */
23389 tree expl_subargs = TREE_OPERAND (expr, 1);
23390 tree arg = TREE_OPERAND (expr, 0);
23391 tree badfn = NULL_TREE;
23392 tree badargs = NULL_TREE;
23394 for (lkp_iterator iter (arg); iter; ++iter)
23396 tree fn = *iter;
23397 tree subargs, elem;
23399 if (TREE_CODE (fn) != TEMPLATE_DECL)
23400 continue;
23402 subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
23403 expl_subargs, NULL_TREE, tf_none);
23404 if (subargs != error_mark_node
23405 && !any_dependent_template_arguments_p (subargs))
23407 elem = instantiate_template (fn, subargs, tf_none);
23408 if (elem == error_mark_node)
23410 badfn = fn;
23411 badargs = subargs;
23413 else if (elem && (!goodfn || !decls_match (goodfn, elem))
23414 && constraints_satisfied_p (elem))
23416 goodfn = elem;
23417 ++good;
23421 if (good == 1)
23423 mark_used (goodfn);
23424 expr = goodfn;
23425 if (baselink)
23426 expr = build_baselink (BASELINK_BINFO (baselink),
23427 BASELINK_ACCESS_BINFO (baselink),
23428 expr, BASELINK_OPTYPE (baselink));
23429 if (offset)
23431 tree base
23432 = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
23433 expr = build_offset_ref (base, expr, addr, complain);
23435 if (addr)
23436 expr = cp_build_addr_expr (expr, complain);
23437 return expr;
23439 else if (good == 0 && badargs && (complain & tf_error))
23440 /* There were no good options and at least one bad one, so let the
23441 user know what the problem is. */
23442 instantiate_template (badfn, badargs, complain);
23444 return orig_expr;
23447 /* As above, but error out if the expression remains overloaded. */
23449 tree
23450 resolve_nondeduced_context_or_error (tree exp, tsubst_flags_t complain)
23452 exp = resolve_nondeduced_context (exp, complain);
23453 if (type_unknown_p (exp))
23455 if (complain & tf_error)
23456 cxx_incomplete_type_error (exp, TREE_TYPE (exp));
23457 return error_mark_node;
23459 return exp;
23462 /* Subroutine of resolve_overloaded_unification; does deduction for a single
23463 overload. Fills TARGS with any deduced arguments, or error_mark_node if
23464 different overloads deduce different arguments for a given parm.
23465 ADDR_P is true if the expression for which deduction is being
23466 performed was of the form "& fn" rather than simply "fn".
23468 Returns 1 on success. */
23470 static int
23471 try_one_overload (tree tparms,
23472 tree orig_targs,
23473 tree targs,
23474 tree parm,
23475 tree arg,
23476 unification_kind_t strict,
23477 int sub_strict,
23478 bool addr_p,
23479 bool explain_p)
23481 int nargs;
23482 tree tempargs;
23483 int i;
23485 if (arg == error_mark_node)
23486 return 0;
23488 /* [temp.deduct.type] A template-argument can be deduced from a pointer
23489 to function or pointer to member function argument if the set of
23490 overloaded functions does not contain function templates and at most
23491 one of a set of overloaded functions provides a unique match.
23493 So if this is a template, just return success. */
23495 if (uses_template_parms (arg))
23496 return 1;
23498 if (TREE_CODE (arg) == METHOD_TYPE)
23499 arg = build_ptrmemfunc_type (build_pointer_type (arg));
23500 else if (addr_p)
23501 arg = build_pointer_type (arg);
23503 sub_strict |= maybe_adjust_types_for_deduction (tparms, strict,
23504 &parm, &arg, NULL_TREE);
23506 /* We don't copy orig_targs for this because if we have already deduced
23507 some template args from previous args, unify would complain when we
23508 try to deduce a template parameter for the same argument, even though
23509 there isn't really a conflict. */
23510 nargs = TREE_VEC_LENGTH (targs);
23511 tempargs = make_tree_vec (nargs);
23513 if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
23514 return 0;
23516 /* First make sure we didn't deduce anything that conflicts with
23517 explicitly specified args. */
23518 for (i = nargs; i--; )
23520 tree elt = TREE_VEC_ELT (tempargs, i);
23521 tree oldelt = TREE_VEC_ELT (orig_targs, i);
23523 if (!elt)
23524 /*NOP*/;
23525 else if (uses_template_parms (elt))
23526 /* Since we're unifying against ourselves, we will fill in
23527 template args used in the function parm list with our own
23528 template parms. Discard them. */
23529 TREE_VEC_ELT (tempargs, i) = NULL_TREE;
23530 else if (oldelt && ARGUMENT_PACK_P (oldelt))
23532 /* Check that the argument at each index of the deduced argument pack
23533 is equivalent to the corresponding explicitly specified argument.
23534 We may have deduced more arguments than were explicitly specified,
23535 and that's OK. */
23537 /* We used to assert ARGUMENT_PACK_INCOMPLETE_P (oldelt) here, but
23538 that's wrong if we deduce the same argument pack from multiple
23539 function arguments: it's only incomplete the first time. */
23541 tree explicit_pack = ARGUMENT_PACK_ARGS (oldelt);
23542 tree deduced_pack = ARGUMENT_PACK_ARGS (elt);
23544 if (TREE_VEC_LENGTH (deduced_pack)
23545 < TREE_VEC_LENGTH (explicit_pack))
23546 return 0;
23548 for (int j = 0; j < TREE_VEC_LENGTH (explicit_pack); j++)
23549 if (!template_args_equal (TREE_VEC_ELT (explicit_pack, j),
23550 TREE_VEC_ELT (deduced_pack, j)))
23551 return 0;
23553 else if (oldelt && !template_args_equal (oldelt, elt))
23554 return 0;
23557 for (i = nargs; i--; )
23559 tree elt = TREE_VEC_ELT (tempargs, i);
23561 if (elt)
23562 TREE_VEC_ELT (targs, i) = elt;
23565 return 1;
23568 /* PARM is a template class (perhaps with unbound template
23569 parameters). ARG is a fully instantiated type. If ARG can be
23570 bound to PARM, return ARG, otherwise return NULL_TREE. TPARMS and
23571 TARGS are as for unify. */
23573 static tree
23574 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
23575 bool explain_p)
23577 if (!CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
23578 return NULL_TREE;
23579 else if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23580 /* Matches anything. */;
23581 else if (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
23582 != most_general_template (CLASSTYPE_TI_TEMPLATE (parm)))
23583 return NULL_TREE;
23585 /* We need to make a new template argument vector for the call to
23586 unify. If we used TARGS, we'd clutter it up with the result of
23587 the attempted unification, even if this class didn't work out.
23588 We also don't want to commit ourselves to all the unifications
23589 we've already done, since unification is supposed to be done on
23590 an argument-by-argument basis. In other words, consider the
23591 following pathological case:
23593 template <int I, int J, int K>
23594 struct S {};
23596 template <int I, int J>
23597 struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
23599 template <int I, int J, int K>
23600 void f(S<I, J, K>, S<I, I, I>);
23602 void g() {
23603 S<0, 0, 0> s0;
23604 S<0, 1, 2> s2;
23606 f(s0, s2);
23609 Now, by the time we consider the unification involving `s2', we
23610 already know that we must have `f<0, 0, 0>'. But, even though
23611 `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
23612 because there are two ways to unify base classes of S<0, 1, 2>
23613 with S<I, I, I>. If we kept the already deduced knowledge, we
23614 would reject the possibility I=1. */
23615 targs = copy_template_args (targs);
23616 for (tree& targ : tree_vec_range (INNERMOST_TEMPLATE_ARGS (targs)))
23617 targ = NULL_TREE;
23619 int err;
23620 if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23621 err = unify_bound_ttp_args (tparms, targs, parm, arg, explain_p);
23622 else
23623 err = unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
23624 CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE, explain_p);
23626 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
23627 for (tree level : tree_vec_range (targs))
23628 ggc_free (level);
23629 ggc_free (targs);
23631 return err ? NULL_TREE : arg;
23634 /* Given a template type PARM and a class type ARG, find the unique
23635 base type in ARG that is an instance of PARM. We do not examine
23636 ARG itself; only its base-classes. If there is not exactly one
23637 appropriate base class, return NULL_TREE. PARM may be the type of
23638 a partial specialization, as well as a plain template type. Used
23639 by unify. */
23641 static enum template_base_result
23642 get_template_base (tree tparms, tree targs, tree parm, tree arg,
23643 bool explain_p, tree *result)
23645 tree rval = NULL_TREE;
23646 tree binfo;
23648 gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
23650 binfo = TYPE_BINFO (complete_type (arg));
23651 if (!binfo)
23653 /* The type could not be completed. */
23654 *result = NULL_TREE;
23655 return tbr_incomplete_type;
23658 /* Walk in inheritance graph order. The search order is not
23659 important, and this avoids multiple walks of virtual bases. */
23660 for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
23662 tree r = try_class_unification (tparms, targs, parm,
23663 BINFO_TYPE (binfo), explain_p);
23665 if (r)
23667 /* If there is more than one satisfactory baseclass, then:
23669 [temp.deduct.call]
23671 If they yield more than one possible deduced A, the type
23672 deduction fails.
23674 applies. */
23675 if (rval && !same_type_p (r, rval))
23677 /* [temp.deduct.call]/4.3: If there is a class C that is a
23678 (direct or indirect) base class of D and derived (directly or
23679 indirectly) from a class B and that would be a valid deduced
23680 A, the deduced A cannot be B or pointer to B, respectively. */
23681 if (DERIVED_FROM_P (r, rval))
23682 /* Ignore r. */
23683 continue;
23684 else if (DERIVED_FROM_P (rval, r))
23685 /* Ignore rval. */;
23686 else
23688 *result = NULL_TREE;
23689 return tbr_ambiguous_baseclass;
23693 rval = r;
23697 *result = rval;
23698 return tbr_success;
23701 /* Returns the level of DECL, which declares a template parameter. */
23703 static int
23704 template_decl_level (tree decl)
23706 switch (TREE_CODE (decl))
23708 case TYPE_DECL:
23709 case TEMPLATE_DECL:
23710 return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
23712 case PARM_DECL:
23713 return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
23715 default:
23716 gcc_unreachable ();
23718 return 0;
23721 /* Decide whether ARG can be unified with PARM, considering only the
23722 cv-qualifiers of each type, given STRICT as documented for unify.
23723 Returns nonzero iff the unification is OK on that basis. */
23725 static int
23726 check_cv_quals_for_unify (int strict, tree arg, tree parm)
23728 int arg_quals = cp_type_quals (arg);
23729 int parm_quals = cp_type_quals (parm);
23731 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
23732 && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
23734 /* Although a CVR qualifier is ignored when being applied to a
23735 substituted template parameter ([8.3.2]/1 for example), that
23736 does not allow us to unify "const T" with "int&" because both
23737 types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
23738 It is ok when we're allowing additional CV qualifiers
23739 at the outer level [14.8.2.1]/3,1st bullet. */
23740 if ((TYPE_REF_P (arg)
23741 || FUNC_OR_METHOD_TYPE_P (arg))
23742 && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
23743 return 0;
23745 if ((!INDIRECT_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
23746 && (parm_quals & TYPE_QUAL_RESTRICT))
23747 return 0;
23750 if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
23751 && (arg_quals & parm_quals) != parm_quals)
23752 return 0;
23754 if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
23755 && (parm_quals & arg_quals) != arg_quals)
23756 return 0;
23758 return 1;
23761 /* Determines the LEVEL and INDEX for the template parameter PARM. */
23762 void
23763 template_parm_level_and_index (tree parm, int* level, int* index)
23765 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
23766 || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
23767 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23769 *index = TEMPLATE_TYPE_IDX (parm);
23770 *level = TEMPLATE_TYPE_LEVEL (parm);
23772 else
23774 *index = TEMPLATE_PARM_IDX (parm);
23775 *level = TEMPLATE_PARM_LEVEL (parm);
23779 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP) \
23780 do { \
23781 if (unify (TP, TA, P, A, S, EP)) \
23782 return 1; \
23783 } while (0)
23785 /* Unifies the remaining arguments in PACKED_ARGS with the pack
23786 expansion at the end of PACKED_PARMS. Returns 0 if the type
23787 deduction succeeds, 1 otherwise. STRICT is the same as in
23788 fn_type_unification. CALL_ARGS_P is true iff PACKED_ARGS is actually a
23789 function call argument list. We'll need to adjust the arguments to make them
23790 types. SUBR tells us if this is from a recursive call to
23791 type_unification_real, or for comparing two template argument
23792 lists. */
23794 static int
23795 unify_pack_expansion (tree tparms, tree targs, tree packed_parms,
23796 tree packed_args, unification_kind_t strict,
23797 bool subr, bool explain_p)
23799 tree parm
23800 = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
23801 tree pattern = PACK_EXPANSION_PATTERN (parm);
23802 tree pack, packs = NULL_TREE;
23803 int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
23805 /* Add in any args remembered from an earlier partial instantiation. */
23806 targs = add_to_template_args (PACK_EXPANSION_EXTRA_ARGS (parm), targs);
23807 int levels = TMPL_ARGS_DEPTH (targs);
23809 packed_args = expand_template_argument_pack (packed_args);
23811 int len = TREE_VEC_LENGTH (packed_args);
23813 /* Determine the parameter packs we will be deducing from the
23814 pattern, and record their current deductions. */
23815 for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm);
23816 pack; pack = TREE_CHAIN (pack))
23818 tree parm_pack = TREE_VALUE (pack);
23819 int idx, level;
23821 /* Only template parameter packs can be deduced, not e.g. function
23822 parameter packs or __bases or __integer_pack. */
23823 if (!TEMPLATE_PARM_P (parm_pack))
23824 continue;
23826 /* Determine the index and level of this parameter pack. */
23827 template_parm_level_and_index (parm_pack, &level, &idx);
23828 if (level > levels)
23829 continue;
23831 /* Keep track of the parameter packs and their corresponding
23832 argument packs. */
23833 packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
23834 TREE_TYPE (packs) = make_tree_vec (len - start);
23837 /* Loop through all of the arguments that have not yet been
23838 unified and unify each with the pattern. */
23839 for (i = start; i < len; i++)
23841 tree parm;
23842 bool any_explicit = false;
23843 tree arg = TREE_VEC_ELT (packed_args, i);
23845 /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
23846 or the element of its argument pack at the current index if
23847 this argument was explicitly specified. */
23848 for (pack = packs; pack; pack = TREE_CHAIN (pack))
23850 int idx, level;
23851 tree arg, pargs;
23852 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
23854 arg = NULL_TREE;
23855 if (TREE_VALUE (pack)
23856 && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
23857 && (i - start < TREE_VEC_LENGTH (pargs)))
23859 any_explicit = true;
23860 arg = TREE_VEC_ELT (pargs, i - start);
23862 TMPL_ARG (targs, level, idx) = arg;
23865 /* If we had explicit template arguments, substitute them into the
23866 pattern before deduction. */
23867 if (any_explicit)
23869 /* Some arguments might still be unspecified or dependent. */
23870 bool dependent;
23871 ++processing_template_decl;
23872 dependent = any_dependent_template_arguments_p (targs);
23873 if (!dependent)
23874 --processing_template_decl;
23875 parm = tsubst (pattern, targs,
23876 explain_p ? tf_warning_or_error : tf_none,
23877 NULL_TREE);
23878 if (dependent)
23879 --processing_template_decl;
23880 if (parm == error_mark_node)
23881 return 1;
23883 else
23884 parm = pattern;
23886 /* Unify the pattern with the current argument. */
23887 if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
23888 explain_p))
23889 return 1;
23891 /* For each parameter pack, collect the deduced value. */
23892 for (pack = packs; pack; pack = TREE_CHAIN (pack))
23894 int idx, level;
23895 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
23897 TREE_VEC_ELT (TREE_TYPE (pack), i - start) =
23898 TMPL_ARG (targs, level, idx);
23902 /* Verify that the results of unification with the parameter packs
23903 produce results consistent with what we've seen before, and make
23904 the deduced argument packs available. */
23905 for (pack = packs; pack; pack = TREE_CHAIN (pack))
23907 tree old_pack = TREE_VALUE (pack);
23908 tree new_args = TREE_TYPE (pack);
23909 int i, len = TREE_VEC_LENGTH (new_args);
23910 int idx, level;
23911 bool nondeduced_p = false;
23913 /* By default keep the original deduced argument pack.
23914 If necessary, more specific code is going to update the
23915 resulting deduced argument later down in this function. */
23916 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
23917 TMPL_ARG (targs, level, idx) = old_pack;
23919 /* If NEW_ARGS contains any NULL_TREE entries, we didn't
23920 actually deduce anything. */
23921 for (i = 0; i < len && !nondeduced_p; ++i)
23922 if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
23923 nondeduced_p = true;
23924 if (nondeduced_p)
23925 continue;
23927 if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
23929 /* If we had fewer function args than explicit template args,
23930 just use the explicits. */
23931 tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
23932 int explicit_len = TREE_VEC_LENGTH (explicit_args);
23933 if (len < explicit_len)
23934 new_args = explicit_args;
23937 if (!old_pack)
23939 tree result;
23940 /* Build the deduced *_ARGUMENT_PACK. */
23941 if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
23943 result = make_node (NONTYPE_ARGUMENT_PACK);
23944 TREE_CONSTANT (result) = 1;
23946 else
23947 result = cxx_make_type (TYPE_ARGUMENT_PACK);
23949 ARGUMENT_PACK_ARGS (result) = new_args;
23951 /* Note the deduced argument packs for this parameter
23952 pack. */
23953 TMPL_ARG (targs, level, idx) = result;
23955 else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
23956 && (ARGUMENT_PACK_ARGS (old_pack)
23957 == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
23959 /* We only had the explicitly-provided arguments before, but
23960 now we have a complete set of arguments. */
23961 tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
23963 ARGUMENT_PACK_ARGS (old_pack) = new_args;
23964 ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
23965 ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
23967 else
23969 tree bad_old_arg = NULL_TREE, bad_new_arg = NULL_TREE;
23970 tree old_args = ARGUMENT_PACK_ARGS (old_pack);
23971 temp_override<int> ovl (TREE_VEC_LENGTH (old_args));
23972 /* During template argument deduction for the aggregate deduction
23973 candidate, the number of elements in a trailing parameter pack
23974 is only deduced from the number of remaining function
23975 arguments if it is not otherwise deduced. */
23976 if (cxx_dialect >= cxx20
23977 && TREE_VEC_LENGTH (new_args) < TREE_VEC_LENGTH (old_args)
23978 && builtin_guide_p (TPARMS_PRIMARY_TEMPLATE (tparms)))
23979 TREE_VEC_LENGTH (old_args) = TREE_VEC_LENGTH (new_args);
23980 if (!comp_template_args (old_args, new_args,
23981 &bad_old_arg, &bad_new_arg))
23982 /* Inconsistent unification of this parameter pack. */
23983 return unify_parameter_pack_inconsistent (explain_p,
23984 bad_old_arg,
23985 bad_new_arg);
23989 return unify_success (explain_p);
23992 /* Handle unification of the domain of an array. PARM_DOM and ARG_DOM are
23993 INTEGER_TYPEs representing the TYPE_DOMAIN of ARRAY_TYPEs. The other
23994 parameters and return value are as for unify. */
23996 static int
23997 unify_array_domain (tree tparms, tree targs,
23998 tree parm_dom, tree arg_dom,
23999 bool explain_p)
24001 tree parm_max;
24002 tree arg_max;
24003 bool parm_cst;
24004 bool arg_cst;
24006 /* Our representation of array types uses "N - 1" as the
24007 TYPE_MAX_VALUE for an array with "N" elements, if "N" is
24008 not an integer constant. We cannot unify arbitrarily
24009 complex expressions, so we eliminate the MINUS_EXPRs
24010 here. */
24011 parm_max = TYPE_MAX_VALUE (parm_dom);
24012 parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
24013 if (!parm_cst)
24015 gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
24016 parm_max = TREE_OPERAND (parm_max, 0);
24018 arg_max = TYPE_MAX_VALUE (arg_dom);
24019 arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
24020 if (!arg_cst)
24022 /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
24023 trying to unify the type of a variable with the type
24024 of a template parameter. For example:
24026 template <unsigned int N>
24027 void f (char (&) [N]);
24028 int g();
24029 void h(int i) {
24030 char a[g(i)];
24031 f(a);
24034 Here, the type of the ARG will be "int [g(i)]", and
24035 may be a SAVE_EXPR, etc. */
24036 if (TREE_CODE (arg_max) != MINUS_EXPR)
24037 return unify_vla_arg (explain_p, arg_dom);
24038 arg_max = TREE_OPERAND (arg_max, 0);
24041 /* If only one of the bounds used a MINUS_EXPR, compensate
24042 by adding one to the other bound. */
24043 if (parm_cst && !arg_cst)
24044 parm_max = fold_build2_loc (input_location, PLUS_EXPR,
24045 integer_type_node,
24046 parm_max,
24047 integer_one_node);
24048 else if (arg_cst && !parm_cst)
24049 arg_max = fold_build2_loc (input_location, PLUS_EXPR,
24050 integer_type_node,
24051 arg_max,
24052 integer_one_node);
24054 return unify (tparms, targs, parm_max, arg_max,
24055 UNIFY_ALLOW_INTEGER, explain_p);
24058 /* Returns whether T, a P or A in unify, is a type, template or expression. */
24060 enum pa_kind_t { pa_type, pa_tmpl, pa_expr };
24062 static pa_kind_t
24063 pa_kind (tree t)
24065 if (PACK_EXPANSION_P (t))
24066 t = PACK_EXPANSION_PATTERN (t);
24067 if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM
24068 || TREE_CODE (t) == UNBOUND_CLASS_TEMPLATE
24069 || DECL_TYPE_TEMPLATE_P (t))
24070 return pa_tmpl;
24071 else if (TYPE_P (t))
24072 return pa_type;
24073 else
24074 return pa_expr;
24077 /* Deduce the value of template parameters. TPARMS is the (innermost)
24078 set of template parameters to a template. TARGS is the bindings
24079 for those template parameters, as determined thus far; TARGS may
24080 include template arguments for outer levels of template parameters
24081 as well. PARM is a parameter to a template function, or a
24082 subcomponent of that parameter; ARG is the corresponding argument.
24083 This function attempts to match PARM with ARG in a manner
24084 consistent with the existing assignments in TARGS. If more values
24085 are deduced, then TARGS is updated.
24087 Returns 0 if the type deduction succeeds, 1 otherwise. The
24088 parameter STRICT is a bitwise or of the following flags:
24090 UNIFY_ALLOW_NONE:
24091 Require an exact match between PARM and ARG.
24092 UNIFY_ALLOW_MORE_CV_QUAL:
24093 Allow the deduced ARG to be more cv-qualified (by qualification
24094 conversion) than ARG.
24095 UNIFY_ALLOW_LESS_CV_QUAL:
24096 Allow the deduced ARG to be less cv-qualified than ARG.
24097 UNIFY_ALLOW_DERIVED:
24098 Allow the deduced ARG to be a template base class of ARG,
24099 or a pointer to a template base class of the type pointed to by
24100 ARG.
24101 UNIFY_ALLOW_INTEGER:
24102 Allow any integral type to be deduced. See the TEMPLATE_PARM_INDEX
24103 case for more information.
24104 UNIFY_ALLOW_OUTER_LEVEL:
24105 This is the outermost level of a deduction. Used to determine validity
24106 of qualification conversions. A valid qualification conversion must
24107 have const qualified pointers leading up to the inner type which
24108 requires additional CV quals, except at the outer level, where const
24109 is not required [conv.qual]. It would be normal to set this flag in
24110 addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
24111 UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
24112 This is the outermost level of a deduction, and PARM can be more CV
24113 qualified at this point.
24114 UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
24115 This is the outermost level of a deduction, and PARM can be less CV
24116 qualified at this point. */
24118 static int
24119 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
24120 bool explain_p)
24122 int idx;
24123 tree targ;
24124 tree tparm;
24125 int strict_in = strict;
24126 tsubst_flags_t complain = (explain_p
24127 ? tf_warning_or_error
24128 : tf_none);
24130 /* I don't think this will do the right thing with respect to types.
24131 But the only case I've seen it in so far has been array bounds, where
24132 signedness is the only information lost, and I think that will be
24133 okay. VIEW_CONVERT_EXPR can appear with class NTTP, thanks to
24134 finish_id_expression_1, and are also OK. */
24135 while (CONVERT_EXPR_P (parm) || TREE_CODE (parm) == VIEW_CONVERT_EXPR)
24136 parm = TREE_OPERAND (parm, 0);
24138 if (arg == error_mark_node)
24139 return unify_invalid (explain_p);
24140 if (arg == unknown_type_node
24141 || arg == init_list_type_node)
24142 /* We can't deduce anything from this, but we might get all the
24143 template args from other function args. */
24144 return unify_success (explain_p);
24146 if (parm == any_targ_node || arg == any_targ_node)
24147 return unify_success (explain_p);
24149 /* If PARM uses template parameters, then we can't bail out here,
24150 even if ARG == PARM, since we won't record unifications for the
24151 template parameters. We might need them if we're trying to
24152 figure out which of two things is more specialized. */
24153 if (arg == parm && !uses_template_parms (parm))
24154 return unify_success (explain_p);
24156 /* Handle init lists early, so the rest of the function can assume
24157 we're dealing with a type. */
24158 if (BRACE_ENCLOSED_INITIALIZER_P (arg))
24160 tree elttype;
24161 tree orig_parm = parm;
24163 if (!is_std_init_list (parm)
24164 && TREE_CODE (parm) != ARRAY_TYPE)
24165 /* We can only deduce from an initializer list argument if the
24166 parameter is std::initializer_list or an array; otherwise this
24167 is a non-deduced context. */
24168 return unify_success (explain_p);
24170 if (TREE_CODE (parm) == ARRAY_TYPE)
24171 elttype = TREE_TYPE (parm);
24172 else
24174 elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
24175 /* Deduction is defined in terms of a single type, so just punt
24176 on the (bizarre) std::initializer_list<T...>. */
24177 if (PACK_EXPANSION_P (elttype))
24178 return unify_success (explain_p);
24181 if (strict != DEDUCE_EXACT
24182 && TYPE_P (elttype)
24183 && !uses_deducible_template_parms (elttype))
24184 /* If ELTTYPE has no deducible template parms, skip deduction from
24185 the list elements. */;
24186 else
24187 for (auto &e: CONSTRUCTOR_ELTS (arg))
24189 tree elt = e.value;
24190 int elt_strict = strict;
24192 if (elt == error_mark_node)
24193 return unify_invalid (explain_p);
24195 if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
24197 tree type = TREE_TYPE (elt);
24198 if (type == error_mark_node)
24199 return unify_invalid (explain_p);
24200 /* It should only be possible to get here for a call. */
24201 gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
24202 elt_strict |= maybe_adjust_types_for_deduction
24203 (tparms, DEDUCE_CALL, &elttype, &type, elt);
24204 elt = type;
24207 RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
24208 explain_p);
24211 if (TREE_CODE (parm) == ARRAY_TYPE
24212 && deducible_array_bound (TYPE_DOMAIN (parm)))
24214 /* Also deduce from the length of the initializer list. */
24215 tree max = size_int (CONSTRUCTOR_NELTS (arg));
24216 tree idx = compute_array_index_type (NULL_TREE, max, tf_none);
24217 if (idx == error_mark_node)
24218 return unify_invalid (explain_p);
24219 return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
24220 idx, explain_p);
24223 /* If the std::initializer_list<T> deduction worked, replace the
24224 deduced A with std::initializer_list<A>. */
24225 if (orig_parm != parm)
24227 idx = TEMPLATE_TYPE_IDX (orig_parm);
24228 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
24229 targ = listify (targ);
24230 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
24232 return unify_success (explain_p);
24235 /* If parm and arg aren't the same kind of thing (template, type, or
24236 expression), fail early. */
24237 if (pa_kind (parm) != pa_kind (arg))
24238 return unify_invalid (explain_p);
24240 /* Immediately reject some pairs that won't unify because of
24241 cv-qualification mismatches. */
24242 if (TREE_CODE (arg) == TREE_CODE (parm)
24243 && TYPE_P (arg)
24244 /* It is the elements of the array which hold the cv quals of an array
24245 type, and the elements might be template type parms. We'll check
24246 when we recurse. */
24247 && TREE_CODE (arg) != ARRAY_TYPE
24248 /* We check the cv-qualifiers when unifying with template type
24249 parameters below. We want to allow ARG `const T' to unify with
24250 PARM `T' for example, when computing which of two templates
24251 is more specialized, for example. */
24252 && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
24253 && !check_cv_quals_for_unify (strict_in, arg, parm))
24254 return unify_cv_qual_mismatch (explain_p, parm, arg);
24256 if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
24257 && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
24258 strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
24259 strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
24260 strict &= ~UNIFY_ALLOW_DERIVED;
24261 strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
24262 strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
24264 switch (TREE_CODE (parm))
24266 case TYPENAME_TYPE:
24267 case SCOPE_REF:
24268 case UNBOUND_CLASS_TEMPLATE:
24269 /* In a type which contains a nested-name-specifier, template
24270 argument values cannot be deduced for template parameters used
24271 within the nested-name-specifier. */
24272 return unify_success (explain_p);
24274 case TEMPLATE_TYPE_PARM:
24275 case TEMPLATE_TEMPLATE_PARM:
24276 case BOUND_TEMPLATE_TEMPLATE_PARM:
24277 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
24278 if (error_operand_p (tparm))
24279 return unify_invalid (explain_p);
24281 if (TEMPLATE_TYPE_LEVEL (parm)
24282 != template_decl_level (tparm))
24283 /* The PARM is not one we're trying to unify. Just check
24284 to see if it matches ARG. */
24286 if (TREE_CODE (arg) == TREE_CODE (parm)
24287 && (is_auto (parm) ? is_auto (arg)
24288 : same_type_p (parm, arg)))
24289 return unify_success (explain_p);
24290 else
24291 return unify_type_mismatch (explain_p, parm, arg);
24293 idx = TEMPLATE_TYPE_IDX (parm);
24294 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
24295 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
24296 if (error_operand_p (tparm))
24297 return unify_invalid (explain_p);
24299 /* Check for mixed types and values. */
24300 if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
24301 && TREE_CODE (tparm) != TYPE_DECL)
24302 || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
24303 && TREE_CODE (tparm) != TEMPLATE_DECL))
24304 gcc_unreachable ();
24306 if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
24308 if ((strict_in & UNIFY_ALLOW_DERIVED)
24309 && CLASS_TYPE_P (arg))
24311 /* First try to match ARG directly. */
24312 tree t = try_class_unification (tparms, targs, parm, arg,
24313 explain_p);
24314 if (!t)
24316 /* Otherwise, look for a suitable base of ARG, as below. */
24317 enum template_base_result r;
24318 r = get_template_base (tparms, targs, parm, arg,
24319 explain_p, &t);
24320 if (!t)
24321 return unify_no_common_base (explain_p, r, parm, arg);
24322 arg = t;
24325 /* ARG must be constructed from a template class or a template
24326 template parameter. */
24327 else if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
24328 && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
24329 return unify_template_deduction_failure (explain_p, parm, arg);
24331 /* Deduce arguments T, i from TT<T> or TT<i>. */
24332 if (unify_bound_ttp_args (tparms, targs, parm, arg, explain_p))
24333 return 1;
24335 arg = TYPE_TI_TEMPLATE (arg);
24336 if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg))
24337 /* If the template is a template template parameter, use the
24338 TEMPLATE_TEMPLATE_PARM for matching. */
24339 arg = TREE_TYPE (arg);
24341 /* Fall through to deduce template name. */
24344 if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
24345 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
24347 /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>. */
24349 /* Simple cases: Value already set, does match or doesn't. */
24350 if (targ != NULL_TREE && template_args_equal (targ, arg))
24351 return unify_success (explain_p);
24352 else if (targ)
24353 return unify_inconsistency (explain_p, parm, targ, arg);
24355 else
24357 /* If PARM is `const T' and ARG is only `int', we don't have
24358 a match unless we are allowing additional qualification.
24359 If ARG is `const int' and PARM is just `T' that's OK;
24360 that binds `const int' to `T'. */
24361 if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
24362 arg, parm))
24363 return unify_cv_qual_mismatch (explain_p, parm, arg);
24365 /* Consider the case where ARG is `const volatile int' and
24366 PARM is `const T'. Then, T should be `volatile int'. */
24367 arg = cp_build_qualified_type
24368 (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
24369 if (arg == error_mark_node)
24370 return unify_invalid (explain_p);
24372 /* Simple cases: Value already set, does match or doesn't. */
24373 if (targ != NULL_TREE && same_type_p (targ, arg))
24374 return unify_success (explain_p);
24375 else if (targ)
24376 return unify_inconsistency (explain_p, parm, targ, arg);
24378 /* Make sure that ARG is not a variable-sized array. (Note
24379 that were talking about variable-sized arrays (like
24380 `int[n]'), rather than arrays of unknown size (like
24381 `int[]').) We'll get very confused by such a type since
24382 the bound of the array is not constant, and therefore
24383 not mangleable. Besides, such types are not allowed in
24384 ISO C++, so we can do as we please here. We do allow
24385 them for 'auto' deduction, since that isn't ABI-exposed. */
24386 if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
24387 return unify_vla_arg (explain_p, arg);
24389 /* Strip typedefs as in convert_template_argument. */
24390 arg = canonicalize_type_argument (arg, tf_none);
24393 /* If ARG is a parameter pack or an expansion, we cannot unify
24394 against it unless PARM is also a parameter pack. */
24395 if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
24396 && !template_parameter_pack_p (parm))
24397 return unify_parameter_pack_mismatch (explain_p, parm, arg);
24399 /* If the argument deduction results is a METHOD_TYPE,
24400 then there is a problem.
24401 METHOD_TYPE doesn't map to any real C++ type the result of
24402 the deduction cannot be of that type. */
24403 if (TREE_CODE (arg) == METHOD_TYPE)
24404 return unify_method_type_error (explain_p, arg);
24406 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
24407 return unify_success (explain_p);
24409 case TEMPLATE_PARM_INDEX:
24410 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
24411 if (error_operand_p (tparm))
24412 return unify_invalid (explain_p);
24414 if (TEMPLATE_PARM_LEVEL (parm)
24415 != template_decl_level (tparm))
24417 /* The PARM is not one we're trying to unify. Just check
24418 to see if it matches ARG. */
24419 int result = !(TREE_CODE (arg) == TREE_CODE (parm)
24420 && cp_tree_equal (parm, arg));
24421 if (result)
24422 unify_expression_unequal (explain_p, parm, arg);
24423 return result;
24426 idx = TEMPLATE_PARM_IDX (parm);
24427 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
24429 if (targ)
24431 if ((strict & UNIFY_ALLOW_INTEGER)
24432 && TREE_TYPE (targ) && TREE_TYPE (arg)
24433 && CP_INTEGRAL_TYPE_P (TREE_TYPE (targ)))
24434 /* We're deducing from an array bound, the type doesn't matter. */
24435 arg = fold_convert (TREE_TYPE (targ), arg);
24436 int x = !cp_tree_equal (targ, arg);
24437 if (x)
24438 unify_inconsistency (explain_p, parm, targ, arg);
24439 return x;
24442 /* [temp.deduct.type] If, in the declaration of a function template
24443 with a non-type template-parameter, the non-type
24444 template-parameter is used in an expression in the function
24445 parameter-list and, if the corresponding template-argument is
24446 deduced, the template-argument type shall match the type of the
24447 template-parameter exactly, except that a template-argument
24448 deduced from an array bound may be of any integral type.
24449 The non-type parameter might use already deduced type parameters. */
24450 tparm = TREE_TYPE (parm);
24451 if (TEMPLATE_PARM_LEVEL (parm) > TMPL_ARGS_DEPTH (targs))
24452 /* We don't have enough levels of args to do any substitution. This
24453 can happen in the context of -fnew-ttp-matching. */;
24454 else
24456 ++processing_template_decl;
24457 tparm = tsubst (tparm, targs, tf_none, NULL_TREE);
24458 --processing_template_decl;
24460 if (tree a = type_uses_auto (tparm))
24462 tparm = do_auto_deduction (tparm, arg, a,
24463 complain, adc_unify, targs);
24464 if (tparm == error_mark_node)
24465 return 1;
24469 if (!TREE_TYPE (arg)
24470 || TREE_CODE (TREE_TYPE (arg)) == DEPENDENT_OPERATOR_TYPE)
24471 /* Template-parameter dependent expression. Just accept it for now.
24472 It will later be processed in convert_template_argument. */
24474 else if (same_type_ignoring_top_level_qualifiers_p
24475 (non_reference (TREE_TYPE (arg)),
24476 non_reference (tparm)))
24477 /* OK. Ignore top-level quals here because a class-type template
24478 parameter object is const. */;
24479 else if ((strict & UNIFY_ALLOW_INTEGER)
24480 && CP_INTEGRAL_TYPE_P (tparm))
24481 /* Convert the ARG to the type of PARM; the deduced non-type
24482 template argument must exactly match the types of the
24483 corresponding parameter. */
24484 arg = fold (build_nop (tparm, arg));
24485 else if (uses_template_parms (tparm))
24487 /* We haven't deduced the type of this parameter yet. */
24488 if (cxx_dialect >= cxx17
24489 /* We deduce from array bounds in try_array_deduction. */
24490 && !(strict & UNIFY_ALLOW_INTEGER)
24491 && TEMPLATE_PARM_LEVEL (parm) <= TMPL_ARGS_DEPTH (targs))
24493 /* Deduce it from the non-type argument. As above, ignore
24494 top-level quals here too. */
24495 tree atype = cv_unqualified (TREE_TYPE (arg));
24496 RECUR_AND_CHECK_FAILURE (tparms, targs,
24497 tparm, atype,
24498 UNIFY_ALLOW_NONE, explain_p);
24499 /* Now check whether the type of this parameter is still
24500 dependent, and give up if so. */
24501 ++processing_template_decl;
24502 tparm = tsubst (TREE_TYPE (parm), targs, tf_none, NULL_TREE);
24503 --processing_template_decl;
24504 if (uses_template_parms (tparm))
24505 return unify_success (explain_p);
24507 else
24508 /* Try again later. */
24509 return unify_success (explain_p);
24511 else
24512 return unify_type_mismatch (explain_p, tparm, TREE_TYPE (arg));
24514 /* If ARG is a parameter pack or an expansion, we cannot unify
24515 against it unless PARM is also a parameter pack. */
24516 if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
24517 && !TEMPLATE_PARM_PARAMETER_PACK (parm))
24518 return unify_parameter_pack_mismatch (explain_p, parm, arg);
24521 bool removed_attr = false;
24522 arg = strip_typedefs_expr (arg, &removed_attr);
24524 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
24525 return unify_success (explain_p);
24527 case PTRMEM_CST:
24529 /* A pointer-to-member constant can be unified only with
24530 another constant. */
24531 if (TREE_CODE (arg) != PTRMEM_CST)
24532 return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
24534 /* Just unify the class member. It would be useless (and possibly
24535 wrong, depending on the strict flags) to unify also
24536 PTRMEM_CST_CLASS, because we want to be sure that both parm and
24537 arg refer to the same variable, even if through different
24538 classes. For instance:
24540 struct A { int x; };
24541 struct B : A { };
24543 Unification of &A::x and &B::x must succeed. */
24544 return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
24545 PTRMEM_CST_MEMBER (arg), strict, explain_p);
24548 case POINTER_TYPE:
24550 if (!TYPE_PTR_P (arg))
24551 return unify_type_mismatch (explain_p, parm, arg);
24553 /* [temp.deduct.call]
24555 A can be another pointer or pointer to member type that can
24556 be converted to the deduced A via a qualification
24557 conversion (_conv.qual_).
24559 We pass down STRICT here rather than UNIFY_ALLOW_NONE.
24560 This will allow for additional cv-qualification of the
24561 pointed-to types if appropriate. */
24563 if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
24564 /* The derived-to-base conversion only persists through one
24565 level of pointers. */
24566 strict |= (strict_in & UNIFY_ALLOW_DERIVED);
24568 return unify (tparms, targs, TREE_TYPE (parm),
24569 TREE_TYPE (arg), strict, explain_p);
24572 case REFERENCE_TYPE:
24573 if (!TYPE_REF_P (arg))
24574 return unify_type_mismatch (explain_p, parm, arg);
24575 return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
24576 strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
24578 case ARRAY_TYPE:
24579 if (TREE_CODE (arg) != ARRAY_TYPE)
24580 return unify_type_mismatch (explain_p, parm, arg);
24581 if ((TYPE_DOMAIN (parm) == NULL_TREE)
24582 != (TYPE_DOMAIN (arg) == NULL_TREE))
24583 return unify_type_mismatch (explain_p, parm, arg);
24584 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
24585 strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
24586 if (TYPE_DOMAIN (parm) != NULL_TREE)
24587 return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
24588 TYPE_DOMAIN (arg), explain_p);
24589 return unify_success (explain_p);
24591 case REAL_TYPE:
24592 case COMPLEX_TYPE:
24593 case VECTOR_TYPE:
24594 case INTEGER_TYPE:
24595 case BOOLEAN_TYPE:
24596 case ENUMERAL_TYPE:
24597 case VOID_TYPE:
24598 case OPAQUE_TYPE:
24599 case NULLPTR_TYPE:
24600 if (TREE_CODE (arg) != TREE_CODE (parm))
24601 return unify_type_mismatch (explain_p, parm, arg);
24603 /* We have already checked cv-qualification at the top of the
24604 function. */
24605 if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
24606 return unify_type_mismatch (explain_p, parm, arg);
24608 /* As far as unification is concerned, this wins. Later checks
24609 will invalidate it if necessary. */
24610 return unify_success (explain_p);
24612 /* Types INTEGER_CST and MINUS_EXPR can come from array bounds. */
24613 /* Type INTEGER_CST can come from ordinary constant template args. */
24614 case INTEGER_CST:
24615 while (CONVERT_EXPR_P (arg))
24616 arg = TREE_OPERAND (arg, 0);
24618 if (TREE_CODE (arg) != INTEGER_CST)
24619 return unify_template_argument_mismatch (explain_p, parm, arg);
24620 return (tree_int_cst_equal (parm, arg)
24621 ? unify_success (explain_p)
24622 : unify_template_argument_mismatch (explain_p, parm, arg));
24624 case TREE_VEC:
24626 int i, len, argslen;
24627 int parm_variadic_p = 0;
24629 if (TREE_CODE (arg) != TREE_VEC)
24630 return unify_template_argument_mismatch (explain_p, parm, arg);
24632 len = TREE_VEC_LENGTH (parm);
24633 argslen = TREE_VEC_LENGTH (arg);
24635 /* Check for pack expansions in the parameters. */
24636 for (i = 0; i < len; ++i)
24638 if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
24640 if (i == len - 1)
24641 /* We can unify against something with a trailing
24642 parameter pack. */
24643 parm_variadic_p = 1;
24644 else
24645 /* [temp.deduct.type]/9: If the template argument list of
24646 P contains a pack expansion that is not the last
24647 template argument, the entire template argument list
24648 is a non-deduced context. */
24649 return unify_success (explain_p);
24653 /* If we don't have enough arguments to satisfy the parameters
24654 (not counting the pack expression at the end), or we have
24655 too many arguments for a parameter list that doesn't end in
24656 a pack expression, we can't unify. */
24657 if (parm_variadic_p
24658 ? argslen < len - parm_variadic_p
24659 : argslen != len)
24660 return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
24662 /* Unify all of the parameters that precede the (optional)
24663 pack expression. */
24664 for (i = 0; i < len - parm_variadic_p; ++i)
24666 RECUR_AND_CHECK_FAILURE (tparms, targs,
24667 TREE_VEC_ELT (parm, i),
24668 TREE_VEC_ELT (arg, i),
24669 UNIFY_ALLOW_NONE, explain_p);
24671 if (parm_variadic_p)
24672 return unify_pack_expansion (tparms, targs, parm, arg,
24673 DEDUCE_EXACT,
24674 /*subr=*/true, explain_p);
24675 return unify_success (explain_p);
24678 case RECORD_TYPE:
24679 case UNION_TYPE:
24680 if (TREE_CODE (arg) != TREE_CODE (parm))
24681 return unify_type_mismatch (explain_p, parm, arg);
24683 if (TYPE_PTRMEMFUNC_P (parm))
24685 if (!TYPE_PTRMEMFUNC_P (arg))
24686 return unify_type_mismatch (explain_p, parm, arg);
24688 return unify (tparms, targs,
24689 TYPE_PTRMEMFUNC_FN_TYPE (parm),
24690 TYPE_PTRMEMFUNC_FN_TYPE (arg),
24691 strict, explain_p);
24693 else if (TYPE_PTRMEMFUNC_P (arg))
24694 return unify_type_mismatch (explain_p, parm, arg);
24696 if (CLASSTYPE_TEMPLATE_INFO (parm))
24698 tree t = NULL_TREE;
24700 if (strict_in & UNIFY_ALLOW_DERIVED)
24702 /* First, we try to unify the PARM and ARG directly. */
24703 t = try_class_unification (tparms, targs,
24704 parm, arg, explain_p);
24706 if (!t)
24708 /* Fallback to the special case allowed in
24709 [temp.deduct.call]:
24711 If P is a class, and P has the form
24712 template-id, then A can be a derived class of
24713 the deduced A. Likewise, if P is a pointer to
24714 a class of the form template-id, A can be a
24715 pointer to a derived class pointed to by the
24716 deduced A. */
24717 enum template_base_result r;
24718 r = get_template_base (tparms, targs, parm, arg,
24719 explain_p, &t);
24721 if (!t)
24723 /* Don't give the derived diagnostic if we're
24724 already dealing with the same template. */
24725 bool same_template
24726 = (CLASSTYPE_TEMPLATE_INFO (arg)
24727 && (CLASSTYPE_TI_TEMPLATE (parm)
24728 == CLASSTYPE_TI_TEMPLATE (arg)));
24729 return unify_no_common_base (explain_p && !same_template,
24730 r, parm, arg);
24734 else if (CLASSTYPE_TEMPLATE_INFO (arg)
24735 && (CLASSTYPE_TI_TEMPLATE (parm)
24736 == CLASSTYPE_TI_TEMPLATE (arg)))
24737 /* Perhaps PARM is something like S<U> and ARG is S<int>.
24738 Then, we should unify `int' and `U'. */
24739 t = arg;
24740 else
24741 /* There's no chance of unification succeeding. */
24742 return unify_type_mismatch (explain_p, parm, arg);
24744 return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
24745 CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE, explain_p);
24747 else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
24748 return unify_type_mismatch (explain_p, parm, arg);
24749 return unify_success (explain_p);
24751 case METHOD_TYPE:
24752 case FUNCTION_TYPE:
24754 unsigned int nargs;
24755 tree *args;
24756 tree a;
24757 unsigned int i;
24759 if (TREE_CODE (arg) != TREE_CODE (parm))
24760 return unify_type_mismatch (explain_p, parm, arg);
24762 /* CV qualifications for methods can never be deduced, they must
24763 match exactly. We need to check them explicitly here,
24764 because type_unification_real treats them as any other
24765 cv-qualified parameter. */
24766 if (TREE_CODE (parm) == METHOD_TYPE
24767 && (!check_cv_quals_for_unify
24768 (UNIFY_ALLOW_NONE,
24769 class_of_this_parm (arg),
24770 class_of_this_parm (parm))))
24771 return unify_cv_qual_mismatch (explain_p, parm, arg);
24772 if (TREE_CODE (arg) == FUNCTION_TYPE
24773 && type_memfn_quals (parm) != type_memfn_quals (arg))
24774 return unify_cv_qual_mismatch (explain_p, parm, arg);
24775 if (type_memfn_rqual (parm) != type_memfn_rqual (arg))
24776 return unify_type_mismatch (explain_p, parm, arg);
24778 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
24779 TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
24781 nargs = list_length (TYPE_ARG_TYPES (arg));
24782 args = XALLOCAVEC (tree, nargs);
24783 for (a = TYPE_ARG_TYPES (arg), i = 0;
24784 a != NULL_TREE && a != void_list_node;
24785 a = TREE_CHAIN (a), ++i)
24786 args[i] = TREE_VALUE (a);
24787 nargs = i;
24789 if (type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
24790 args, nargs, 1, DEDUCE_EXACT,
24791 NULL, explain_p))
24792 return 1;
24794 if (flag_noexcept_type)
24796 tree pspec = TYPE_RAISES_EXCEPTIONS (parm);
24797 tree aspec = canonical_eh_spec (TYPE_RAISES_EXCEPTIONS (arg));
24798 if (pspec == NULL_TREE) pspec = noexcept_false_spec;
24799 if (aspec == NULL_TREE) aspec = noexcept_false_spec;
24800 if (TREE_PURPOSE (pspec) && TREE_PURPOSE (aspec)
24801 && uses_template_parms (TREE_PURPOSE (pspec)))
24802 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_PURPOSE (pspec),
24803 TREE_PURPOSE (aspec),
24804 UNIFY_ALLOW_NONE, explain_p);
24805 else if (nothrow_spec_p (pspec) && !nothrow_spec_p (aspec))
24806 return unify_type_mismatch (explain_p, parm, arg);
24809 return 0;
24812 case OFFSET_TYPE:
24813 /* Unify a pointer to member with a pointer to member function, which
24814 deduces the type of the member as a function type. */
24815 if (TYPE_PTRMEMFUNC_P (arg))
24817 /* Check top-level cv qualifiers */
24818 if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
24819 return unify_cv_qual_mismatch (explain_p, parm, arg);
24821 RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
24822 TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
24823 UNIFY_ALLOW_NONE, explain_p);
24825 /* Determine the type of the function we are unifying against. */
24826 tree fntype = static_fn_type (arg);
24828 return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
24831 if (TREE_CODE (arg) != OFFSET_TYPE)
24832 return unify_type_mismatch (explain_p, parm, arg);
24833 RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
24834 TYPE_OFFSET_BASETYPE (arg),
24835 UNIFY_ALLOW_NONE, explain_p);
24836 return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
24837 strict, explain_p);
24839 case CONST_DECL:
24840 if (DECL_TEMPLATE_PARM_P (parm))
24841 return unify (tparms, targs, DECL_INITIAL (parm), arg, strict, explain_p);
24842 if (arg != scalar_constant_value (parm))
24843 return unify_template_argument_mismatch (explain_p, parm, arg);
24844 return unify_success (explain_p);
24846 case FIELD_DECL:
24847 case TEMPLATE_DECL:
24848 /* Matched cases are handled by the ARG == PARM test above. */
24849 return unify_template_argument_mismatch (explain_p, parm, arg);
24851 case VAR_DECL:
24852 /* We might get a variable as a non-type template argument in parm if the
24853 corresponding parameter is type-dependent. Make any necessary
24854 adjustments based on whether arg is a reference. */
24855 if (CONSTANT_CLASS_P (arg))
24856 parm = fold_non_dependent_expr (parm, complain);
24857 else if (REFERENCE_REF_P (arg))
24859 tree sub = TREE_OPERAND (arg, 0);
24860 STRIP_NOPS (sub);
24861 if (TREE_CODE (sub) == ADDR_EXPR)
24862 arg = TREE_OPERAND (sub, 0);
24864 /* Now use the normal expression code to check whether they match. */
24865 goto expr;
24867 case TYPE_ARGUMENT_PACK:
24868 case NONTYPE_ARGUMENT_PACK:
24869 return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
24870 ARGUMENT_PACK_ARGS (arg), strict, explain_p);
24872 case TYPEOF_TYPE:
24873 case DECLTYPE_TYPE:
24874 case TRAIT_TYPE:
24875 /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
24876 or TRAIT_TYPE nodes. */
24877 return unify_success (explain_p);
24879 case ERROR_MARK:
24880 /* Unification fails if we hit an error node. */
24881 return unify_invalid (explain_p);
24883 case INDIRECT_REF:
24884 if (REFERENCE_REF_P (parm))
24886 bool pexp = PACK_EXPANSION_P (arg);
24887 if (pexp)
24888 arg = PACK_EXPANSION_PATTERN (arg);
24889 if (REFERENCE_REF_P (arg))
24890 arg = TREE_OPERAND (arg, 0);
24891 if (pexp)
24892 arg = make_pack_expansion (arg, complain);
24893 return unify (tparms, targs, TREE_OPERAND (parm, 0), arg,
24894 strict, explain_p);
24896 /* FALLTHRU */
24898 default:
24899 /* An unresolved overload is a nondeduced context. */
24900 if (is_overloaded_fn (parm) || type_unknown_p (parm))
24901 return unify_success (explain_p);
24902 gcc_assert (EXPR_P (parm)
24903 || TREE_CODE (parm) == CONSTRUCTOR
24904 || TREE_CODE (parm) == TRAIT_EXPR);
24905 expr:
24906 /* We must be looking at an expression. This can happen with
24907 something like:
24909 template <int I>
24910 void foo(S<I>, S<I + 2>);
24914 template<typename T>
24915 void foo(A<T, T{}>);
24917 This is a "non-deduced context":
24919 [deduct.type]
24921 The non-deduced contexts are:
24923 --A non-type template argument or an array bound in which
24924 a subexpression references a template parameter.
24926 In these cases, we assume deduction succeeded, but don't
24927 actually infer any unifications. */
24929 if (!uses_template_parms (parm)
24930 && !template_args_equal (parm, arg))
24931 return unify_expression_unequal (explain_p, parm, arg);
24932 else
24933 return unify_success (explain_p);
24936 #undef RECUR_AND_CHECK_FAILURE
24938 /* Note that DECL can be defined in this translation unit, if
24939 required. */
24941 static void
24942 mark_definable (tree decl)
24944 tree clone;
24945 DECL_NOT_REALLY_EXTERN (decl) = 1;
24946 FOR_EACH_CLONE (clone, decl)
24947 DECL_NOT_REALLY_EXTERN (clone) = 1;
24950 /* Called if RESULT is explicitly instantiated, or is a member of an
24951 explicitly instantiated class. */
24953 void
24954 mark_decl_instantiated (tree result, int extern_p)
24956 SET_DECL_EXPLICIT_INSTANTIATION (result);
24958 /* If this entity has already been written out, it's too late to
24959 make any modifications. */
24960 if (TREE_ASM_WRITTEN (result))
24961 return;
24963 /* consteval functions are never emitted. */
24964 if (TREE_CODE (result) == FUNCTION_DECL
24965 && DECL_IMMEDIATE_FUNCTION_P (result))
24966 return;
24968 /* For anonymous namespace we don't need to do anything. */
24969 if (decl_internal_context_p (result))
24971 gcc_assert (!TREE_PUBLIC (result));
24972 return;
24975 if (TREE_CODE (result) != FUNCTION_DECL)
24976 /* The TREE_PUBLIC flag for function declarations will have been
24977 set correctly by tsubst. */
24978 TREE_PUBLIC (result) = 1;
24980 if (extern_p)
24982 DECL_EXTERNAL (result) = 1;
24983 DECL_NOT_REALLY_EXTERN (result) = 0;
24985 else
24987 mark_definable (result);
24988 mark_needed (result);
24989 /* Always make artificials weak. */
24990 if (DECL_ARTIFICIAL (result) && flag_weak)
24991 comdat_linkage (result);
24992 /* For WIN32 we also want to put explicit instantiations in
24993 linkonce sections. */
24994 else if (TREE_PUBLIC (result))
24995 maybe_make_one_only (result);
24996 if (TREE_CODE (result) == FUNCTION_DECL
24997 && DECL_TEMPLATE_INSTANTIATED (result))
24998 /* If the function has already been instantiated, clear DECL_EXTERNAL,
24999 since start_preparsed_function wouldn't have if we had an earlier
25000 extern explicit instantiation. */
25001 DECL_EXTERNAL (result) = 0;
25004 /* If EXTERN_P, then this function will not be emitted -- unless
25005 followed by an explicit instantiation, at which point its linkage
25006 will be adjusted. If !EXTERN_P, then this function will be
25007 emitted here. In neither circumstance do we want
25008 import_export_decl to adjust the linkage. */
25009 DECL_INTERFACE_KNOWN (result) = 1;
25012 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
25013 important template arguments. If any are missing, we check whether
25014 they're important by using error_mark_node for substituting into any
25015 args that were used for partial ordering (the ones between ARGS and END)
25016 and seeing if it bubbles up. */
25018 static bool
25019 check_undeduced_parms (tree targs, tree args, tree end)
25021 bool found = false;
25022 for (tree& targ : tree_vec_range (targs))
25023 if (targ == NULL_TREE)
25025 found = true;
25026 targ = error_mark_node;
25028 if (found)
25030 tree substed = tsubst_arg_types (args, targs, end, tf_none, NULL_TREE);
25031 if (substed == error_mark_node)
25032 return true;
25034 return false;
25037 /* Given two function templates PAT1 and PAT2, return:
25039 1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
25040 -1 if PAT2 is more specialized than PAT1.
25041 0 if neither is more specialized.
25043 LEN indicates the number of parameters we should consider
25044 (defaulted parameters should not be considered).
25046 The 1998 std underspecified function template partial ordering, and
25047 DR214 addresses the issue. We take pairs of arguments, one from
25048 each of the templates, and deduce them against each other. One of
25049 the templates will be more specialized if all the *other*
25050 template's arguments deduce against its arguments and at least one
25051 of its arguments *does* *not* deduce against the other template's
25052 corresponding argument. Deduction is done as for class templates.
25053 The arguments used in deduction have reference and top level cv
25054 qualifiers removed. Iff both arguments were originally reference
25055 types *and* deduction succeeds in both directions, an lvalue reference
25056 wins against an rvalue reference and otherwise the template
25057 with the more cv-qualified argument wins for that pairing (if
25058 neither is more cv-qualified, they both are equal). Unlike regular
25059 deduction, after all the arguments have been deduced in this way,
25060 we do *not* verify the deduced template argument values can be
25061 substituted into non-deduced contexts.
25063 The logic can be a bit confusing here, because we look at deduce1 and
25064 targs1 to see if pat2 is at least as specialized, and vice versa; if we
25065 can find template arguments for pat1 to make arg1 look like arg2, that
25066 means that arg2 is at least as specialized as arg1. */
25069 more_specialized_fn (tree pat1, tree pat2, int len)
25071 tree decl1 = DECL_TEMPLATE_RESULT (pat1);
25072 tree decl2 = DECL_TEMPLATE_RESULT (pat2);
25073 tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
25074 tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
25075 tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
25076 tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
25077 tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
25078 tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
25079 tree origs1, origs2;
25080 bool lose1 = false;
25081 bool lose2 = false;
25083 /* Remove the this parameter from non-static member functions. If
25084 one is a non-static member function and the other is not a static
25085 member function, remove the first parameter from that function
25086 also. This situation occurs for operator functions where we
25087 locate both a member function (with this pointer) and non-member
25088 operator (with explicit first operand). */
25089 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
25091 len--; /* LEN is the number of significant arguments for DECL1 */
25092 args1 = TREE_CHAIN (args1);
25093 if (!DECL_STATIC_FUNCTION_P (decl2))
25094 args2 = TREE_CHAIN (args2);
25096 else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
25098 args2 = TREE_CHAIN (args2);
25099 if (!DECL_STATIC_FUNCTION_P (decl1))
25101 len--;
25102 args1 = TREE_CHAIN (args1);
25106 /* If only one is a conversion operator, they are unordered. */
25107 if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
25108 return 0;
25110 /* Consider the return type for a conversion function */
25111 if (DECL_CONV_FN_P (decl1))
25113 args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
25114 args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
25115 len++;
25118 processing_template_decl++;
25120 origs1 = args1;
25121 origs2 = args2;
25123 while (len--
25124 /* Stop when an ellipsis is seen. */
25125 && args1 != NULL_TREE && args2 != NULL_TREE)
25127 tree arg1 = TREE_VALUE (args1);
25128 tree arg2 = TREE_VALUE (args2);
25129 int deduce1, deduce2;
25130 int quals1 = -1;
25131 int quals2 = -1;
25132 int ref1 = 0;
25133 int ref2 = 0;
25135 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
25136 && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25138 /* When both arguments are pack expansions, we need only
25139 unify the patterns themselves. */
25140 arg1 = PACK_EXPANSION_PATTERN (arg1);
25141 arg2 = PACK_EXPANSION_PATTERN (arg2);
25143 /* This is the last comparison we need to do. */
25144 len = 0;
25147 if (TYPE_REF_P (arg1))
25149 ref1 = TYPE_REF_IS_RVALUE (arg1) + 1;
25150 arg1 = TREE_TYPE (arg1);
25151 quals1 = cp_type_quals (arg1);
25154 if (TYPE_REF_P (arg2))
25156 ref2 = TYPE_REF_IS_RVALUE (arg2) + 1;
25157 arg2 = TREE_TYPE (arg2);
25158 quals2 = cp_type_quals (arg2);
25161 arg1 = TYPE_MAIN_VARIANT (arg1);
25162 arg2 = TYPE_MAIN_VARIANT (arg2);
25164 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
25166 int i, len2 = remaining_arguments (args2);
25167 tree parmvec = make_tree_vec (1);
25168 tree argvec = make_tree_vec (len2);
25169 tree ta = args2;
25171 /* Setup the parameter vector, which contains only ARG1. */
25172 TREE_VEC_ELT (parmvec, 0) = arg1;
25174 /* Setup the argument vector, which contains the remaining
25175 arguments. */
25176 for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
25177 TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
25179 deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
25180 argvec, DEDUCE_EXACT,
25181 /*subr=*/true, /*explain_p=*/false)
25182 == 0);
25184 /* We cannot deduce in the other direction, because ARG1 is
25185 a pack expansion but ARG2 is not. */
25186 deduce2 = 0;
25188 else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25190 int i, len1 = remaining_arguments (args1);
25191 tree parmvec = make_tree_vec (1);
25192 tree argvec = make_tree_vec (len1);
25193 tree ta = args1;
25195 /* Setup the parameter vector, which contains only ARG1. */
25196 TREE_VEC_ELT (parmvec, 0) = arg2;
25198 /* Setup the argument vector, which contains the remaining
25199 arguments. */
25200 for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
25201 TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
25203 deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
25204 argvec, DEDUCE_EXACT,
25205 /*subr=*/true, /*explain_p=*/false)
25206 == 0);
25208 /* We cannot deduce in the other direction, because ARG2 is
25209 a pack expansion but ARG1 is not.*/
25210 deduce1 = 0;
25213 else
25215 /* The normal case, where neither argument is a pack
25216 expansion. */
25217 deduce1 = (unify (tparms1, targs1, arg1, arg2,
25218 UNIFY_ALLOW_NONE, /*explain_p=*/false)
25219 == 0);
25220 deduce2 = (unify (tparms2, targs2, arg2, arg1,
25221 UNIFY_ALLOW_NONE, /*explain_p=*/false)
25222 == 0);
25225 /* If we couldn't deduce arguments for tparms1 to make arg1 match
25226 arg2, then arg2 is not as specialized as arg1. */
25227 if (!deduce1)
25228 lose2 = true;
25229 if (!deduce2)
25230 lose1 = true;
25232 /* "If, for a given type, deduction succeeds in both directions
25233 (i.e., the types are identical after the transformations above)
25234 and both P and A were reference types (before being replaced with
25235 the type referred to above):
25236 - if the type from the argument template was an lvalue reference and
25237 the type from the parameter template was not, the argument type is
25238 considered to be more specialized than the other; otherwise,
25239 - if the type from the argument template is more cv-qualified
25240 than the type from the parameter template (as described above),
25241 the argument type is considered to be more specialized than the other;
25242 otherwise,
25243 - neither type is more specialized than the other." */
25245 if (deduce1 && deduce2)
25247 if (ref1 && ref2 && ref1 != ref2)
25249 if (ref1 > ref2)
25250 lose1 = true;
25251 else
25252 lose2 = true;
25254 else if (quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
25256 if ((quals1 & quals2) == quals2)
25257 lose2 = true;
25258 if ((quals1 & quals2) == quals1)
25259 lose1 = true;
25263 if (lose1 && lose2)
25264 /* We've failed to deduce something in either direction.
25265 These must be unordered. */
25266 break;
25268 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
25269 || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25270 /* We have already processed all of the arguments in our
25271 handing of the pack expansion type. */
25272 len = 0;
25274 args1 = TREE_CHAIN (args1);
25275 args2 = TREE_CHAIN (args2);
25278 /* "In most cases, all template parameters must have values in order for
25279 deduction to succeed, but for partial ordering purposes a template
25280 parameter may remain without a value provided it is not used in the
25281 types being used for partial ordering."
25283 Thus, if we are missing any of the targs1 we need to substitute into
25284 origs1, then pat2 is not as specialized as pat1. This can happen when
25285 there is a nondeduced context. */
25286 if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
25287 lose2 = true;
25288 if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
25289 lose1 = true;
25291 processing_template_decl--;
25293 /* If both deductions succeed, the partial ordering selects the more
25294 constrained template. */
25295 /* P2113: If the corresponding template-parameters of the
25296 template-parameter-lists are not equivalent ([temp.over.link]) or if
25297 the function parameters that positionally correspond between the two
25298 templates are not of the same type, neither template is more
25299 specialized than the other. */
25300 if (!lose1 && !lose2
25301 && comp_template_parms (DECL_TEMPLATE_PARMS (pat1),
25302 DECL_TEMPLATE_PARMS (pat2))
25303 && compparms (origs1, origs2))
25305 int winner = more_constrained (decl1, decl2);
25306 if (winner > 0)
25307 lose2 = true;
25308 else if (winner < 0)
25309 lose1 = true;
25312 /* All things being equal, if the next argument is a pack expansion
25313 for one function but not for the other, prefer the
25314 non-variadic function. FIXME this is bogus; see c++/41958. */
25315 if (lose1 == lose2
25316 && args1 && TREE_VALUE (args1)
25317 && args2 && TREE_VALUE (args2))
25319 lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
25320 lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
25323 if (lose1 == lose2)
25324 return 0;
25325 else if (!lose1)
25326 return 1;
25327 else
25328 return -1;
25331 /* Determine which of two partial specializations of TMPL is more
25332 specialized.
25334 PAT1 is a TREE_LIST whose TREE_VALUE is the TEMPLATE_DECL corresponding
25335 to the first partial specialization. The TREE_PURPOSE is the
25336 innermost set of template parameters for the partial
25337 specialization. PAT2 is similar, but for the second template.
25339 Return 1 if the first partial specialization is more specialized;
25340 -1 if the second is more specialized; 0 if neither is more
25341 specialized.
25343 See [temp.class.order] for information about determining which of
25344 two templates is more specialized. */
25346 static int
25347 more_specialized_partial_spec (tree tmpl, tree pat1, tree pat2)
25349 tree targs;
25350 int winner = 0;
25351 bool any_deductions = false;
25353 tree tmpl1 = TREE_VALUE (pat1);
25354 tree tmpl2 = TREE_VALUE (pat2);
25355 tree specargs1 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl1)));
25356 tree specargs2 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl2)));
25358 /* Just like what happens for functions, if we are ordering between
25359 different template specializations, we may encounter dependent
25360 types in the arguments, and we need our dependency check functions
25361 to behave correctly. */
25362 ++processing_template_decl;
25363 targs = get_partial_spec_bindings (tmpl, tmpl1, specargs2);
25364 if (targs)
25366 --winner;
25367 any_deductions = true;
25370 targs = get_partial_spec_bindings (tmpl, tmpl2, specargs1);
25371 if (targs)
25373 ++winner;
25374 any_deductions = true;
25376 --processing_template_decl;
25378 /* If both deductions succeed, the partial ordering selects the more
25379 constrained template. */
25380 if (!winner && any_deductions)
25381 winner = more_constrained (tmpl1, tmpl2);
25383 /* In the case of a tie where at least one of the templates
25384 has a parameter pack at the end, the template with the most
25385 non-packed parameters wins. */
25386 if (winner == 0
25387 && any_deductions
25388 && (template_args_variadic_p (TREE_PURPOSE (pat1))
25389 || template_args_variadic_p (TREE_PURPOSE (pat2))))
25391 tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
25392 tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
25393 int len1 = TREE_VEC_LENGTH (args1);
25394 int len2 = TREE_VEC_LENGTH (args2);
25396 /* We don't count the pack expansion at the end. */
25397 if (template_args_variadic_p (TREE_PURPOSE (pat1)))
25398 --len1;
25399 if (template_args_variadic_p (TREE_PURPOSE (pat2)))
25400 --len2;
25402 if (len1 > len2)
25403 return 1;
25404 else if (len1 < len2)
25405 return -1;
25408 return winner;
25411 /* Return the template arguments that will produce the function signature
25412 DECL from the function template FN, with the explicit template
25413 arguments EXPLICIT_ARGS. If CHECK_RETTYPE is true, the return type must
25414 also match. Return NULL_TREE if no satisfactory arguments could be
25415 found. */
25417 static tree
25418 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
25420 int ntparms = DECL_NTPARMS (fn);
25421 tree targs = make_tree_vec (ntparms);
25422 tree decl_type = TREE_TYPE (decl);
25423 tree decl_arg_types;
25424 tree *args;
25425 unsigned int nargs, ix;
25426 tree arg;
25428 gcc_assert (decl != DECL_TEMPLATE_RESULT (fn));
25430 /* Never do unification on the 'this' parameter. */
25431 decl_arg_types = skip_artificial_parms_for (decl,
25432 TYPE_ARG_TYPES (decl_type));
25434 nargs = list_length (decl_arg_types);
25435 args = XALLOCAVEC (tree, nargs);
25436 for (arg = decl_arg_types, ix = 0;
25437 arg != NULL_TREE;
25438 arg = TREE_CHAIN (arg), ++ix)
25439 args[ix] = TREE_VALUE (arg);
25441 if (fn_type_unification (fn, explicit_args, targs,
25442 args, ix,
25443 (check_rettype || DECL_CONV_FN_P (fn)
25444 ? TREE_TYPE (decl_type) : NULL_TREE),
25445 DEDUCE_EXACT, LOOKUP_NORMAL, NULL,
25446 /*explain_p=*/false,
25447 /*decltype*/false)
25448 == error_mark_node)
25449 return NULL_TREE;
25451 return targs;
25454 /* Return the innermost template arguments that, when applied to a partial
25455 specialization SPEC_TMPL of TMPL, yield the ARGS.
25457 For example, suppose we have:
25459 template <class T, class U> struct S {};
25460 template <class T> struct S<T*, int> {};
25462 Then, suppose we want to get `S<double*, int>'. SPEC_TMPL will be the
25463 partial specialization and the ARGS will be {double*, int}. The resulting
25464 vector will be {double}, indicating that `T' is bound to `double'. */
25466 static tree
25467 get_partial_spec_bindings (tree tmpl, tree spec_tmpl, tree args)
25469 tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (spec_tmpl);
25470 tree spec_args
25471 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (spec_tmpl)));
25472 int i, ntparms = TREE_VEC_LENGTH (tparms);
25473 tree deduced_args;
25474 tree innermost_deduced_args;
25476 innermost_deduced_args = make_tree_vec (ntparms);
25477 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
25479 deduced_args = copy_node (args);
25480 SET_TMPL_ARGS_LEVEL (deduced_args,
25481 TMPL_ARGS_DEPTH (deduced_args),
25482 innermost_deduced_args);
25484 else
25485 deduced_args = innermost_deduced_args;
25487 bool tried_array_deduction = (cxx_dialect < cxx17);
25488 again:
25489 if (unify (tparms, deduced_args,
25490 INNERMOST_TEMPLATE_ARGS (spec_args),
25491 INNERMOST_TEMPLATE_ARGS (args),
25492 UNIFY_ALLOW_NONE, /*explain_p=*/false))
25493 return NULL_TREE;
25495 for (i = 0; i < ntparms; ++i)
25496 if (! TREE_VEC_ELT (innermost_deduced_args, i))
25498 if (!tried_array_deduction)
25500 try_array_deduction (tparms, innermost_deduced_args,
25501 INNERMOST_TEMPLATE_ARGS (spec_args));
25502 tried_array_deduction = true;
25503 if (TREE_VEC_ELT (innermost_deduced_args, i))
25504 goto again;
25506 return NULL_TREE;
25509 if (!push_tinst_level (spec_tmpl, deduced_args))
25511 excessive_deduction_depth = true;
25512 return NULL_TREE;
25515 /* Verify that nondeduced template arguments agree with the type
25516 obtained from argument deduction.
25518 For example:
25520 struct A { typedef int X; };
25521 template <class T, class U> struct C {};
25522 template <class T> struct C<T, typename T::X> {};
25524 Then with the instantiation `C<A, int>', we can deduce that
25525 `T' is `A' but unify () does not check whether `typename T::X'
25526 is `int'. */
25527 spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
25529 if (spec_args != error_mark_node)
25530 spec_args = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
25531 INNERMOST_TEMPLATE_ARGS (spec_args),
25532 tmpl, tf_none, false);
25534 pop_tinst_level ();
25536 if (spec_args == error_mark_node
25537 /* We only need to check the innermost arguments; the other
25538 arguments will always agree. */
25539 || !comp_template_args_porder (INNERMOST_TEMPLATE_ARGS (spec_args),
25540 INNERMOST_TEMPLATE_ARGS (args)))
25541 return NULL_TREE;
25543 /* Now that we have bindings for all of the template arguments,
25544 ensure that the arguments deduced for the template template
25545 parameters have compatible template parameter lists. See the use
25546 of template_template_parm_bindings_ok_p in fn_type_unification
25547 for more information. */
25548 if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
25549 return NULL_TREE;
25551 return deduced_args;
25554 // Compare two function templates T1 and T2 by deducing bindings
25555 // from one against the other. If both deductions succeed, compare
25556 // constraints to see which is more constrained.
25557 static int
25558 more_specialized_inst (tree t1, tree t2)
25560 int fate = 0;
25561 int count = 0;
25563 if (get_bindings (t1, DECL_TEMPLATE_RESULT (t2), NULL_TREE, true))
25565 --fate;
25566 ++count;
25569 if (get_bindings (t2, DECL_TEMPLATE_RESULT (t1), NULL_TREE, true))
25571 ++fate;
25572 ++count;
25575 // If both deductions succeed, then one may be more constrained.
25576 if (count == 2 && fate == 0)
25577 fate = more_constrained (t1, t2);
25579 return fate;
25582 /* TEMPLATES is a TREE_LIST. Each TREE_VALUE is a TEMPLATE_DECL.
25583 Return the TREE_LIST node with the most specialized template, if
25584 any. If there is no most specialized template, the error_mark_node
25585 is returned.
25587 Note that this function does not look at, or modify, the
25588 TREE_PURPOSE or TREE_TYPE of any of the nodes. Since the node
25589 returned is one of the elements of INSTANTIATIONS, callers may
25590 store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
25591 and retrieve it from the value returned. */
25593 tree
25594 most_specialized_instantiation (tree templates)
25596 tree fn, champ;
25598 ++processing_template_decl;
25600 champ = templates;
25601 for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
25603 gcc_assert (TREE_VALUE (champ) != TREE_VALUE (fn));
25604 int fate = more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn));
25605 if (fate == -1)
25606 champ = fn;
25607 else if (!fate)
25609 /* Equally specialized, move to next function. If there
25610 is no next function, nothing's most specialized. */
25611 fn = TREE_CHAIN (fn);
25612 champ = fn;
25613 if (!fn)
25614 break;
25618 if (champ)
25619 /* Now verify that champ is better than everything earlier in the
25620 instantiation list. */
25621 for (fn = templates; fn != champ; fn = TREE_CHAIN (fn)) {
25622 if (more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn)) != 1)
25624 champ = NULL_TREE;
25625 break;
25629 processing_template_decl--;
25631 if (!champ)
25632 return error_mark_node;
25634 return champ;
25637 /* If DECL is a specialization of some template, return the most
25638 general such template. Otherwise, returns NULL_TREE.
25640 For example, given:
25642 template <class T> struct S { template <class U> void f(U); };
25644 if TMPL is `template <class U> void S<int>::f(U)' this will return
25645 the full template. This function will not trace past partial
25646 specializations, however. For example, given in addition:
25648 template <class T> struct S<T*> { template <class U> void f(U); };
25650 if TMPL is `template <class U> void S<int*>::f(U)' this will return
25651 `template <class T> template <class U> S<T*>::f(U)'. */
25653 tree
25654 most_general_template (tree decl)
25656 if (TREE_CODE (decl) != TEMPLATE_DECL)
25658 if (tree tinfo = get_template_info (decl))
25659 decl = TI_TEMPLATE (tinfo);
25660 /* The TI_TEMPLATE can be an IDENTIFIER_NODE for a
25661 template friend, or a FIELD_DECL for a capture pack. */
25662 if (TREE_CODE (decl) != TEMPLATE_DECL)
25663 return NULL_TREE;
25666 /* Look for more and more general templates. */
25667 while (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
25669 /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
25670 (See cp-tree.h for details.) */
25671 if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
25672 break;
25674 if (CLASS_TYPE_P (TREE_TYPE (decl))
25675 && !TYPE_DECL_ALIAS_P (TYPE_NAME (TREE_TYPE (decl)))
25676 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
25677 break;
25679 /* Stop if we run into an explicitly specialized class template. */
25680 if (!DECL_NAMESPACE_SCOPE_P (decl)
25681 && DECL_CONTEXT (decl)
25682 && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
25683 break;
25685 decl = DECL_TI_TEMPLATE (decl);
25688 return decl;
25691 /* Return the most specialized of the template partial specializations
25692 which can produce TARGET, a specialization of some class or variable
25693 template. The value returned is actually a TREE_LIST; the TREE_VALUE is
25694 a TEMPLATE_DECL node corresponding to the partial specialization, while
25695 the TREE_PURPOSE is the set of template arguments that must be
25696 substituted into the template pattern in order to generate TARGET.
25698 If the choice of partial specialization is ambiguous, a diagnostic
25699 is issued, and the error_mark_node is returned. If there are no
25700 partial specializations matching TARGET, then NULL_TREE is
25701 returned, indicating that the primary template should be used. */
25703 tree
25704 most_specialized_partial_spec (tree target, tsubst_flags_t complain)
25706 tree list = NULL_TREE;
25707 tree t;
25708 tree champ;
25709 int fate;
25710 bool ambiguous_p;
25711 tree outer_args = NULL_TREE;
25712 tree tmpl, args;
25714 tree decl;
25715 if (TYPE_P (target))
25717 tree tinfo = CLASSTYPE_TEMPLATE_INFO (target);
25718 tmpl = TI_TEMPLATE (tinfo);
25719 args = TI_ARGS (tinfo);
25720 decl = TYPE_NAME (target);
25722 else if (TREE_CODE (target) == TEMPLATE_ID_EXPR)
25724 tmpl = TREE_OPERAND (target, 0);
25725 args = TREE_OPERAND (target, 1);
25726 decl = DECL_TEMPLATE_RESULT (tmpl);
25728 else if (VAR_P (target))
25730 tree tinfo = DECL_TEMPLATE_INFO (target);
25731 tmpl = TI_TEMPLATE (tinfo);
25732 args = TI_ARGS (tinfo);
25733 decl = target;
25735 else
25736 gcc_unreachable ();
25738 push_access_scope_guard pas (decl);
25739 deferring_access_check_sentinel acs (dk_no_deferred);
25741 tree main_tmpl = most_general_template (tmpl);
25743 /* For determining which partial specialization to use, only the
25744 innermost args are interesting. */
25745 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
25747 outer_args = strip_innermost_template_args (args, 1);
25748 args = INNERMOST_TEMPLATE_ARGS (args);
25751 /* The caller hasn't called push_to_top_level yet, but we need
25752 get_partial_spec_bindings to be done in non-template context so that we'll
25753 fully resolve everything. */
25754 processing_template_decl_sentinel ptds;
25756 for (t = DECL_TEMPLATE_SPECIALIZATIONS (main_tmpl); t; t = TREE_CHAIN (t))
25758 const tree ospec_tmpl = TREE_VALUE (t);
25760 tree spec_tmpl;
25761 if (outer_args)
25763 /* Substitute in the template args from the enclosing class. */
25764 ++processing_template_decl;
25765 spec_tmpl = tsubst (ospec_tmpl, outer_args, tf_none, NULL_TREE);
25766 --processing_template_decl;
25767 if (spec_tmpl == error_mark_node)
25768 return error_mark_node;
25770 else
25771 spec_tmpl = ospec_tmpl;
25773 tree spec_args = get_partial_spec_bindings (tmpl, spec_tmpl, args);
25774 if (spec_args)
25776 if (outer_args)
25777 spec_args = add_to_template_args (outer_args, spec_args);
25779 /* Keep the candidate only if the constraints are satisfied,
25780 or if we're not compiling with concepts. */
25781 if (!flag_concepts
25782 || constraints_satisfied_p (ospec_tmpl, spec_args))
25784 list = tree_cons (spec_args, ospec_tmpl, list);
25785 TREE_TYPE (list) = TREE_TYPE (t);
25790 if (! list)
25791 return NULL_TREE;
25793 ambiguous_p = false;
25794 t = list;
25795 champ = t;
25796 t = TREE_CHAIN (t);
25797 for (; t; t = TREE_CHAIN (t))
25799 fate = more_specialized_partial_spec (tmpl, champ, t);
25800 if (fate == 1)
25802 else
25804 if (fate == 0)
25806 t = TREE_CHAIN (t);
25807 if (! t)
25809 ambiguous_p = true;
25810 break;
25813 champ = t;
25817 if (!ambiguous_p)
25818 for (t = list; t && t != champ; t = TREE_CHAIN (t))
25820 fate = more_specialized_partial_spec (tmpl, champ, t);
25821 if (fate != 1)
25823 ambiguous_p = true;
25824 break;
25828 if (ambiguous_p)
25830 const char *str;
25831 char *spaces = NULL;
25832 if (!(complain & tf_error))
25833 return error_mark_node;
25834 if (TYPE_P (target))
25835 error ("ambiguous template instantiation for %q#T", target);
25836 else
25837 error ("ambiguous template instantiation for %q#D", target);
25838 str = ngettext ("candidate is:", "candidates are:", list_length (list));
25839 for (t = list; t; t = TREE_CHAIN (t))
25841 tree subst = build_tree_list (TREE_VALUE (t), TREE_PURPOSE (t));
25842 inform (DECL_SOURCE_LOCATION (TREE_VALUE (t)),
25843 "%s %#qS", spaces ? spaces : str, subst);
25844 spaces = spaces ? spaces : get_spaces (str);
25846 free (spaces);
25847 return error_mark_node;
25850 return champ;
25853 /* Explicitly instantiate DECL. */
25855 void
25856 do_decl_instantiation (tree decl, tree storage)
25858 tree result = NULL_TREE;
25859 int extern_p = 0;
25861 if (!decl || decl == error_mark_node)
25862 /* An error occurred, for which grokdeclarator has already issued
25863 an appropriate message. */
25864 return;
25865 else if (! DECL_LANG_SPECIFIC (decl))
25867 error ("explicit instantiation of non-template %q#D", decl);
25868 return;
25870 else if (DECL_DECLARED_CONCEPT_P (decl))
25872 if (VAR_P (decl))
25873 error ("explicit instantiation of variable concept %q#D", decl);
25874 else
25875 error ("explicit instantiation of function concept %q#D", decl);
25876 return;
25879 bool var_templ = (DECL_TEMPLATE_INFO (decl)
25880 && variable_template_p (DECL_TI_TEMPLATE (decl)));
25882 if (VAR_P (decl) && !var_templ)
25884 /* There is an asymmetry here in the way VAR_DECLs and
25885 FUNCTION_DECLs are handled by grokdeclarator. In the case of
25886 the latter, the DECL we get back will be marked as a
25887 template instantiation, and the appropriate
25888 DECL_TEMPLATE_INFO will be set up. This does not happen for
25889 VAR_DECLs so we do the lookup here. Probably, grokdeclarator
25890 should handle VAR_DECLs as it currently handles
25891 FUNCTION_DECLs. */
25892 if (!DECL_CLASS_SCOPE_P (decl))
25894 error ("%qD is not a static data member of a class template", decl);
25895 return;
25897 result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
25898 if (!result || !VAR_P (result))
25900 error ("no matching template for %qD found", decl);
25901 return;
25903 if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
25905 error ("type %qT for explicit instantiation %qD does not match "
25906 "declared type %qT", TREE_TYPE (result), decl,
25907 TREE_TYPE (decl));
25908 return;
25911 else if (TREE_CODE (decl) != FUNCTION_DECL && !var_templ)
25913 error ("explicit instantiation of %q#D", decl);
25914 return;
25916 else
25917 result = decl;
25919 /* Check for various error cases. Note that if the explicit
25920 instantiation is valid the RESULT will currently be marked as an
25921 *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
25922 until we get here. */
25924 if (DECL_TEMPLATE_SPECIALIZATION (result))
25926 /* DR 259 [temp.spec].
25928 Both an explicit instantiation and a declaration of an explicit
25929 specialization shall not appear in a program unless the explicit
25930 instantiation follows a declaration of the explicit specialization.
25932 For a given set of template parameters, if an explicit
25933 instantiation of a template appears after a declaration of an
25934 explicit specialization for that template, the explicit
25935 instantiation has no effect. */
25936 return;
25938 else if (DECL_EXPLICIT_INSTANTIATION (result))
25940 /* [temp.spec]
25942 No program shall explicitly instantiate any template more
25943 than once.
25945 We check DECL_NOT_REALLY_EXTERN so as not to complain when
25946 the first instantiation was `extern' and the second is not,
25947 and EXTERN_P for the opposite case. */
25948 if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
25949 permerror (input_location, "duplicate explicit instantiation of %q#D", result);
25950 /* If an "extern" explicit instantiation follows an ordinary
25951 explicit instantiation, the template is instantiated. */
25952 if (extern_p)
25953 return;
25955 else if (!DECL_IMPLICIT_INSTANTIATION (result))
25957 error ("no matching template for %qD found", result);
25958 return;
25960 else if (!DECL_TEMPLATE_INFO (result))
25962 permerror (input_location, "explicit instantiation of non-template %q#D", result);
25963 return;
25966 if (storage == NULL_TREE)
25968 else if (storage == ridpointers[(int) RID_EXTERN])
25970 if (cxx_dialect == cxx98)
25971 pedwarn (input_location, OPT_Wpedantic,
25972 "ISO C++ 1998 forbids the use of %<extern%> on explicit "
25973 "instantiations");
25974 extern_p = 1;
25976 else
25977 error ("storage class %qD applied to template instantiation", storage);
25979 check_explicit_instantiation_namespace (result);
25980 mark_decl_instantiated (result, extern_p);
25981 if (! extern_p)
25982 instantiate_decl (result, /*defer_ok=*/true,
25983 /*expl_inst_class_mem_p=*/false);
25986 static void
25987 mark_class_instantiated (tree t, int extern_p)
25989 SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
25990 SET_CLASSTYPE_INTERFACE_KNOWN (t);
25991 CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
25992 TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
25993 if (! extern_p)
25995 CLASSTYPE_DEBUG_REQUESTED (t) = 1;
25996 rest_of_type_compilation (t, 1);
26000 /* Perform an explicit instantiation of template class T. STORAGE, if
26001 non-null, is the RID for extern, inline or static. COMPLAIN is
26002 nonzero if this is called from the parser, zero if called recursively,
26003 since the standard is unclear (as detailed below). */
26005 void
26006 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
26008 if (!(CLASS_TYPE_P (t) && CLASSTYPE_TEMPLATE_INFO (t)))
26010 if (tree ti = TYPE_TEMPLATE_INFO (t))
26011 error ("explicit instantiation of non-class template %qD",
26012 TI_TEMPLATE (ti));
26013 else
26014 error ("explicit instantiation of non-template type %qT", t);
26015 return;
26018 complete_type (t);
26020 if (!COMPLETE_TYPE_P (t))
26022 if (complain & tf_error)
26023 error ("explicit instantiation of %q#T before definition of template",
26025 return;
26028 /* At most one of these will be true. */
26029 bool extern_p = false;
26030 bool nomem_p = false;
26031 bool static_p = false;
26033 if (storage != NULL_TREE)
26035 if (storage == ridpointers[(int) RID_EXTERN])
26037 if (cxx_dialect == cxx98)
26038 pedwarn (input_location, OPT_Wpedantic,
26039 "ISO C++ 1998 forbids the use of %<extern%> on "
26040 "explicit instantiations");
26042 else
26043 pedwarn (input_location, OPT_Wpedantic,
26044 "ISO C++ forbids the use of %qE"
26045 " on explicit instantiations", storage);
26047 if (storage == ridpointers[(int) RID_INLINE])
26048 nomem_p = true;
26049 else if (storage == ridpointers[(int) RID_EXTERN])
26050 extern_p = true;
26051 else if (storage == ridpointers[(int) RID_STATIC])
26052 static_p = true;
26053 else
26054 error ("storage class %qD applied to template instantiation",
26055 storage);
26058 if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
26059 /* DR 259 [temp.spec].
26061 Both an explicit instantiation and a declaration of an explicit
26062 specialization shall not appear in a program unless the
26063 explicit instantiation follows a declaration of the explicit
26064 specialization.
26066 For a given set of template parameters, if an explicit
26067 instantiation of a template appears after a declaration of an
26068 explicit specialization for that template, the explicit
26069 instantiation has no effect. */
26070 return;
26072 if (CLASSTYPE_EXPLICIT_INSTANTIATION (t) && !CLASSTYPE_INTERFACE_ONLY (t))
26074 /* We've already instantiated the template. */
26076 /* [temp.spec]
26078 No program shall explicitly instantiate any template more
26079 than once.
26081 If EXTERN_P then this is ok. */
26082 if (!extern_p && (complain & tf_error))
26083 permerror (input_location,
26084 "duplicate explicit instantiation of %q#T", t);
26086 return;
26089 check_explicit_instantiation_namespace (TYPE_NAME (t));
26090 mark_class_instantiated (t, extern_p);
26092 if (nomem_p)
26093 return;
26095 /* In contrast to implicit instantiation, where only the
26096 declarations, and not the definitions, of members are
26097 instantiated, we have here:
26099 [temp.explicit]
26101 An explicit instantiation that names a class template
26102 specialization is also an explicit instantiation of the same
26103 kind (declaration or definition) of each of its members (not
26104 including members inherited from base classes and members
26105 that are templates) that has not been previously explicitly
26106 specialized in the translation unit containing the explicit
26107 instantiation, provided that the associated constraints, if
26108 any, of that member are satisfied by the template arguments
26109 of the explicit instantiation. */
26110 for (tree fld = TYPE_FIELDS (t); fld; fld = DECL_CHAIN (fld))
26111 if ((VAR_P (fld)
26112 || (TREE_CODE (fld) == FUNCTION_DECL
26113 && !static_p
26114 && user_provided_p (fld)))
26115 && DECL_TEMPLATE_INSTANTIATION (fld)
26116 && constraints_satisfied_p (fld))
26118 mark_decl_instantiated (fld, extern_p);
26119 if (! extern_p)
26120 instantiate_decl (fld, /*defer_ok=*/true,
26121 /*expl_inst_class_mem_p=*/true);
26123 else if (DECL_IMPLICIT_TYPEDEF_P (fld))
26125 tree type = TREE_TYPE (fld);
26127 if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
26128 && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
26129 do_type_instantiation (type, storage, 0);
26133 /* Given a function DECL, which is a specialization of TMPL, modify
26134 DECL to be a re-instantiation of TMPL with the same template
26135 arguments. TMPL should be the template into which tsubst'ing
26136 should occur for DECL, not the most general template.
26138 One reason for doing this is a scenario like this:
26140 template <class T>
26141 void f(const T&, int i);
26143 void g() { f(3, 7); }
26145 template <class T>
26146 void f(const T& t, const int i) { }
26148 Note that when the template is first instantiated, with
26149 instantiate_template, the resulting DECL will have no name for the
26150 first parameter, and the wrong type for the second. So, when we go
26151 to instantiate the DECL, we regenerate it. */
26153 static void
26154 regenerate_decl_from_template (tree decl, tree tmpl, tree args)
26156 /* The arguments used to instantiate DECL, from the most general
26157 template. */
26158 tree code_pattern = DECL_TEMPLATE_RESULT (tmpl);
26160 /* Make sure that we can see identifiers, and compute access correctly. */
26161 push_access_scope (decl);
26163 if (TREE_CODE (decl) == FUNCTION_DECL)
26165 tree specs;
26166 int args_depth;
26167 int parms_depth;
26169 /* Use the source location of the definition. */
26170 DECL_SOURCE_LOCATION (decl) = DECL_SOURCE_LOCATION (tmpl);
26172 args_depth = TMPL_ARGS_DEPTH (args);
26173 parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
26174 if (args_depth > parms_depth)
26175 args = get_innermost_template_args (args, parms_depth);
26177 /* Instantiate a dynamic exception-specification. noexcept will be
26178 handled below. */
26179 if (tree raises = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (code_pattern)))
26180 if (TREE_VALUE (raises))
26182 specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
26183 args, tf_error, NULL_TREE,
26184 /*defer_ok*/false);
26185 if (specs && specs != error_mark_node)
26186 TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
26187 specs);
26190 /* Merge parameter declarations. */
26191 if (tree pattern_parm
26192 = skip_artificial_parms_for (code_pattern,
26193 DECL_ARGUMENTS (code_pattern)))
26195 tree *p = &DECL_ARGUMENTS (decl);
26196 for (int skip = num_artificial_parms_for (decl); skip; --skip)
26197 p = &DECL_CHAIN (*p);
26198 *p = tsubst_decl (pattern_parm, args, tf_error);
26199 for (tree t = *p; t; t = DECL_CHAIN (t))
26200 DECL_CONTEXT (t) = decl;
26203 if (DECL_CONTRACTS (decl))
26205 /* If we're regenerating a specialization, the contracts will have
26206 been copied from the most general template. Replace those with
26207 the ones from the actual specialization. */
26208 tree tmpl = DECL_TI_TEMPLATE (decl);
26209 if (DECL_TEMPLATE_SPECIALIZATION (tmpl))
26211 remove_contract_attributes (decl);
26212 copy_contract_attributes (decl, code_pattern);
26215 tsubst_contract_attributes (decl, args, tf_warning_or_error, code_pattern);
26218 /* Merge additional specifiers from the CODE_PATTERN. */
26219 if (DECL_DECLARED_INLINE_P (code_pattern)
26220 && !DECL_DECLARED_INLINE_P (decl))
26221 DECL_DECLARED_INLINE_P (decl) = 1;
26223 maybe_instantiate_noexcept (decl, tf_error);
26225 else if (VAR_P (decl))
26227 start_lambda_scope (decl);
26228 DECL_INITIAL (decl) =
26229 tsubst_init (DECL_INITIAL (code_pattern), decl, args,
26230 tf_error, DECL_TI_TEMPLATE (decl));
26231 finish_lambda_scope ();
26232 if (VAR_HAD_UNKNOWN_BOUND (decl))
26233 TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
26234 tf_error, DECL_TI_TEMPLATE (decl));
26236 else
26237 gcc_unreachable ();
26239 pop_access_scope (decl);
26242 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
26243 substituted to get DECL. */
26245 tree
26246 template_for_substitution (tree decl)
26248 tree tmpl = DECL_TI_TEMPLATE (decl);
26250 /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
26251 for the instantiation. This is not always the most general
26252 template. Consider, for example:
26254 template <class T>
26255 struct S { template <class U> void f();
26256 template <> void f<int>(); };
26258 and an instantiation of S<double>::f<int>. We want TD to be the
26259 specialization S<T>::f<int>, not the more general S<T>::f<U>. */
26260 while (/* An instantiation cannot have a definition, so we need a
26261 more general template. */
26262 DECL_TEMPLATE_INSTANTIATION (tmpl)
26263 /* We must also deal with friend templates. Given:
26265 template <class T> struct S {
26266 template <class U> friend void f() {};
26269 S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
26270 so far as the language is concerned, but that's still
26271 where we get the pattern for the instantiation from. On
26272 other hand, if the definition comes outside the class, say:
26274 template <class T> struct S {
26275 template <class U> friend void f();
26277 template <class U> friend void f() {}
26279 we don't need to look any further. That's what the check for
26280 DECL_INITIAL is for. */
26281 || (TREE_CODE (decl) == FUNCTION_DECL
26282 && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
26283 && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
26285 /* The present template, TD, should not be a definition. If it
26286 were a definition, we should be using it! Note that we
26287 cannot restructure the loop to just keep going until we find
26288 a template with a definition, since that might go too far if
26289 a specialization was declared, but not defined. */
26291 /* Fetch the more general template. */
26292 tmpl = DECL_TI_TEMPLATE (tmpl);
26295 return tmpl;
26298 /* Returns true if we need to instantiate this template instance even if we
26299 know we aren't going to emit it. */
26301 bool
26302 always_instantiate_p (tree decl)
26304 /* We always instantiate inline functions so that we can inline them. An
26305 explicit instantiation declaration prohibits implicit instantiation of
26306 non-inline functions. With high levels of optimization, we would
26307 normally inline non-inline functions -- but we're not allowed to do
26308 that for "extern template" functions. Therefore, we check
26309 DECL_DECLARED_INLINE_P, rather than possibly_inlined_p. */
26310 return ((TREE_CODE (decl) == FUNCTION_DECL
26311 && (DECL_DECLARED_INLINE_P (decl)
26312 || type_uses_auto (TREE_TYPE (TREE_TYPE (decl)))))
26313 /* And we need to instantiate static data members so that
26314 their initializers are available in integral constant
26315 expressions. */
26316 || (VAR_P (decl)
26317 && decl_maybe_constant_var_p (decl)));
26320 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
26321 instantiate it now, modifying TREE_TYPE (fn). Returns false on
26322 error, true otherwise. */
26324 bool
26325 maybe_instantiate_noexcept (tree fn, tsubst_flags_t complain)
26327 if (fn == error_mark_node)
26328 return false;
26330 /* Don't instantiate a noexcept-specification from template context. */
26331 if (processing_template_decl
26332 && (!flag_noexcept_type || type_dependent_expression_p (fn)))
26333 return true;
26335 tree fntype = TREE_TYPE (fn);
26336 tree spec = TYPE_RAISES_EXCEPTIONS (fntype);
26338 if ((!spec || UNEVALUATED_NOEXCEPT_SPEC_P (spec))
26339 && DECL_MAYBE_DELETED (fn))
26341 if (fn == current_function_decl)
26342 /* We're in start_preparsed_function, keep going. */
26343 return true;
26345 ++function_depth;
26346 maybe_synthesize_method (fn);
26347 --function_depth;
26348 return !DECL_DELETED_FN (fn);
26351 if (!spec || !TREE_PURPOSE (spec))
26352 return true;
26354 tree noex = TREE_PURPOSE (spec);
26355 if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
26356 && TREE_CODE (noex) != DEFERRED_PARSE)
26357 return true;
26359 tree orig_fn = NULL_TREE;
26360 /* For a member friend template we can get a TEMPLATE_DECL. Let's use
26361 its FUNCTION_DECL for the rest of this function -- push_access_scope
26362 doesn't accept TEMPLATE_DECLs. */
26363 if (DECL_FUNCTION_TEMPLATE_P (fn))
26365 orig_fn = fn;
26366 fn = DECL_TEMPLATE_RESULT (fn);
26369 if (DECL_CLONED_FUNCTION_P (fn))
26371 tree prime = DECL_CLONED_FUNCTION (fn);
26372 if (!maybe_instantiate_noexcept (prime, complain))
26373 return false;
26374 spec = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (prime));
26376 else if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
26378 static hash_set<tree>* fns = new hash_set<tree>;
26379 bool added = false;
26380 if (DEFERRED_NOEXCEPT_PATTERN (noex) == NULL_TREE)
26382 spec = get_defaulted_eh_spec (fn, complain);
26383 if (spec == error_mark_node)
26384 /* This might have failed because of an unparsed DMI, so
26385 let's try again later. */
26386 return false;
26388 else if (!(added = !fns->add (fn)))
26390 /* If hash_set::add returns true, the element was already there. */
26391 location_t loc = cp_expr_loc_or_loc (DEFERRED_NOEXCEPT_PATTERN (noex),
26392 DECL_SOURCE_LOCATION (fn));
26393 error_at (loc,
26394 "exception specification of %qD depends on itself",
26395 fn);
26396 spec = noexcept_false_spec;
26398 else if (push_tinst_level (fn))
26400 push_to_top_level ();
26401 push_access_scope (fn);
26402 push_deferring_access_checks (dk_no_deferred);
26403 input_location = DECL_SOURCE_LOCATION (fn);
26405 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
26406 && !DECL_LOCAL_DECL_P (fn))
26408 /* If needed, set current_class_ptr for the benefit of
26409 tsubst_copy/PARM_DECL. */
26410 tree this_parm = DECL_ARGUMENTS (fn);
26411 current_class_ptr = NULL_TREE;
26412 current_class_ref = cp_build_fold_indirect_ref (this_parm);
26413 current_class_ptr = this_parm;
26416 /* If this function is represented by a TEMPLATE_DECL, then
26417 the deferred noexcept-specification might still contain
26418 dependent types, even after substitution. And we need the
26419 dependency check functions to work in build_noexcept_spec. */
26420 if (orig_fn)
26421 ++processing_template_decl;
26423 /* Do deferred instantiation of the noexcept-specifier. */
26424 noex = tsubst_copy_and_build (DEFERRED_NOEXCEPT_PATTERN (noex),
26425 DEFERRED_NOEXCEPT_ARGS (noex),
26426 tf_warning_or_error, fn);
26428 /* Build up the noexcept-specification. */
26429 spec = build_noexcept_spec (noex, tf_warning_or_error);
26431 if (orig_fn)
26432 --processing_template_decl;
26434 pop_deferring_access_checks ();
26435 pop_access_scope (fn);
26436 pop_tinst_level ();
26437 pop_from_top_level ();
26439 else
26440 spec = noexcept_false_spec;
26442 if (added)
26443 fns->remove (fn);
26446 if (spec == error_mark_node)
26448 /* This failed with a hard error, so let's go with false. */
26449 gcc_assert (seen_error ());
26450 spec = noexcept_false_spec;
26453 TREE_TYPE (fn) = build_exception_variant (fntype, spec);
26454 if (orig_fn)
26455 TREE_TYPE (orig_fn) = TREE_TYPE (fn);
26457 return true;
26460 /* We're starting to process the function INST, an instantiation of PATTERN;
26461 add their parameters to local_specializations. */
26463 void
26464 register_parameter_specializations (tree pattern, tree inst)
26466 tree tmpl_parm = DECL_ARGUMENTS (pattern);
26467 tree spec_parm = DECL_ARGUMENTS (inst);
26468 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (inst))
26470 register_local_specialization (spec_parm, tmpl_parm);
26471 spec_parm = skip_artificial_parms_for (inst, spec_parm);
26472 tmpl_parm = skip_artificial_parms_for (pattern, tmpl_parm);
26474 for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
26476 if (!DECL_PACK_P (tmpl_parm))
26478 register_local_specialization (spec_parm, tmpl_parm);
26479 spec_parm = DECL_CHAIN (spec_parm);
26481 else
26483 /* Register the (value) argument pack as a specialization of
26484 TMPL_PARM, then move on. */
26485 tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
26486 register_local_specialization (argpack, tmpl_parm);
26489 gcc_assert (!spec_parm);
26492 /* Instantiate the body of D using PATTERN with ARGS. We have
26493 already determined PATTERN is the correct template to use.
26494 NESTED_P is true if this is a nested function, in which case
26495 PATTERN will be a FUNCTION_DECL not a TEMPLATE_DECL. */
26497 static void
26498 instantiate_body (tree pattern, tree args, tree d, bool nested_p)
26500 tree td = NULL_TREE;
26501 tree code_pattern = pattern;
26503 if (!nested_p)
26505 td = pattern;
26506 code_pattern = DECL_TEMPLATE_RESULT (td);
26508 else
26509 /* Only OMP reductions are nested. */
26510 gcc_checking_assert (DECL_OMP_DECLARE_REDUCTION_P (code_pattern));
26512 vec<tree> omp_privatization_save;
26513 if (current_function_decl)
26514 save_omp_privatization_clauses (omp_privatization_save);
26516 bool push_to_top
26517 = !(current_function_decl
26518 && !LAMBDA_FUNCTION_P (d)
26519 && decl_function_context (d) == current_function_decl);
26521 if (push_to_top)
26522 push_to_top_level ();
26523 else
26525 gcc_assert (!processing_template_decl);
26526 push_function_context ();
26527 cp_unevaluated_operand = 0;
26528 c_inhibit_evaluation_warnings = 0;
26531 if (VAR_P (d))
26533 /* The variable might be a lambda's extra scope, and that
26534 lambda's visibility depends on D's. */
26535 maybe_commonize_var (d);
26536 determine_visibility (d);
26539 /* Mark D as instantiated so that recursive calls to
26540 instantiate_decl do not try to instantiate it again. */
26541 DECL_TEMPLATE_INSTANTIATED (d) = 1;
26543 if (td)
26544 /* Regenerate the declaration in case the template has been modified
26545 by a subsequent redeclaration. */
26546 regenerate_decl_from_template (d, td, args);
26548 /* We already set the file and line above. Reset them now in case
26549 they changed as a result of calling regenerate_decl_from_template. */
26550 input_location = DECL_SOURCE_LOCATION (d);
26552 if (VAR_P (d))
26554 /* Clear out DECL_RTL; whatever was there before may not be right
26555 since we've reset the type of the declaration. */
26556 SET_DECL_RTL (d, NULL);
26557 DECL_IN_AGGR_P (d) = 0;
26559 /* The initializer is placed in DECL_INITIAL by
26560 regenerate_decl_from_template so we don't need to
26561 push/pop_access_scope again here. Pull it out so that
26562 cp_finish_decl can process it. */
26563 bool const_init = false;
26564 tree init = DECL_INITIAL (d);
26565 DECL_INITIAL (d) = NULL_TREE;
26566 DECL_INITIALIZED_P (d) = 0;
26568 /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
26569 initializer. That function will defer actual emission until
26570 we have a chance to determine linkage. */
26571 DECL_EXTERNAL (d) = 0;
26573 /* Enter the scope of D so that access-checking works correctly. */
26574 bool enter_context = DECL_CLASS_SCOPE_P (d);
26575 if (enter_context)
26576 push_nested_class (DECL_CONTEXT (d));
26578 const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
26579 cp_finish_decl (d, init, const_init, NULL_TREE, 0);
26581 if (enter_context)
26582 pop_nested_class ();
26584 else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
26585 synthesize_method (d);
26586 else if (TREE_CODE (d) == FUNCTION_DECL)
26588 /* Set up the list of local specializations. */
26589 local_specialization_stack lss (push_to_top ? lss_blank : lss_copy);
26590 tree block = NULL_TREE;
26592 /* Set up context. */
26593 if (nested_p)
26594 block = push_stmt_list ();
26595 else
26597 start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
26599 perform_instantiation_time_access_checks (code_pattern, args);
26602 /* Create substitution entries for the parameters. */
26603 register_parameter_specializations (code_pattern, d);
26605 /* Substitute into the body of the function. */
26606 if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
26607 tsubst_omp_udr (DECL_SAVED_TREE (code_pattern), args,
26608 tf_warning_or_error, d);
26609 else
26611 tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
26612 tf_warning_or_error, DECL_TI_TEMPLATE (d));
26614 /* Set the current input_location to the end of the function
26615 so that finish_function knows where we are. */
26616 input_location
26617 = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
26619 /* Remember if we saw an infinite loop in the template. */
26620 current_function_infinite_loop
26621 = DECL_STRUCT_FUNCTION (code_pattern)->language->infinite_loop;
26624 /* Finish the function. */
26625 if (nested_p)
26626 DECL_SAVED_TREE (d) = pop_stmt_list (block);
26627 else
26629 d = finish_function (/*inline_p=*/false);
26630 expand_or_defer_fn (d);
26633 if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
26634 cp_check_omp_declare_reduction (d);
26637 /* We're not deferring instantiation any more. */
26638 if (!nested_p)
26639 TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
26641 if (push_to_top)
26642 pop_from_top_level ();
26643 else
26644 pop_function_context ();
26646 if (current_function_decl)
26647 restore_omp_privatization_clauses (omp_privatization_save);
26650 /* Produce the definition of D, a _DECL generated from a template. If
26651 DEFER_OK is true, then we don't have to actually do the
26652 instantiation now; we just have to do it sometime. Normally it is
26653 an error if this is an explicit instantiation but D is undefined.
26654 EXPL_INST_CLASS_MEM_P is true iff D is a member of an explicitly
26655 instantiated class template. */
26657 tree
26658 instantiate_decl (tree d, bool defer_ok, bool expl_inst_class_mem_p)
26660 tree tmpl = DECL_TI_TEMPLATE (d);
26661 tree gen_args;
26662 tree args;
26663 tree td;
26664 tree code_pattern;
26665 tree spec;
26666 tree gen_tmpl;
26667 bool pattern_defined;
26668 location_t saved_loc = input_location;
26669 int saved_unevaluated_operand = cp_unevaluated_operand;
26670 int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
26671 bool external_p;
26672 bool deleted_p;
26674 /* This function should only be used to instantiate templates for
26675 functions and static member variables. */
26676 gcc_assert (VAR_OR_FUNCTION_DECL_P (d));
26678 /* A concept is never instantiated. */
26679 gcc_assert (!DECL_DECLARED_CONCEPT_P (d));
26681 gcc_checking_assert (!DECL_FUNCTION_SCOPE_P (d));
26683 if (modules_p ())
26684 /* We may have a pending instantiation of D itself. */
26685 lazy_load_pendings (d);
26687 /* Variables are never deferred; if instantiation is required, they
26688 are instantiated right away. That allows for better code in the
26689 case that an expression refers to the value of the variable --
26690 if the variable has a constant value the referring expression can
26691 take advantage of that fact. */
26692 if (VAR_P (d))
26693 defer_ok = false;
26695 /* Don't instantiate cloned functions. Instead, instantiate the
26696 functions they cloned. */
26697 if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
26698 d = DECL_CLONED_FUNCTION (d);
26700 if (DECL_TEMPLATE_INSTANTIATED (d)
26701 || TREE_TYPE (d) == error_mark_node
26702 || (TREE_CODE (d) == FUNCTION_DECL
26703 && DECL_DEFAULTED_FN (d) && DECL_INITIAL (d))
26704 || DECL_TEMPLATE_SPECIALIZATION (d))
26705 /* D has already been instantiated or explicitly specialized, so
26706 there's nothing for us to do here.
26708 It might seem reasonable to check whether or not D is an explicit
26709 instantiation, and, if so, stop here. But when an explicit
26710 instantiation is deferred until the end of the compilation,
26711 DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
26712 the instantiation. */
26713 return d;
26715 /* Check to see whether we know that this template will be
26716 instantiated in some other file, as with "extern template"
26717 extension. */
26718 external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
26720 /* In general, we do not instantiate such templates. */
26721 if (external_p && !always_instantiate_p (d))
26722 return d;
26724 gen_tmpl = most_general_template (tmpl);
26725 gen_args = DECL_TI_ARGS (d);
26727 /* We should already have the extra args. */
26728 gcc_checking_assert (tmpl == gen_tmpl
26729 || (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
26730 == TMPL_ARGS_DEPTH (gen_args)));
26731 /* And what's in the hash table should match D. */
26732 gcc_checking_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0))
26733 == d
26734 || spec == NULL_TREE);
26736 /* This needs to happen before any tsubsting. */
26737 if (! push_tinst_level (d))
26738 return d;
26740 auto_timevar tv (TV_TEMPLATE_INST);
26742 /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
26743 for the instantiation. */
26744 td = template_for_substitution (d);
26745 args = gen_args;
26747 if (variable_template_specialization_p (d))
26749 /* Look up an explicit specialization, if any. */
26750 tree elt = most_specialized_partial_spec (d, tf_warning_or_error);
26751 if (elt && elt != error_mark_node)
26753 td = TREE_VALUE (elt);
26754 args = TREE_PURPOSE (elt);
26758 code_pattern = DECL_TEMPLATE_RESULT (td);
26760 /* We should never be trying to instantiate a member of a class
26761 template or partial specialization. */
26762 gcc_assert (d != code_pattern);
26764 if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
26765 || DECL_TEMPLATE_SPECIALIZATION (td))
26766 /* In the case of a friend template whose definition is provided
26767 outside the class, we may have too many arguments. Drop the
26768 ones we don't need. The same is true for specializations. */
26769 args = get_innermost_template_args
26770 (args, TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (td)));
26772 if (TREE_CODE (d) == FUNCTION_DECL)
26774 deleted_p = DECL_DELETED_FN (code_pattern);
26775 pattern_defined = ((DECL_SAVED_TREE (code_pattern) != NULL_TREE
26776 && DECL_INITIAL (code_pattern) != error_mark_node)
26777 || DECL_DEFAULTED_FN (code_pattern)
26778 || deleted_p);
26780 else
26782 deleted_p = false;
26783 if (DECL_CLASS_SCOPE_P (code_pattern))
26784 pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
26785 else
26786 pattern_defined = ! DECL_EXTERNAL (code_pattern);
26789 /* We may be in the middle of deferred access check. Disable it now. */
26790 push_deferring_access_checks (dk_no_deferred);
26792 /* Unless an explicit instantiation directive has already determined
26793 the linkage of D, remember that a definition is available for
26794 this entity. */
26795 if (pattern_defined
26796 && !DECL_INTERFACE_KNOWN (d)
26797 && !DECL_NOT_REALLY_EXTERN (d))
26798 mark_definable (d);
26800 DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
26801 DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
26802 input_location = DECL_SOURCE_LOCATION (d);
26804 /* If D is a member of an explicitly instantiated class template,
26805 and no definition is available, treat it like an implicit
26806 instantiation. */
26807 if (!pattern_defined && expl_inst_class_mem_p
26808 && DECL_EXPLICIT_INSTANTIATION (d))
26810 /* Leave linkage flags alone on instantiations with anonymous
26811 visibility. */
26812 if (TREE_PUBLIC (d))
26814 DECL_NOT_REALLY_EXTERN (d) = 0;
26815 DECL_INTERFACE_KNOWN (d) = 0;
26817 SET_DECL_IMPLICIT_INSTANTIATION (d);
26820 /* Defer all other templates, unless we have been explicitly
26821 forbidden from doing so. */
26822 if (/* If there is no definition, we cannot instantiate the
26823 template. */
26824 ! pattern_defined
26825 /* If it's OK to postpone instantiation, do so. */
26826 || defer_ok
26827 /* If this is a static data member that will be defined
26828 elsewhere, we don't want to instantiate the entire data
26829 member, but we do want to instantiate the initializer so that
26830 we can substitute that elsewhere. */
26831 || (external_p && VAR_P (d))
26832 /* Handle here a deleted function too, avoid generating
26833 its body (c++/61080). */
26834 || deleted_p)
26836 /* The definition of the static data member is now required so
26837 we must substitute the initializer. */
26838 if (VAR_P (d)
26839 && !DECL_INITIAL (d)
26840 && DECL_INITIAL (code_pattern))
26842 tree ns;
26843 tree init;
26844 bool const_init = false;
26845 bool enter_context = DECL_CLASS_SCOPE_P (d);
26847 ns = decl_namespace_context (d);
26848 push_nested_namespace (ns);
26849 if (enter_context)
26850 push_nested_class (DECL_CONTEXT (d));
26851 init = tsubst_expr (DECL_INITIAL (code_pattern),
26852 args,
26853 tf_warning_or_error, NULL_TREE);
26854 /* If instantiating the initializer involved instantiating this
26855 again, don't call cp_finish_decl twice. */
26856 if (!DECL_INITIAL (d))
26858 /* Make sure the initializer is still constant, in case of
26859 circular dependency (template/instantiate6.C). */
26860 const_init
26861 = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
26862 cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
26863 /*asmspec_tree=*/NULL_TREE, 0);
26865 if (enter_context)
26866 pop_nested_class ();
26867 pop_nested_namespace (ns);
26870 /* We restore the source position here because it's used by
26871 add_pending_template. */
26872 input_location = saved_loc;
26874 if (at_eof && !pattern_defined
26875 && DECL_EXPLICIT_INSTANTIATION (d)
26876 && DECL_NOT_REALLY_EXTERN (d))
26877 /* [temp.explicit]
26879 The definition of a non-exported function template, a
26880 non-exported member function template, or a non-exported
26881 member function or static data member of a class template
26882 shall be present in every translation unit in which it is
26883 explicitly instantiated. */
26884 permerror (input_location, "explicit instantiation of %qD "
26885 "but no definition available", d);
26887 /* If we're in unevaluated context, we just wanted to get the
26888 constant value; this isn't an odr use, so don't queue
26889 a full instantiation. */
26890 if (!cp_unevaluated_operand
26891 /* ??? Historically, we have instantiated inline functions, even
26892 when marked as "extern template". */
26893 && !(external_p && VAR_P (d)))
26894 add_pending_template (d);
26896 else
26898 set_instantiating_module (d);
26899 if (variable_template_p (gen_tmpl))
26900 note_variable_template_instantiation (d);
26901 instantiate_body (td, args, d, false);
26904 pop_deferring_access_checks ();
26905 pop_tinst_level ();
26906 input_location = saved_loc;
26907 cp_unevaluated_operand = saved_unevaluated_operand;
26908 c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
26910 return d;
26913 /* Run through the list of templates that we wish we could
26914 instantiate, and instantiate any we can. RETRIES is the
26915 number of times we retry pending template instantiation. */
26917 void
26918 instantiate_pending_templates (int retries)
26920 int reconsider;
26921 location_t saved_loc = input_location;
26923 /* Instantiating templates may trigger vtable generation. This in turn
26924 may require further template instantiations. We place a limit here
26925 to avoid infinite loop. */
26926 if (pending_templates && retries >= max_tinst_depth)
26928 tree decl = pending_templates->tinst->maybe_get_node ();
26930 fatal_error (input_location,
26931 "template instantiation depth exceeds maximum of %d"
26932 " instantiating %q+D, possibly from virtual table generation"
26933 " (use %<-ftemplate-depth=%> to increase the maximum)",
26934 max_tinst_depth, decl);
26935 if (TREE_CODE (decl) == FUNCTION_DECL)
26936 /* Pretend that we defined it. */
26937 DECL_INITIAL (decl) = error_mark_node;
26938 return;
26943 struct pending_template **t = &pending_templates;
26944 struct pending_template *last = NULL;
26945 reconsider = 0;
26946 while (*t)
26948 tree instantiation = reopen_tinst_level ((*t)->tinst);
26949 bool complete = false;
26951 if (TYPE_P (instantiation))
26953 if (!COMPLETE_TYPE_P (instantiation))
26955 instantiate_class_template (instantiation);
26956 if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
26957 for (tree fld = TYPE_FIELDS (instantiation);
26958 fld; fld = TREE_CHAIN (fld))
26959 if ((VAR_P (fld)
26960 || (TREE_CODE (fld) == FUNCTION_DECL
26961 && !DECL_ARTIFICIAL (fld)))
26962 && DECL_TEMPLATE_INSTANTIATION (fld))
26963 instantiate_decl (fld,
26964 /*defer_ok=*/false,
26965 /*expl_inst_class_mem_p=*/false);
26967 if (COMPLETE_TYPE_P (instantiation))
26968 reconsider = 1;
26971 complete = COMPLETE_TYPE_P (instantiation);
26973 else
26975 if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
26976 && !DECL_TEMPLATE_INSTANTIATED (instantiation))
26978 instantiation
26979 = instantiate_decl (instantiation,
26980 /*defer_ok=*/false,
26981 /*expl_inst_class_mem_p=*/false);
26982 if (DECL_TEMPLATE_INSTANTIATED (instantiation))
26983 reconsider = 1;
26986 complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
26987 || DECL_TEMPLATE_INSTANTIATED (instantiation));
26990 if (complete)
26992 /* If INSTANTIATION has been instantiated, then we don't
26993 need to consider it again in the future. */
26994 struct pending_template *drop = *t;
26995 *t = (*t)->next;
26996 set_refcount_ptr (drop->tinst);
26997 pending_template_freelist ().free (drop);
26999 else
27001 last = *t;
27002 t = &(*t)->next;
27004 tinst_depth = 0;
27005 set_refcount_ptr (current_tinst_level);
27007 last_pending_template = last;
27009 while (reconsider);
27011 input_location = saved_loc;
27014 /* Substitute ARGVEC into T, which is a list of initializers for
27015 either base class or a non-static data member. The TREE_PURPOSEs
27016 are DECLs, and the TREE_VALUEs are the initializer values. Used by
27017 instantiate_decl. */
27019 static tree
27020 tsubst_initializer_list (tree t, tree argvec)
27022 tree inits = NULL_TREE;
27023 tree target_ctor = error_mark_node;
27025 for (; t; t = TREE_CHAIN (t))
27027 tree decl;
27028 tree init;
27029 tree expanded_bases = NULL_TREE;
27030 tree expanded_arguments = NULL_TREE;
27031 int i, len = 1;
27033 if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
27035 tree expr;
27036 tree arg;
27038 /* Expand the base class expansion type into separate base
27039 classes. */
27040 expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
27041 tf_warning_or_error,
27042 NULL_TREE);
27043 if (expanded_bases == error_mark_node)
27044 continue;
27046 /* We'll be building separate TREE_LISTs of arguments for
27047 each base. */
27048 len = TREE_VEC_LENGTH (expanded_bases);
27049 expanded_arguments = make_tree_vec (len);
27050 for (i = 0; i < len; i++)
27051 TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
27053 /* Build a dummy EXPR_PACK_EXPANSION that will be used to
27054 expand each argument in the TREE_VALUE of t. */
27055 expr = make_node (EXPR_PACK_EXPANSION);
27056 PACK_EXPANSION_LOCAL_P (expr) = true;
27057 PACK_EXPANSION_PARAMETER_PACKS (expr) =
27058 PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
27060 if (TREE_VALUE (t) == void_type_node)
27061 /* VOID_TYPE_NODE is used to indicate
27062 value-initialization. */
27064 for (i = 0; i < len; i++)
27065 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
27067 else
27069 /* Substitute parameter packs into each argument in the
27070 TREE_LIST. */
27071 in_base_initializer = 1;
27072 for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
27074 tree expanded_exprs;
27076 /* Expand the argument. */
27077 tree value;
27078 if (TREE_CODE (TREE_VALUE (arg)) == EXPR_PACK_EXPANSION)
27079 value = TREE_VALUE (arg);
27080 else
27082 value = expr;
27083 PACK_EXPANSION_PATTERN (value) = TREE_VALUE (arg);
27085 expanded_exprs
27086 = tsubst_pack_expansion (value, argvec,
27087 tf_warning_or_error,
27088 NULL_TREE);
27089 if (expanded_exprs == error_mark_node)
27090 continue;
27092 /* Prepend each of the expanded expressions to the
27093 corresponding TREE_LIST in EXPANDED_ARGUMENTS. */
27094 for (i = 0; i < len; i++)
27095 if (TREE_CODE (TREE_VALUE (arg)) == EXPR_PACK_EXPANSION)
27096 for (int j = 0; j < TREE_VEC_LENGTH (expanded_exprs); j++)
27097 TREE_VEC_ELT (expanded_arguments, i)
27098 = tree_cons (NULL_TREE,
27099 TREE_VEC_ELT (expanded_exprs, j),
27100 TREE_VEC_ELT (expanded_arguments, i));
27101 else
27102 TREE_VEC_ELT (expanded_arguments, i)
27103 = tree_cons (NULL_TREE,
27104 TREE_VEC_ELT (expanded_exprs, i),
27105 TREE_VEC_ELT (expanded_arguments, i));
27107 in_base_initializer = 0;
27109 /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
27110 since we built them backwards. */
27111 for (i = 0; i < len; i++)
27113 TREE_VEC_ELT (expanded_arguments, i) =
27114 nreverse (TREE_VEC_ELT (expanded_arguments, i));
27119 for (i = 0; i < len; ++i)
27121 if (expanded_bases)
27123 decl = TREE_VEC_ELT (expanded_bases, i);
27124 decl = expand_member_init (decl);
27125 init = TREE_VEC_ELT (expanded_arguments, i);
27127 else
27129 tree tmp;
27130 decl = tsubst_copy (TREE_PURPOSE (t), argvec,
27131 tf_warning_or_error, NULL_TREE);
27133 decl = expand_member_init (decl);
27134 if (decl && !DECL_P (decl))
27135 in_base_initializer = 1;
27137 init = TREE_VALUE (t);
27138 tmp = init;
27139 if (init != void_type_node)
27140 init = tsubst_expr (init, argvec,
27141 tf_warning_or_error, NULL_TREE);
27142 if (init == NULL_TREE && tmp != NULL_TREE)
27143 /* If we had an initializer but it instantiated to nothing,
27144 value-initialize the object. This will only occur when
27145 the initializer was a pack expansion where the parameter
27146 packs used in that expansion were of length zero. */
27147 init = void_type_node;
27148 in_base_initializer = 0;
27151 if (target_ctor != error_mark_node
27152 && init != error_mark_node)
27154 error ("mem-initializer for %qD follows constructor delegation",
27155 decl);
27156 return inits;
27158 /* Look for a target constructor. */
27159 if (init != error_mark_node
27160 && decl && CLASS_TYPE_P (decl)
27161 && same_type_p (decl, current_class_type))
27163 maybe_warn_cpp0x (CPP0X_DELEGATING_CTORS);
27164 if (inits)
27166 error ("constructor delegation follows mem-initializer for %qD",
27167 TREE_PURPOSE (inits));
27168 continue;
27170 target_ctor = init;
27173 if (decl)
27175 init = build_tree_list (decl, init);
27176 /* Carry over the dummy TREE_TYPE node containing the source
27177 location. */
27178 TREE_TYPE (init) = TREE_TYPE (t);
27179 TREE_CHAIN (init) = inits;
27180 inits = init;
27184 return inits;
27187 /* Instantiate an enumerated type. TAG is the template type, NEWTAG
27188 is the instantiation (which should have been created with
27189 start_enum) and ARGS are the template arguments to use. */
27191 static void
27192 tsubst_enum (tree tag, tree newtag, tree args)
27194 tree e;
27196 if (SCOPED_ENUM_P (newtag))
27197 begin_scope (sk_scoped_enum, newtag);
27199 for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
27201 tree value;
27202 tree decl = TREE_VALUE (e);
27204 /* Note that in a template enum, the TREE_VALUE is the
27205 CONST_DECL, not the corresponding INTEGER_CST. */
27206 value = tsubst_expr (DECL_INITIAL (decl),
27207 args, tf_warning_or_error, NULL_TREE);
27209 /* Give this enumeration constant the correct access. */
27210 set_current_access_from_decl (decl);
27212 /* Actually build the enumerator itself. Here we're assuming that
27213 enumerators can't have dependent attributes. */
27214 tree newdecl = build_enumerator (DECL_NAME (decl), value, newtag,
27215 DECL_ATTRIBUTES (decl),
27216 DECL_SOURCE_LOCATION (decl));
27217 /* Attribute deprecated without an argument isn't sticky: it'll
27218 melt into a tree flag, so we need to propagate the flag here,
27219 since we just created a new enumerator. */
27220 TREE_DEPRECATED (newdecl) = TREE_DEPRECATED (decl);
27221 TREE_UNAVAILABLE (newdecl) = TREE_UNAVAILABLE (decl);
27224 if (SCOPED_ENUM_P (newtag))
27225 finish_scope ();
27227 finish_enum_value_list (newtag);
27228 finish_enum (newtag);
27230 DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
27231 = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
27232 TREE_DEPRECATED (newtag) = TREE_DEPRECATED (tag);
27233 TREE_UNAVAILABLE (newtag) = TREE_UNAVAILABLE (tag);
27236 /* DECL is a FUNCTION_DECL that is a template specialization. Return
27237 its type -- but without substituting the innermost set of template
27238 arguments. So, innermost set of template parameters will appear in
27239 the type. */
27241 tree
27242 get_mostly_instantiated_function_type (tree decl)
27244 /* For a function, DECL_TI_TEMPLATE is partially instantiated. */
27245 return TREE_TYPE (DECL_TI_TEMPLATE (decl));
27248 /* Return truthvalue if we're processing a template different from
27249 the last one involved in diagnostics. */
27250 bool
27251 problematic_instantiation_changed (void)
27253 return current_tinst_level != last_error_tinst_level;
27256 /* Remember current template involved in diagnostics. */
27257 void
27258 record_last_problematic_instantiation (void)
27260 set_refcount_ptr (last_error_tinst_level, current_tinst_level);
27263 struct tinst_level *
27264 current_instantiation (void)
27266 return current_tinst_level;
27269 /* Return TRUE if current_function_decl is being instantiated, false
27270 otherwise. */
27272 bool
27273 instantiating_current_function_p (void)
27275 return (current_instantiation ()
27276 && (current_instantiation ()->maybe_get_node ()
27277 == current_function_decl));
27280 /* [temp.param] Check that template non-type parm TYPE is of an allowable
27281 type. Return false for ok, true for disallowed. Issue error and
27282 inform messages under control of COMPLAIN. */
27284 static bool
27285 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
27287 if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
27288 return false;
27289 else if (TYPE_PTR_P (type))
27290 return false;
27291 else if (TYPE_REF_P (type)
27292 && !TYPE_REF_IS_RVALUE (type))
27293 return false;
27294 else if (TYPE_PTRMEM_P (type))
27295 return false;
27296 else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
27298 if (CLASS_PLACEHOLDER_TEMPLATE (type) && cxx_dialect < cxx20)
27300 if (complain & tf_error)
27301 error ("non-type template parameters of deduced class type only "
27302 "available with %<-std=c++20%> or %<-std=gnu++20%>");
27303 return true;
27305 return false;
27307 else if (TREE_CODE (type) == NULLPTR_TYPE)
27308 return false;
27309 else if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM
27310 && cxx_dialect < cxx11)
27311 /* Fall through; before C++11 alias templates, a bound ttp
27312 always instantiates into a class type. */;
27313 else if (WILDCARD_TYPE_P (type))
27314 /* Any other wildcard type not already handled above is allowed. */
27315 return false;
27316 else if (TREE_CODE (type) == COMPLEX_TYPE)
27317 /* Fall through. */;
27318 else if (VOID_TYPE_P (type))
27319 /* Fall through. */;
27320 else if (cxx_dialect >= cxx20)
27322 if (dependent_type_p (type))
27323 return false;
27324 if (!complete_type_or_maybe_complain (type, NULL_TREE, complain))
27325 return true;
27326 if (structural_type_p (type))
27327 return false;
27328 if (complain & tf_error)
27330 auto_diagnostic_group d;
27331 error ("%qT is not a valid type for a template non-type "
27332 "parameter because it is not structural", type);
27333 structural_type_p (type, true);
27335 return true;
27337 else if (CLASS_TYPE_P (type))
27339 if (complain & tf_error)
27340 error ("non-type template parameters of class type only available "
27341 "with %<-std=c++20%> or %<-std=gnu++20%>");
27342 return true;
27345 if (complain & tf_error)
27347 if (type == error_mark_node)
27348 inform (input_location, "invalid template non-type parameter");
27349 else
27350 error ("%q#T is not a valid type for a template non-type parameter",
27351 type);
27353 return true;
27356 /* Returns true iff the noexcept-specifier for TYPE is value-dependent. */
27358 static bool
27359 value_dependent_noexcept_spec_p (tree type)
27361 if (tree spec = TYPE_RAISES_EXCEPTIONS (type))
27362 if (tree noex = TREE_PURPOSE (spec))
27363 /* Treat DEFERRED_NOEXCEPT as non-dependent, since it doesn't
27364 affect overload resolution and treating it as dependent breaks
27365 things. Same for an unparsed noexcept expression. */
27366 if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
27367 && TREE_CODE (noex) != DEFERRED_PARSE
27368 && value_dependent_expression_p (noex))
27369 return true;
27371 return false;
27374 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
27375 Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
27377 static bool
27378 dependent_type_p_r (tree type)
27380 tree scope;
27382 /* [temp.dep.type]
27384 A type is dependent if it is:
27386 -- a template parameter. Template template parameters are types
27387 for us (since TYPE_P holds true for them) so we handle
27388 them here. */
27389 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
27390 || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
27391 return true;
27392 /* -- a qualified-id with a nested-name-specifier which contains a
27393 class-name that names a dependent type or whose unqualified-id
27394 names a dependent type. */
27395 if (TREE_CODE (type) == TYPENAME_TYPE)
27396 return true;
27398 /* An alias template specialization can be dependent even if the
27399 resulting type is not. */
27400 if (dependent_alias_template_spec_p (type, nt_transparent))
27401 return true;
27403 /* -- a cv-qualified type where the cv-unqualified type is
27404 dependent.
27405 No code is necessary for this bullet; the code below handles
27406 cv-qualified types, and we don't want to strip aliases with
27407 TYPE_MAIN_VARIANT because of DR 1558. */
27408 /* -- a compound type constructed from any dependent type. */
27409 if (TYPE_PTRMEM_P (type))
27410 return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
27411 || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
27412 (type)));
27413 else if (INDIRECT_TYPE_P (type))
27414 return dependent_type_p (TREE_TYPE (type));
27415 else if (FUNC_OR_METHOD_TYPE_P (type))
27417 tree arg_type;
27419 if (dependent_type_p (TREE_TYPE (type)))
27420 return true;
27421 for (arg_type = TYPE_ARG_TYPES (type);
27422 arg_type;
27423 arg_type = TREE_CHAIN (arg_type))
27424 if (dependent_type_p (TREE_VALUE (arg_type)))
27425 return true;
27426 if (cxx_dialect >= cxx17
27427 && value_dependent_noexcept_spec_p (type))
27428 /* A value-dependent noexcept-specifier makes the type dependent. */
27429 return true;
27430 return false;
27432 /* -- an array type constructed from any dependent type or whose
27433 size is specified by a constant expression that is
27434 value-dependent.
27436 We checked for type- and value-dependence of the bounds in
27437 compute_array_index_type, so TYPE_DEPENDENT_P is already set. */
27438 if (TREE_CODE (type) == ARRAY_TYPE)
27440 if (TYPE_DOMAIN (type)
27441 && dependent_type_p (TYPE_DOMAIN (type)))
27442 return true;
27443 return dependent_type_p (TREE_TYPE (type));
27446 /* -- a template-id in which either the template name is a template
27447 parameter ... */
27448 if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
27449 return true;
27450 /* ... or any of the template arguments is a dependent type or
27451 an expression that is type-dependent or value-dependent. */
27452 else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
27453 && (any_dependent_template_arguments_p
27454 (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
27455 return true;
27457 /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and TRAIT_TYPEs are
27458 dependent; if the argument of the `typeof' expression is not
27459 type-dependent, then it should already been have resolved. */
27460 if (TREE_CODE (type) == TYPEOF_TYPE
27461 || TREE_CODE (type) == DECLTYPE_TYPE
27462 || TREE_CODE (type) == TRAIT_TYPE)
27463 return true;
27465 /* A template argument pack is dependent if any of its packed
27466 arguments are. */
27467 if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
27469 tree args = ARGUMENT_PACK_ARGS (type);
27470 for (tree arg : tree_vec_range (args))
27471 if (dependent_template_arg_p (arg))
27472 return true;
27475 /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
27476 be template parameters. */
27477 if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
27478 return true;
27480 if (TREE_CODE (type) == DEPENDENT_OPERATOR_TYPE)
27481 return true;
27483 if (any_dependent_type_attributes_p (TYPE_ATTRIBUTES (type)))
27484 return true;
27486 /* The standard does not specifically mention types that are local
27487 to template functions or local classes, but they should be
27488 considered dependent too. For example:
27490 template <int I> void f() {
27491 enum E { a = I };
27492 S<sizeof (E)> s;
27495 The size of `E' cannot be known until the value of `I' has been
27496 determined. Therefore, `E' must be considered dependent. */
27497 scope = TYPE_CONTEXT (type);
27498 if (scope && TYPE_P (scope))
27499 return dependent_type_p (scope);
27500 /* Don't use type_dependent_expression_p here, as it can lead
27501 to infinite recursion trying to determine whether a lambda
27502 nested in a lambda is dependent (c++/47687). */
27503 else if (scope && TREE_CODE (scope) == FUNCTION_DECL
27504 && DECL_LANG_SPECIFIC (scope)
27505 && DECL_TEMPLATE_INFO (scope)
27506 && (any_dependent_template_arguments_p
27507 (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
27508 return true;
27510 /* Other types are non-dependent. */
27511 return false;
27514 /* Returns TRUE if TYPE is dependent, in the sense of
27515 [temp.dep.type]. Note that a NULL type is considered dependent. */
27517 bool
27518 dependent_type_p (tree type)
27520 /* If there are no template parameters in scope, then there can't be
27521 any dependent types. */
27522 if (!processing_template_decl)
27524 /* If we are not processing a template, then nobody should be
27525 providing us with a dependent type. */
27526 gcc_assert (type);
27527 gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
27528 return false;
27531 /* If the type is NULL, we have not computed a type for the entity
27532 in question; in that case, the type is dependent. */
27533 if (!type)
27534 return true;
27536 /* Erroneous types can be considered non-dependent. */
27537 if (type == error_mark_node)
27538 return false;
27540 /* If we have not already computed the appropriate value for TYPE,
27541 do so now. */
27542 if (!TYPE_DEPENDENT_P_VALID (type))
27544 TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
27545 TYPE_DEPENDENT_P_VALID (type) = 1;
27548 return TYPE_DEPENDENT_P (type);
27551 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
27552 lookup. In other words, a dependent type that is not the current
27553 instantiation. */
27555 bool
27556 dependent_scope_p (tree scope)
27558 return (scope && TYPE_P (scope) && dependent_type_p (scope)
27559 && !currently_open_class (scope));
27562 /* True if we might find more declarations in SCOPE during instantiation than
27563 we can when parsing the template. */
27565 bool
27566 dependentish_scope_p (tree scope)
27568 return dependent_scope_p (scope) || any_dependent_bases_p (scope);
27571 /* T is a SCOPE_REF. Return whether it represents a non-static member of
27572 an unknown base of 'this' (and is therefore instantiation-dependent). */
27574 static bool
27575 unknown_base_ref_p (tree t)
27577 if (!current_class_ptr)
27578 return false;
27580 tree mem = TREE_OPERAND (t, 1);
27581 if (shared_member_p (mem))
27582 return false;
27584 tree cur = current_nonlambda_class_type ();
27585 if (!any_dependent_bases_p (cur))
27586 return false;
27588 tree ctx = TREE_OPERAND (t, 0);
27589 if (DERIVED_FROM_P (ctx, cur))
27590 return false;
27592 return true;
27595 /* T is a SCOPE_REF; return whether we need to consider it
27596 instantiation-dependent so that we can check access at instantiation
27597 time even though we know which member it resolves to. */
27599 static bool
27600 instantiation_dependent_scope_ref_p (tree t)
27602 if (DECL_P (TREE_OPERAND (t, 1))
27603 && CLASS_TYPE_P (TREE_OPERAND (t, 0))
27604 && !dependent_scope_p (TREE_OPERAND (t, 0))
27605 && !unknown_base_ref_p (t)
27606 && accessible_in_template_p (TREE_OPERAND (t, 0),
27607 TREE_OPERAND (t, 1)))
27608 return false;
27609 else
27610 return true;
27613 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
27614 [temp.dep.constexpr]. EXPRESSION is already known to be a constant
27615 expression. */
27617 /* Note that this predicate is not appropriate for general expressions;
27618 only constant expressions (that satisfy potential_constant_expression)
27619 can be tested for value dependence. */
27621 bool
27622 value_dependent_expression_p (tree expression)
27624 if (!processing_template_decl || expression == NULL_TREE)
27625 return false;
27627 /* A type-dependent expression is also value-dependent. */
27628 if (type_dependent_expression_p (expression))
27629 return true;
27631 switch (TREE_CODE (expression))
27633 case BASELINK:
27634 /* A dependent member function of the current instantiation. */
27635 return dependent_type_p (BINFO_TYPE (BASELINK_BINFO (expression)));
27637 case FUNCTION_DECL:
27638 /* A dependent member function of the current instantiation. */
27639 if (DECL_CLASS_SCOPE_P (expression)
27640 && dependent_type_p (DECL_CONTEXT (expression)))
27641 return true;
27642 break;
27644 case IDENTIFIER_NODE:
27645 /* A name that has not been looked up -- must be dependent. */
27646 return true;
27648 case TEMPLATE_PARM_INDEX:
27649 /* A non-type template parm. */
27650 return true;
27652 case CONST_DECL:
27653 /* A non-type template parm. */
27654 if (DECL_TEMPLATE_PARM_P (expression))
27655 return true;
27656 return value_dependent_expression_p (DECL_INITIAL (expression));
27658 case VAR_DECL:
27659 /* A constant with literal type and is initialized
27660 with an expression that is value-dependent. */
27661 if (DECL_DEPENDENT_INIT_P (expression)
27662 /* FIXME cp_finish_decl doesn't fold reference initializers. */
27663 || TYPE_REF_P (TREE_TYPE (expression)))
27664 return true;
27665 if (DECL_HAS_VALUE_EXPR_P (expression))
27667 tree value_expr = DECL_VALUE_EXPR (expression);
27668 if (value_dependent_expression_p (value_expr)
27669 /* __PRETTY_FUNCTION__ inside a template function is dependent
27670 on the name of the function. */
27671 || (DECL_PRETTY_FUNCTION_P (expression)
27672 /* It might be used in a template, but not a template
27673 function, in which case its DECL_VALUE_EXPR will be
27674 "top level". */
27675 && value_expr == error_mark_node))
27676 return true;
27678 return false;
27680 case DYNAMIC_CAST_EXPR:
27681 case STATIC_CAST_EXPR:
27682 case CONST_CAST_EXPR:
27683 case REINTERPRET_CAST_EXPR:
27684 case CAST_EXPR:
27685 case IMPLICIT_CONV_EXPR:
27686 /* These expressions are value-dependent if the type to which
27687 the cast occurs is dependent or the expression being casted
27688 is value-dependent. */
27690 tree type = TREE_TYPE (expression);
27692 if (dependent_type_p (type))
27693 return true;
27695 /* A functional cast has a list of operands. */
27696 expression = TREE_OPERAND (expression, 0);
27697 if (!expression)
27699 /* If there are no operands, it must be an expression such
27700 as "int()". This should not happen for aggregate types
27701 because it would form non-constant expressions. */
27702 gcc_assert (cxx_dialect >= cxx11
27703 || INTEGRAL_OR_ENUMERATION_TYPE_P (type));
27705 return false;
27708 if (TREE_CODE (expression) == TREE_LIST)
27709 return any_value_dependent_elements_p (expression);
27711 if (TREE_CODE (type) == REFERENCE_TYPE
27712 && has_value_dependent_address (expression))
27713 return true;
27715 return value_dependent_expression_p (expression);
27718 case SIZEOF_EXPR:
27719 if (SIZEOF_EXPR_TYPE_P (expression))
27720 return dependent_type_p (TREE_TYPE (TREE_OPERAND (expression, 0)));
27721 /* FALLTHRU */
27722 case ALIGNOF_EXPR:
27723 case TYPEID_EXPR:
27724 /* A `sizeof' expression is value-dependent if the operand is
27725 type-dependent or is a pack expansion. */
27726 expression = TREE_OPERAND (expression, 0);
27727 if (PACK_EXPANSION_P (expression))
27728 return true;
27729 else if (TYPE_P (expression))
27730 return dependent_type_p (expression);
27731 return instantiation_dependent_uneval_expression_p (expression);
27733 case AT_ENCODE_EXPR:
27734 /* An 'encode' expression is value-dependent if the operand is
27735 type-dependent. */
27736 expression = TREE_OPERAND (expression, 0);
27737 return dependent_type_p (expression);
27739 case NOEXCEPT_EXPR:
27740 expression = TREE_OPERAND (expression, 0);
27741 return instantiation_dependent_uneval_expression_p (expression);
27743 case SCOPE_REF:
27744 /* All instantiation-dependent expressions should also be considered
27745 value-dependent. */
27746 return instantiation_dependent_scope_ref_p (expression);
27748 case COMPONENT_REF:
27749 return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
27750 || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
27752 case NONTYPE_ARGUMENT_PACK:
27753 /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
27754 is value-dependent. */
27755 for (tree arg : tree_vec_range (ARGUMENT_PACK_ARGS (expression)))
27756 if (value_dependent_expression_p (arg))
27757 return true;
27758 return false;
27760 case TRAIT_EXPR:
27762 tree type2 = TRAIT_EXPR_TYPE2 (expression);
27764 if (dependent_type_p (TRAIT_EXPR_TYPE1 (expression)))
27765 return true;
27767 if (!type2)
27768 return false;
27770 if (TREE_CODE (type2) != TREE_LIST)
27771 return dependent_type_p (type2);
27773 for (; type2; type2 = TREE_CHAIN (type2))
27774 if (dependent_type_p (TREE_VALUE (type2)))
27775 return true;
27777 return false;
27780 case MODOP_EXPR:
27781 return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
27782 || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
27784 case ARRAY_REF:
27785 return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
27786 || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
27788 case ADDR_EXPR:
27790 tree op = TREE_OPERAND (expression, 0);
27791 return (value_dependent_expression_p (op)
27792 || has_value_dependent_address (op));
27795 case REQUIRES_EXPR:
27796 /* Treat all requires-expressions as value-dependent so
27797 we don't try to fold them. */
27798 return true;
27800 case TYPE_REQ:
27801 return dependent_type_p (TREE_OPERAND (expression, 0));
27803 case CALL_EXPR:
27805 if (value_dependent_expression_p (CALL_EXPR_FN (expression)))
27806 return true;
27807 tree fn = get_callee_fndecl (expression);
27808 int i, nargs;
27809 nargs = call_expr_nargs (expression);
27810 for (i = 0; i < nargs; ++i)
27812 tree op = CALL_EXPR_ARG (expression, i);
27813 /* In a call to a constexpr member function, look through the
27814 implicit ADDR_EXPR on the object argument so that it doesn't
27815 cause the call to be considered value-dependent. We also
27816 look through it in potential_constant_expression. */
27817 if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
27818 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
27819 && TREE_CODE (op) == ADDR_EXPR)
27820 op = TREE_OPERAND (op, 0);
27821 if (value_dependent_expression_p (op))
27822 return true;
27824 return false;
27827 case TEMPLATE_ID_EXPR:
27828 return concept_definition_p (TREE_OPERAND (expression, 0))
27829 && any_dependent_template_arguments_p (TREE_OPERAND (expression, 1));
27831 case CONSTRUCTOR:
27833 unsigned ix;
27834 tree val;
27835 if (dependent_type_p (TREE_TYPE (expression)))
27836 return true;
27837 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
27838 if (value_dependent_expression_p (val))
27839 return true;
27840 return false;
27843 case STMT_EXPR:
27844 /* Treat a GNU statement expression as dependent to avoid crashing
27845 under instantiate_non_dependent_expr; it can't be constant. */
27846 return true;
27848 case NEW_EXPR:
27849 case VEC_NEW_EXPR:
27850 /* The second operand is a type, which type_dependent_expression_p
27851 (and therefore value_dependent_expression_p) doesn't want to see. */
27852 return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
27853 || value_dependent_expression_p (TREE_OPERAND (expression, 2))
27854 || value_dependent_expression_p (TREE_OPERAND (expression, 3)));
27856 default:
27857 /* A constant expression is value-dependent if any subexpression is
27858 value-dependent. */
27859 switch (TREE_CODE_CLASS (TREE_CODE (expression)))
27861 case tcc_reference:
27862 case tcc_unary:
27863 case tcc_comparison:
27864 case tcc_binary:
27865 case tcc_expression:
27866 case tcc_vl_exp:
27868 int i, len = cp_tree_operand_length (expression);
27870 for (i = 0; i < len; i++)
27872 tree t = TREE_OPERAND (expression, i);
27874 /* In some cases, some of the operands may be missing.
27875 (For example, in the case of PREDECREMENT_EXPR, the
27876 amount to increment by may be missing.) That doesn't
27877 make the expression dependent. */
27878 if (t && value_dependent_expression_p (t))
27879 return true;
27882 break;
27883 default:
27884 break;
27886 break;
27889 /* The expression is not value-dependent. */
27890 return false;
27893 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
27894 [temp.dep.expr]. Note that an expression with no type is
27895 considered dependent. Other parts of the compiler arrange for an
27896 expression with type-dependent subexpressions to have no type, so
27897 this function doesn't have to be fully recursive. */
27899 bool
27900 type_dependent_expression_p (tree expression)
27902 if (!processing_template_decl)
27903 return false;
27905 if (expression == NULL_TREE || expression == error_mark_node)
27906 return false;
27908 gcc_checking_assert (!TYPE_P (expression));
27910 STRIP_ANY_LOCATION_WRAPPER (expression);
27912 /* An unresolved name is always dependent. */
27913 if (identifier_p (expression)
27914 || TREE_CODE (expression) == USING_DECL
27915 || TREE_CODE (expression) == WILDCARD_DECL)
27916 return true;
27918 /* A lambda-expression in template context is dependent. dependent_type_p is
27919 true for a lambda in the scope of a class or function template, but that
27920 doesn't cover all template contexts, like a default template argument. */
27921 if (TREE_CODE (expression) == LAMBDA_EXPR)
27922 return true;
27924 /* A fold expression is type-dependent. */
27925 if (TREE_CODE (expression) == UNARY_LEFT_FOLD_EXPR
27926 || TREE_CODE (expression) == UNARY_RIGHT_FOLD_EXPR
27927 || TREE_CODE (expression) == BINARY_LEFT_FOLD_EXPR
27928 || TREE_CODE (expression) == BINARY_RIGHT_FOLD_EXPR)
27929 return true;
27931 /* Some expression forms are never type-dependent. */
27932 if (TREE_CODE (expression) == SIZEOF_EXPR
27933 || TREE_CODE (expression) == ALIGNOF_EXPR
27934 || TREE_CODE (expression) == AT_ENCODE_EXPR
27935 || TREE_CODE (expression) == NOEXCEPT_EXPR
27936 || TREE_CODE (expression) == TRAIT_EXPR
27937 || TREE_CODE (expression) == TYPEID_EXPR
27938 || TREE_CODE (expression) == DELETE_EXPR
27939 || TREE_CODE (expression) == VEC_DELETE_EXPR
27940 || TREE_CODE (expression) == THROW_EXPR
27941 || TREE_CODE (expression) == REQUIRES_EXPR)
27942 return false;
27944 /* The types of these expressions depends only on the type to which
27945 the cast occurs. */
27946 if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
27947 || TREE_CODE (expression) == STATIC_CAST_EXPR
27948 || TREE_CODE (expression) == CONST_CAST_EXPR
27949 || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
27950 || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
27951 || TREE_CODE (expression) == CAST_EXPR)
27952 return dependent_type_p (TREE_TYPE (expression));
27954 /* The types of these expressions depends only on the type created
27955 by the expression. */
27956 if (TREE_CODE (expression) == NEW_EXPR
27957 || TREE_CODE (expression) == VEC_NEW_EXPR)
27959 /* For NEW_EXPR tree nodes created inside a template, either
27960 the object type itself or a TREE_LIST may appear as the
27961 operand 1. */
27962 tree type = TREE_OPERAND (expression, 1);
27963 if (TREE_CODE (type) == TREE_LIST)
27964 /* This is an array type. We need to check array dimensions
27965 as well. */
27966 return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
27967 || value_dependent_expression_p
27968 (TREE_OPERAND (TREE_VALUE (type), 1));
27969 /* Array type whose dimension has to be deduced. */
27970 else if (TREE_CODE (type) == ARRAY_TYPE
27971 && TREE_OPERAND (expression, 2) == NULL_TREE)
27972 return true;
27973 else
27974 return dependent_type_p (type);
27977 if (TREE_CODE (expression) == SCOPE_REF)
27979 tree scope = TREE_OPERAND (expression, 0);
27980 tree name = TREE_OPERAND (expression, 1);
27982 /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
27983 contains an identifier associated by name lookup with one or more
27984 declarations declared with a dependent type, or...a
27985 nested-name-specifier or qualified-id that names a member of an
27986 unknown specialization. */
27987 return (type_dependent_expression_p (name)
27988 || dependent_scope_p (scope));
27991 if (TREE_CODE (expression) == TEMPLATE_DECL
27992 && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
27993 return uses_outer_template_parms (expression);
27995 if (TREE_CODE (expression) == STMT_EXPR)
27996 expression = stmt_expr_value_expr (expression);
27998 if (BRACE_ENCLOSED_INITIALIZER_P (expression))
28000 for (auto &elt : CONSTRUCTOR_ELTS (expression))
28001 if (type_dependent_expression_p (elt.value))
28002 return true;
28003 return false;
28006 /* A static data member of the current instantiation with incomplete
28007 array type is type-dependent, as the definition and specializations
28008 can have different bounds. */
28009 if (VAR_P (expression)
28010 && DECL_CLASS_SCOPE_P (expression)
28011 && dependent_type_p (DECL_CONTEXT (expression))
28012 && VAR_HAD_UNKNOWN_BOUND (expression))
28013 return true;
28015 /* An array of unknown bound depending on a variadic parameter, eg:
28017 template<typename... Args>
28018 void foo (Args... args)
28020 int arr[] = { args... };
28023 template<int... vals>
28024 void bar ()
28026 int arr[] = { vals... };
28029 If the array has no length and has an initializer, it must be that
28030 we couldn't determine its length in cp_complete_array_type because
28031 it is dependent. */
28032 if (((VAR_P (expression) && DECL_INITIAL (expression))
28033 || COMPOUND_LITERAL_P (expression))
28034 && TREE_TYPE (expression) != NULL_TREE
28035 && TREE_CODE (TREE_TYPE (expression)) == ARRAY_TYPE
28036 && !TYPE_DOMAIN (TREE_TYPE (expression)))
28037 return true;
28039 /* Pull a FUNCTION_DECL out of a BASELINK if we can. */
28040 if (BASELINK_P (expression))
28042 if (BASELINK_OPTYPE (expression)
28043 && dependent_type_p (BASELINK_OPTYPE (expression)))
28044 return true;
28045 expression = BASELINK_FUNCTIONS (expression);
28048 /* A function or variable template-id is type-dependent if it has any
28049 dependent template arguments. */
28050 if (VAR_OR_FUNCTION_DECL_P (expression)
28051 && DECL_LANG_SPECIFIC (expression)
28052 && DECL_TEMPLATE_INFO (expression))
28054 /* Consider the innermost template arguments, since those are the ones
28055 that come from the template-id; the template arguments for the
28056 enclosing class do not make it type-dependent unless they are used in
28057 the type of the decl. */
28058 if (instantiates_primary_template_p (expression)
28059 && (any_dependent_template_arguments_p
28060 (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
28061 return true;
28064 /* Otherwise, if the function decl isn't from a dependent scope, it can't be
28065 type-dependent. Checking this is important for functions with auto return
28066 type, which looks like a dependent type. */
28067 if (TREE_CODE (expression) == FUNCTION_DECL
28068 && !(DECL_CLASS_SCOPE_P (expression)
28069 && dependent_type_p (DECL_CONTEXT (expression)))
28070 && !(DECL_LANG_SPECIFIC (expression)
28071 && DECL_UNIQUE_FRIEND_P (expression)
28072 && (!DECL_FRIEND_CONTEXT (expression)
28073 || dependent_type_p (DECL_FRIEND_CONTEXT (expression))))
28074 && !DECL_LOCAL_DECL_P (expression))
28076 gcc_assert (!dependent_type_p (TREE_TYPE (expression))
28077 || undeduced_auto_decl (expression));
28078 return false;
28081 /* Otherwise, its constraints could still depend on outer template parameters
28082 from its (dependent) scope. */
28083 if (TREE_CODE (expression) == FUNCTION_DECL
28084 /* As an optimization, check this cheaper sufficient condition first.
28085 (At this point we've established that we're looking at a member of
28086 a dependent class, so it makes sense to start treating say undeduced
28087 auto as dependent.) */
28088 && !dependent_type_p (TREE_TYPE (expression))
28089 && uses_outer_template_parms_in_constraints (expression))
28090 return true;
28092 /* Always dependent, on the number of arguments if nothing else. */
28093 if (TREE_CODE (expression) == EXPR_PACK_EXPANSION)
28094 return true;
28096 if (TREE_TYPE (expression) == unknown_type_node)
28098 if (TREE_CODE (expression) == ADDR_EXPR)
28099 return type_dependent_expression_p (TREE_OPERAND (expression, 0));
28100 if (TREE_CODE (expression) == COMPONENT_REF
28101 || TREE_CODE (expression) == OFFSET_REF)
28103 if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
28104 return true;
28105 expression = TREE_OPERAND (expression, 1);
28106 if (identifier_p (expression))
28107 return false;
28109 /* SCOPE_REF with non-null TREE_TYPE is always non-dependent. */
28110 if (TREE_CODE (expression) == SCOPE_REF)
28111 return false;
28113 /* CO_AWAIT/YIELD_EXPR with unknown type is always dependent. */
28114 if (TREE_CODE (expression) == CO_AWAIT_EXPR
28115 || TREE_CODE (expression) == CO_YIELD_EXPR)
28116 return true;
28118 if (BASELINK_P (expression))
28120 if (BASELINK_OPTYPE (expression)
28121 && dependent_type_p (BASELINK_OPTYPE (expression)))
28122 return true;
28123 expression = BASELINK_FUNCTIONS (expression);
28126 if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
28128 if (any_dependent_template_arguments_p
28129 (TREE_OPERAND (expression, 1)))
28130 return true;
28131 expression = TREE_OPERAND (expression, 0);
28132 if (identifier_p (expression))
28133 return true;
28136 gcc_assert (OVL_P (expression));
28138 for (lkp_iterator iter (expression); iter; ++iter)
28139 if (type_dependent_expression_p (*iter))
28140 return true;
28142 return false;
28145 /* The type of a non-type template parm declared with a placeholder type
28146 depends on the corresponding template argument, even though
28147 placeholders are not normally considered dependent. */
28148 if (TREE_CODE (expression) == TEMPLATE_PARM_INDEX
28149 && is_auto (TREE_TYPE (expression)))
28150 return true;
28152 gcc_assert (TREE_CODE (expression) != TYPE_DECL);
28154 /* Dependent type attributes might not have made it from the decl to
28155 the type yet. */
28156 if (DECL_P (expression)
28157 && any_dependent_type_attributes_p (DECL_ATTRIBUTES (expression)))
28158 return true;
28160 return (dependent_type_p (TREE_TYPE (expression)));
28163 /* [temp.dep.expr]/5: A class member access expression (5.2.5) is
28164 type-dependent if the expression refers to a member of the current
28165 instantiation and the type of the referenced member is dependent, or the
28166 class member access expression refers to a member of an unknown
28167 specialization.
28169 This function returns true if the OBJECT in such a class member access
28170 expression is of an unknown specialization. */
28172 bool
28173 type_dependent_object_expression_p (tree object)
28175 /* An IDENTIFIER_NODE can sometimes have a TREE_TYPE, but it's still
28176 dependent. */
28177 if (TREE_CODE (object) == IDENTIFIER_NODE)
28178 return true;
28179 tree scope = TREE_TYPE (object);
28180 return (!scope || dependent_scope_p (scope));
28183 /* walk_tree callback function for instantiation_dependent_expression_p,
28184 below. Returns non-zero if a dependent subexpression is found. */
28186 static tree
28187 instantiation_dependent_r (tree *tp, int *walk_subtrees,
28188 void * /*data*/)
28190 if (TYPE_P (*tp))
28192 /* We don't have to worry about decltype currently because decltype
28193 of an instantiation-dependent expr is a dependent type. This
28194 might change depending on the resolution of DR 1172. */
28195 *walk_subtrees = false;
28196 return NULL_TREE;
28198 enum tree_code code = TREE_CODE (*tp);
28199 switch (code)
28201 /* Don't treat an argument list as dependent just because it has no
28202 TREE_TYPE. */
28203 case TREE_LIST:
28204 case TREE_VEC:
28205 case NONTYPE_ARGUMENT_PACK:
28206 return NULL_TREE;
28208 case TEMPLATE_PARM_INDEX:
28209 if (dependent_type_p (TREE_TYPE (*tp)))
28210 return *tp;
28211 if (TEMPLATE_PARM_PARAMETER_PACK (*tp))
28212 return *tp;
28213 /* We'll check value-dependence separately. */
28214 return NULL_TREE;
28216 /* Handle expressions with type operands. */
28217 case SIZEOF_EXPR:
28218 case ALIGNOF_EXPR:
28219 case TYPEID_EXPR:
28220 case AT_ENCODE_EXPR:
28222 tree op = TREE_OPERAND (*tp, 0);
28223 if (code == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (*tp))
28224 op = TREE_TYPE (op);
28225 if (TYPE_P (op))
28227 if (dependent_type_p (op))
28228 return *tp;
28229 else
28231 *walk_subtrees = false;
28232 return NULL_TREE;
28235 break;
28238 case COMPONENT_REF:
28239 if (identifier_p (TREE_OPERAND (*tp, 1)))
28240 /* In a template, finish_class_member_access_expr creates a
28241 COMPONENT_REF with an IDENTIFIER_NODE for op1 even if it isn't
28242 type-dependent, so that we can check access control at
28243 instantiation time (PR 42277). See also Core issue 1273. */
28244 return *tp;
28245 break;
28247 case SCOPE_REF:
28248 if (instantiation_dependent_scope_ref_p (*tp))
28249 return *tp;
28250 else
28251 break;
28253 /* Treat statement-expressions as dependent. */
28254 case BIND_EXPR:
28255 return *tp;
28257 /* Treat requires-expressions as dependent. */
28258 case REQUIRES_EXPR:
28259 return *tp;
28261 case CONSTRUCTOR:
28262 if (CONSTRUCTOR_IS_DEPENDENT (*tp))
28263 return *tp;
28264 break;
28266 case TEMPLATE_DECL:
28267 case FUNCTION_DECL:
28268 /* Before C++17, a noexcept-specifier isn't part of the function type
28269 so it doesn't affect type dependence, but we still want to consider it
28270 for instantiation dependence. */
28271 if (cxx_dialect < cxx17
28272 && DECL_DECLARES_FUNCTION_P (*tp)
28273 && value_dependent_noexcept_spec_p (TREE_TYPE (*tp)))
28274 return *tp;
28275 break;
28277 default:
28278 break;
28281 if (type_dependent_expression_p (*tp))
28282 return *tp;
28283 else
28284 return NULL_TREE;
28287 /* Returns TRUE if the EXPRESSION is instantiation-dependent, in the
28288 sense defined by the ABI:
28290 "An expression is instantiation-dependent if it is type-dependent
28291 or value-dependent, or it has a subexpression that is type-dependent
28292 or value-dependent."
28294 Except don't actually check value-dependence for unevaluated expressions,
28295 because in sizeof(i) we don't care about the value of i. Checking
28296 type-dependence will in turn check value-dependence of array bounds/template
28297 arguments as needed. */
28299 bool
28300 instantiation_dependent_uneval_expression_p (tree expression)
28302 tree result;
28304 if (!processing_template_decl)
28305 return false;
28307 if (expression == error_mark_node)
28308 return false;
28310 result = cp_walk_tree_without_duplicates (&expression,
28311 instantiation_dependent_r, NULL);
28312 return result != NULL_TREE;
28315 /* As above, but also check value-dependence of the expression as a whole. */
28317 bool
28318 instantiation_dependent_expression_p (tree expression)
28320 return (instantiation_dependent_uneval_expression_p (expression)
28321 || (processing_template_decl
28322 && potential_constant_expression (expression)
28323 && value_dependent_expression_p (expression)));
28326 /* Like type_dependent_expression_p, but it also works while not processing
28327 a template definition, i.e. during substitution or mangling. */
28329 bool
28330 type_dependent_expression_p_push (tree expr)
28332 bool b;
28333 ++processing_template_decl;
28334 b = type_dependent_expression_p (expr);
28335 --processing_template_decl;
28336 return b;
28339 /* Returns TRUE if ARGS contains a type-dependent expression. */
28341 bool
28342 any_type_dependent_arguments_p (const vec<tree, va_gc> *args)
28344 unsigned int i;
28345 tree arg;
28347 FOR_EACH_VEC_SAFE_ELT (args, i, arg)
28349 if (type_dependent_expression_p (arg))
28350 return true;
28352 return false;
28355 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
28356 expressions) contains any type-dependent expressions. */
28358 bool
28359 any_type_dependent_elements_p (const_tree list)
28361 for (; list; list = TREE_CHAIN (list))
28362 if (type_dependent_expression_p (TREE_VALUE (list)))
28363 return true;
28365 return false;
28368 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
28369 expressions) contains any value-dependent expressions. */
28371 bool
28372 any_value_dependent_elements_p (const_tree list)
28374 for (; list; list = TREE_CHAIN (list))
28375 if (value_dependent_expression_p (TREE_VALUE (list)))
28376 return true;
28378 return false;
28381 /* Returns TRUE if the ARG (a template argument) is dependent. */
28383 bool
28384 dependent_template_arg_p (tree arg)
28386 if (!processing_template_decl)
28387 return false;
28389 /* Assume a template argument that was wrongly written by the user
28390 is dependent. This is consistent with what
28391 any_dependent_template_arguments_p [that calls this function]
28392 does. */
28393 if (!arg || arg == error_mark_node)
28394 return true;
28396 if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
28397 arg = argument_pack_select_arg (arg);
28399 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
28400 return true;
28401 if (TREE_CODE (arg) == TEMPLATE_DECL)
28403 if (DECL_TEMPLATE_PARM_P (arg))
28404 return true;
28405 /* A member template of a dependent class is not necessarily
28406 type-dependent, but it is a dependent template argument because it
28407 will be a member of an unknown specialization to that template. */
28408 tree scope = CP_DECL_CONTEXT (arg);
28409 return TYPE_P (scope) && dependent_type_p (scope);
28411 else if (ARGUMENT_PACK_P (arg))
28413 tree args = ARGUMENT_PACK_ARGS (arg);
28414 for (tree arg : tree_vec_range (args))
28415 if (dependent_template_arg_p (arg))
28416 return true;
28417 return false;
28419 else if (TYPE_P (arg))
28420 return dependent_type_p (arg);
28421 else
28422 return value_dependent_expression_p (arg);
28425 /* Identify any expressions that use function parms. */
28427 static tree
28428 find_parm_usage_r (tree *tp, int *walk_subtrees, void*)
28430 tree t = *tp;
28431 if (TREE_CODE (t) == PARM_DECL)
28433 *walk_subtrees = 0;
28434 return t;
28436 return NULL_TREE;
28439 /* Returns true if a type specialization formed using the template
28440 arguments ARGS needs to use structural equality. */
28442 bool
28443 any_template_arguments_need_structural_equality_p (tree args)
28445 int i;
28446 int j;
28448 if (!args)
28449 return false;
28450 if (args == error_mark_node)
28451 return true;
28453 for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
28455 tree level = TMPL_ARGS_LEVEL (args, i + 1);
28456 for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
28458 tree arg = TREE_VEC_ELT (level, j);
28459 tree packed_args = NULL_TREE;
28460 int k, len = 1;
28462 if (ARGUMENT_PACK_P (arg))
28464 /* Look inside the argument pack. */
28465 packed_args = ARGUMENT_PACK_ARGS (arg);
28466 len = TREE_VEC_LENGTH (packed_args);
28469 for (k = 0; k < len; ++k)
28471 if (packed_args)
28472 arg = TREE_VEC_ELT (packed_args, k);
28474 if (error_operand_p (arg))
28475 return true;
28476 else if (TREE_CODE (arg) == TEMPLATE_DECL)
28477 continue;
28478 else if (arg == any_targ_node)
28479 /* An any_targ_node argument (added by add_defaults_to_ttp)
28480 makes the corresponding specialization not canonicalizable,
28481 since template_args_equal always return true for it. We
28482 may see this when called from bind_template_template_parm. */
28483 return true;
28484 /* Checking current_function_decl because this structural
28485 comparison is only necessary for redeclaration. */
28486 else if (!current_function_decl
28487 && dependent_template_arg_p (arg)
28488 && (cp_walk_tree_without_duplicates
28489 (&arg, find_parm_usage_r, NULL)))
28490 /* The identity of a class template specialization that uses
28491 a function parameter depends on the identity of the function.
28492 And if this specialization appeared in the trailing return
28493 type thereof, we don't know the identity of the function
28494 (e.g. if it's a redeclaration or a new function) until we
28495 form its signature and go through duplicate_decls. Thus
28496 it's unsafe to decide on a canonical type now (which depends
28497 on the DECL_CONTEXT of the function parameter, which can get
28498 mutated after the fact by duplicate_decls), so just require
28499 structural equality in this case (PR52830). */
28500 return true;
28505 return false;
28508 /* Returns true if ARGS (a collection of template arguments) contains
28509 any dependent arguments. */
28511 bool
28512 any_dependent_template_arguments_p (const_tree args)
28514 int i;
28515 int j;
28517 if (!args)
28518 return false;
28519 if (args == error_mark_node)
28520 return true;
28522 for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
28524 const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
28525 for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
28526 if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
28527 return true;
28530 return false;
28533 /* Returns true if ARGS contains any errors. */
28535 bool
28536 any_erroneous_template_args_p (const_tree args)
28538 int i;
28539 int j;
28541 if (args == error_mark_node)
28542 return true;
28544 if (args && TREE_CODE (args) != TREE_VEC)
28546 if (tree ti = get_template_info (args))
28547 args = TI_ARGS (ti);
28548 else
28549 args = NULL_TREE;
28552 if (!args)
28553 return false;
28555 for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
28557 const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
28558 for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
28559 if (error_operand_p (TREE_VEC_ELT (level, j)))
28560 return true;
28563 return false;
28566 /* Returns TRUE if the template TMPL is type-dependent. */
28568 bool
28569 dependent_template_p (tree tmpl)
28571 if (TREE_CODE (tmpl) == OVERLOAD)
28573 for (lkp_iterator iter (tmpl); iter; ++iter)
28574 if (dependent_template_p (*iter))
28575 return true;
28576 return false;
28579 /* Template template parameters are dependent. */
28580 if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
28581 || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
28582 return true;
28583 /* So are names that have not been looked up. */
28584 if (TREE_CODE (tmpl) == SCOPE_REF || identifier_p (tmpl))
28585 return true;
28586 return false;
28589 /* Returns TRUE if the specialization TMPL<ARGS> is dependent. */
28591 bool
28592 dependent_template_id_p (tree tmpl, tree args)
28594 return (dependent_template_p (tmpl)
28595 || any_dependent_template_arguments_p (args));
28598 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
28599 are dependent. */
28601 bool
28602 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
28604 int i;
28606 if (!processing_template_decl)
28607 return false;
28609 for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
28611 tree decl = TREE_VEC_ELT (declv, i);
28612 tree init = TREE_VEC_ELT (initv, i);
28613 tree cond = TREE_VEC_ELT (condv, i);
28614 tree incr = TREE_VEC_ELT (incrv, i);
28616 if (type_dependent_expression_p (decl)
28617 || TREE_CODE (decl) == SCOPE_REF)
28618 return true;
28620 if (init && type_dependent_expression_p (init))
28621 return true;
28623 if (cond == global_namespace)
28624 return true;
28626 if (type_dependent_expression_p (cond))
28627 return true;
28629 if (COMPARISON_CLASS_P (cond)
28630 && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
28631 || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
28632 return true;
28634 if (TREE_CODE (incr) == MODOP_EXPR)
28636 if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
28637 || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
28638 return true;
28640 else if (type_dependent_expression_p (incr))
28641 return true;
28642 else if (TREE_CODE (incr) == MODIFY_EXPR)
28644 if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
28645 return true;
28646 else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
28648 tree t = TREE_OPERAND (incr, 1);
28649 if (type_dependent_expression_p (TREE_OPERAND (t, 0))
28650 || type_dependent_expression_p (TREE_OPERAND (t, 1)))
28651 return true;
28653 /* If this loop has a class iterator with != comparison
28654 with increment other than i++/++i/i--/--i, make sure the
28655 increment is constant. */
28656 if (CLASS_TYPE_P (TREE_TYPE (decl))
28657 && TREE_CODE (cond) == NE_EXPR)
28659 if (TREE_OPERAND (t, 0) == decl)
28660 t = TREE_OPERAND (t, 1);
28661 else
28662 t = TREE_OPERAND (t, 0);
28663 if (TREE_CODE (t) != INTEGER_CST)
28664 return true;
28670 return false;
28673 /* TYPE is a TYPENAME_TYPE. Returns the ordinary TYPE to which the
28674 TYPENAME_TYPE corresponds. Returns the original TYPENAME_TYPE if
28675 no such TYPE can be found. Note that this function peers inside
28676 uninstantiated templates and therefore should be used only in
28677 extremely limited situations. ONLY_CURRENT_P restricts this
28678 peering to the currently open classes hierarchy (which is required
28679 when comparing types). */
28681 tree
28682 resolve_typename_type (tree type, bool only_current_p)
28684 tree scope;
28685 tree name;
28686 tree decl;
28687 int quals;
28688 tree pushed_scope;
28689 tree result;
28691 gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
28693 scope = TYPE_CONTEXT (type);
28694 /* We shouldn't have built a TYPENAME_TYPE with a non-dependent scope. */
28695 gcc_checking_assert (uses_template_parms (scope));
28697 /* Usually the non-qualified identifier of a TYPENAME_TYPE is
28698 TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of a
28699 TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL
28700 representing the typedef. In that case TYPE_IDENTIFIER (type) is
28701 not the non-qualified identifier of the TYPENAME_TYPE anymore.
28702 So by getting the TYPE_IDENTIFIER of the _main declaration_ of
28703 the TYPENAME_TYPE instead, we avoid messing up with a possible
28704 typedef variant case. */
28705 name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
28707 /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
28708 it first before we can figure out what NAME refers to. */
28709 if (TREE_CODE (scope) == TYPENAME_TYPE)
28711 if (TYPENAME_IS_RESOLVING_P (scope))
28712 /* Given a class template A with a dependent base with nested type C,
28713 typedef typename A::C::C C will land us here, as trying to resolve
28714 the initial A::C leads to the local C typedef, which leads back to
28715 A::C::C. So we break the recursion now. */
28716 return type;
28717 else
28718 scope = resolve_typename_type (scope, only_current_p);
28720 /* If we don't know what SCOPE refers to, then we cannot resolve the
28721 TYPENAME_TYPE. */
28722 if (!CLASS_TYPE_P (scope))
28723 return type;
28724 /* If this is a typedef, we don't want to look inside (c++/11987). */
28725 if (typedef_variant_p (type))
28726 return type;
28727 /* If SCOPE isn't the template itself, it will not have a valid
28728 TYPE_FIELDS list. */
28729 if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
28730 /* scope is either the template itself or a compatible instantiation
28731 like X<T>, so look up the name in the original template. */
28732 scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
28733 /* If scope has no fields, it can't be a current instantiation. Check this
28734 before currently_open_class to avoid infinite recursion (71515). */
28735 if (!TYPE_FIELDS (scope))
28736 return type;
28737 /* If the SCOPE is not the current instantiation, there's no reason
28738 to look inside it. */
28739 if (only_current_p && !currently_open_class (scope))
28740 return type;
28741 /* Enter the SCOPE so that name lookup will be resolved as if we
28742 were in the class definition. In particular, SCOPE will no
28743 longer be considered a dependent type. */
28744 pushed_scope = push_scope (scope);
28745 /* Look up the declaration. */
28746 decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true,
28747 tf_warning_or_error);
28749 result = NULL_TREE;
28751 /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
28752 find a TEMPLATE_DECL. Otherwise, we want to find a TYPE_DECL. */
28753 tree fullname = TYPENAME_TYPE_FULLNAME (type);
28754 if (!decl)
28755 /*nop*/;
28756 else if (identifier_p (fullname)
28757 && TREE_CODE (decl) == TYPE_DECL)
28759 result = TREE_TYPE (decl);
28760 if (result == error_mark_node)
28761 result = NULL_TREE;
28763 else if (TREE_CODE (fullname) == TEMPLATE_ID_EXPR
28764 && DECL_CLASS_TEMPLATE_P (decl))
28766 /* Obtain the template and the arguments. */
28767 tree tmpl = TREE_OPERAND (fullname, 0);
28768 if (TREE_CODE (tmpl) == IDENTIFIER_NODE)
28770 /* We get here with a plain identifier because a previous tentative
28771 parse of the nested-name-specifier as part of a ptr-operator saw
28772 ::template X<A>. The use of ::template is necessary in a
28773 ptr-operator, but wrong in a declarator-id.
28775 [temp.names]: In a qualified-id of a declarator-id, the keyword
28776 template shall not appear at the top level. */
28777 pedwarn (cp_expr_loc_or_input_loc (fullname), OPT_Wpedantic,
28778 "keyword %<template%> not allowed in declarator-id");
28779 tmpl = decl;
28781 tree args = TREE_OPERAND (fullname, 1);
28782 /* Instantiate the template. */
28783 result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
28784 /*entering_scope=*/true,
28785 tf_error | tf_user);
28786 if (result == error_mark_node)
28787 result = NULL_TREE;
28790 /* Leave the SCOPE. */
28791 if (pushed_scope)
28792 pop_scope (pushed_scope);
28794 /* If we failed to resolve it, return the original typename. */
28795 if (!result)
28796 return type;
28798 /* If lookup found a typename type, resolve that too. */
28799 if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
28801 /* Ill-formed programs can cause infinite recursion here, so we
28802 must catch that. */
28803 TYPENAME_IS_RESOLVING_P (result) = 1;
28804 result = resolve_typename_type (result, only_current_p);
28805 TYPENAME_IS_RESOLVING_P (result) = 0;
28808 /* Qualify the resulting type. */
28809 quals = cp_type_quals (type);
28810 if (quals)
28811 result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
28813 return result;
28816 /* EXPR is an expression which is not type-dependent. Return a proxy
28817 for EXPR that can be used to compute the types of larger
28818 expressions containing EXPR. */
28820 tree
28821 build_non_dependent_expr (tree expr)
28823 tree orig_expr = expr;
28824 tree inner_expr;
28826 /* When checking, try to get a constant value for all non-dependent
28827 expressions in order to expose bugs in *_dependent_expression_p
28828 and constexpr. This can affect code generation, see PR70704, so
28829 only do this for -fchecking=2. */
28830 if (flag_checking > 1
28831 && cxx_dialect >= cxx11
28832 /* Don't do this during nsdmi parsing as it can lead to
28833 unexpected recursive instantiations. */
28834 && !parsing_nsdmi ()
28835 /* Don't do this during concept processing either and for
28836 the same reason. */
28837 && !processing_constraint_expression_p ())
28838 fold_non_dependent_expr (expr, tf_none);
28840 STRIP_ANY_LOCATION_WRAPPER (expr);
28842 /* Preserve OVERLOADs; the functions must be available to resolve
28843 types. */
28844 inner_expr = expr;
28845 if (TREE_CODE (inner_expr) == STMT_EXPR)
28846 inner_expr = stmt_expr_value_expr (inner_expr);
28847 if (TREE_CODE (inner_expr) == ADDR_EXPR)
28848 inner_expr = TREE_OPERAND (inner_expr, 0);
28849 if (TREE_CODE (inner_expr) == COMPONENT_REF)
28850 inner_expr = TREE_OPERAND (inner_expr, 1);
28851 if (is_overloaded_fn (inner_expr)
28852 || TREE_CODE (inner_expr) == OFFSET_REF)
28853 return orig_expr;
28854 /* There is no need to return a proxy for a variable, parameter
28855 or enumerator. */
28856 if (VAR_P (expr) || TREE_CODE (expr) == PARM_DECL
28857 || TREE_CODE (expr) == CONST_DECL)
28858 return orig_expr;
28859 /* Preserve string constants; conversions from string constants to
28860 "char *" are allowed, even though normally a "const char *"
28861 cannot be used to initialize a "char *". */
28862 if (TREE_CODE (expr) == STRING_CST)
28863 return orig_expr;
28864 /* Preserve void and arithmetic constants, as an optimization -- there is no
28865 reason to create a new node. */
28866 if (TREE_CODE (expr) == VOID_CST
28867 || TREE_CODE (expr) == INTEGER_CST
28868 || TREE_CODE (expr) == REAL_CST)
28869 return orig_expr;
28870 /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
28871 There is at least one place where we want to know that a
28872 particular expression is a throw-expression: when checking a ?:
28873 expression, there are special rules if the second or third
28874 argument is a throw-expression. */
28875 if (TREE_CODE (expr) == THROW_EXPR)
28876 return orig_expr;
28878 /* Don't wrap an initializer list, we need to be able to look inside. */
28879 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
28880 return orig_expr;
28882 /* Don't wrap a dummy object, we need to be able to test for it. */
28883 if (is_dummy_object (expr))
28884 return orig_expr;
28886 if (TREE_CODE (expr) == COND_EXPR)
28887 return build3 (COND_EXPR,
28888 TREE_TYPE (expr),
28889 build_non_dependent_expr (TREE_OPERAND (expr, 0)),
28890 (TREE_OPERAND (expr, 1)
28891 ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
28892 : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
28893 build_non_dependent_expr (TREE_OPERAND (expr, 2)));
28894 if (TREE_CODE (expr) == COMPOUND_EXPR)
28895 return build2 (COMPOUND_EXPR,
28896 TREE_TYPE (expr),
28897 TREE_OPERAND (expr, 0),
28898 build_non_dependent_expr (TREE_OPERAND (expr, 1)));
28900 /* If the type is unknown, it can't really be non-dependent */
28901 gcc_assert (TREE_TYPE (expr) != unknown_type_node);
28903 /* Otherwise, build a NON_DEPENDENT_EXPR. */
28904 return build1_loc (EXPR_LOCATION (orig_expr), NON_DEPENDENT_EXPR,
28905 TREE_TYPE (expr), expr);
28908 /* ARGS is a vector of expressions as arguments to a function call.
28909 Replace the arguments with equivalent non-dependent expressions.
28910 This modifies ARGS in place. */
28912 void
28913 make_args_non_dependent (vec<tree, va_gc> *args)
28915 unsigned int ix;
28916 tree arg;
28918 FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
28920 tree newarg = build_non_dependent_expr (arg);
28921 if (newarg != arg)
28922 (*args)[ix] = newarg;
28926 /* Returns a type which represents 'auto' or 'decltype(auto)'. We use a
28927 TEMPLATE_TYPE_PARM with a level one deeper than the actual template parms,
28928 by default. If set_canonical is true, we set TYPE_CANONICAL on it. */
28930 static tree
28931 make_auto_1 (tree name, bool set_canonical, int level = -1)
28933 if (level == -1)
28934 level = current_template_depth + 1;
28935 tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
28936 TYPE_NAME (au) = build_decl (input_location, TYPE_DECL, name, au);
28937 TYPE_STUB_DECL (au) = TYPE_NAME (au);
28938 TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
28939 (0, level, level, TYPE_NAME (au), NULL_TREE);
28940 if (set_canonical)
28941 TYPE_CANONICAL (au) = canonical_type_parameter (au);
28942 DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
28943 SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
28944 if (name == decltype_auto_identifier)
28945 AUTO_IS_DECLTYPE (au) = true;
28947 return au;
28950 tree
28951 make_decltype_auto (void)
28953 return make_auto_1 (decltype_auto_identifier, true);
28956 tree
28957 make_auto (void)
28959 return make_auto_1 (auto_identifier, true);
28962 /* Return a C++17 deduction placeholder for class template TMPL.
28963 There are represented as an 'auto' with the special level 0 and
28964 CLASS_PLACEHOLDER_TEMPLATE set. */
28966 tree
28967 make_template_placeholder (tree tmpl)
28969 tree t = make_auto_1 (auto_identifier, false, /*level=*/0);
28970 CLASS_PLACEHOLDER_TEMPLATE (t) = tmpl;
28971 /* Our canonical type depends on the placeholder. */
28972 TYPE_CANONICAL (t) = canonical_type_parameter (t);
28973 return t;
28976 /* True iff T is a C++17 class template deduction placeholder. */
28978 bool
28979 template_placeholder_p (tree t)
28981 return is_auto (t) && CLASS_PLACEHOLDER_TEMPLATE (t);
28984 /* Make a "constrained auto" type-specifier. This is an auto or
28985 decltype(auto) type with constraints that must be associated after
28986 deduction. The constraint is formed from the given concept CON
28987 and its optional sequence of template arguments ARGS.
28989 TYPE must be the result of make_auto_type or make_decltype_auto_type. */
28991 static tree
28992 make_constrained_placeholder_type (tree type, tree con, tree args)
28994 /* Build the constraint. */
28995 tree tmpl = DECL_TI_TEMPLATE (con);
28996 tree expr = tmpl;
28997 if (TREE_CODE (con) == FUNCTION_DECL)
28998 expr = ovl_make (tmpl);
28999 ++processing_template_decl;
29000 expr = build_concept_check (expr, type, args, tf_warning_or_error);
29001 --processing_template_decl;
29003 PLACEHOLDER_TYPE_CONSTRAINTS_INFO (type)
29004 = build_tree_list (current_template_parms, expr);
29006 /* Our canonical type depends on the constraint. */
29007 TYPE_CANONICAL (type) = canonical_type_parameter (type);
29009 /* Attach the constraint to the type declaration. */
29010 return TYPE_NAME (type);
29013 /* Make a "constrained auto" type-specifier. */
29015 tree
29016 make_constrained_auto (tree con, tree args)
29018 tree type = make_auto_1 (auto_identifier, false);
29019 return make_constrained_placeholder_type (type, con, args);
29022 /* Make a "constrained decltype(auto)" type-specifier. */
29024 tree
29025 make_constrained_decltype_auto (tree con, tree args)
29027 tree type = make_auto_1 (decltype_auto_identifier, false);
29028 return make_constrained_placeholder_type (type, con, args);
29031 /* Returns true if the placeholder type constraint T has any dependent
29032 (explicit) template arguments. */
29034 static bool
29035 placeholder_type_constraint_dependent_p (tree t)
29037 tree id = unpack_concept_check (t);
29038 tree args = TREE_OPERAND (id, 1);
29039 tree first = TREE_VEC_ELT (args, 0);
29040 if (ARGUMENT_PACK_P (first))
29042 args = expand_template_argument_pack (args);
29043 first = TREE_VEC_ELT (args, 0);
29045 gcc_checking_assert (TREE_CODE (first) == WILDCARD_DECL
29046 || is_auto (first));
29047 for (int i = 1; i < TREE_VEC_LENGTH (args); ++i)
29048 if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
29049 return true;
29050 return false;
29053 /* Build and return a concept definition. Like other templates, the
29054 CONCEPT_DECL node is wrapped by a TEMPLATE_DECL. This returns the
29055 the TEMPLATE_DECL. */
29057 tree
29058 finish_concept_definition (cp_expr id, tree init, tree attrs)
29060 gcc_assert (identifier_p (id));
29061 gcc_assert (processing_template_decl);
29063 location_t loc = id.get_location();
29065 /* A concept-definition shall not have associated constraints. */
29066 if (TEMPLATE_PARMS_CONSTRAINTS (current_template_parms))
29068 error_at (loc, "a concept cannot be constrained");
29069 TEMPLATE_PARMS_CONSTRAINTS (current_template_parms) = NULL_TREE;
29072 /* A concept-definition shall appear in namespace scope. Templates
29073 aren't allowed in block scope, so we only need to check for class
29074 scope. */
29075 if (TYPE_P (current_scope()) || !DECL_NAMESPACE_SCOPE_P (current_scope ()))
29077 error_at (loc, "concept %qE not in namespace scope", *id);
29078 return error_mark_node;
29081 if (current_template_depth > 1)
29083 error_at (loc, "concept %qE has multiple template parameter lists", *id);
29084 return error_mark_node;
29087 /* Initially build the concept declaration; its type is bool. */
29088 tree decl = build_lang_decl_loc (loc, CONCEPT_DECL, *id, boolean_type_node);
29089 DECL_CONTEXT (decl) = current_scope ();
29090 DECL_INITIAL (decl) = init;
29092 if (attrs)
29093 cplus_decl_attributes (&decl, attrs, 0);
29095 set_originating_module (decl, false);
29097 /* Push the enclosing template. */
29098 return push_template_decl (decl);
29101 /* Given type ARG, return std::initializer_list<ARG>. */
29103 static tree
29104 listify (tree arg)
29106 tree std_init_list = lookup_qualified_name (std_node, init_list_identifier);
29108 if (std_init_list == error_mark_node
29109 || !DECL_CLASS_TEMPLATE_P (std_init_list))
29111 gcc_rich_location richloc (input_location);
29112 maybe_add_include_fixit (&richloc, "<initializer_list>", false);
29113 error_at (&richloc,
29114 "deducing from brace-enclosed initializer list"
29115 " requires %<#include <initializer_list>%>");
29117 return error_mark_node;
29119 tree argvec = make_tree_vec (1);
29120 TREE_VEC_ELT (argvec, 0) = arg;
29122 return lookup_template_class (std_init_list, argvec, NULL_TREE,
29123 NULL_TREE, 0, tf_warning_or_error);
29126 /* Replace auto in TYPE with std::initializer_list<auto>. */
29128 static tree
29129 listify_autos (tree type, tree auto_node)
29131 tree init_auto = listify (strip_top_quals (auto_node));
29132 tree argvec = make_tree_vec (1);
29133 TREE_VEC_ELT (argvec, 0) = init_auto;
29134 if (processing_template_decl)
29135 argvec = add_to_template_args (current_template_args (), argvec);
29136 return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
29139 /* Hash traits for hashing possibly constrained 'auto'
29140 TEMPLATE_TYPE_PARMs for use by do_auto_deduction. */
29142 struct auto_hash : default_hash_traits<tree>
29144 static inline hashval_t hash (tree);
29145 static inline bool equal (tree, tree);
29148 /* Hash the 'auto' T. */
29150 inline hashval_t
29151 auto_hash::hash (tree t)
29153 if (tree c = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (t)))
29154 /* Matching constrained-type-specifiers denote the same template
29155 parameter, so hash the constraint. */
29156 return hash_placeholder_constraint (c);
29157 else
29158 /* But unconstrained autos are all separate, so just hash the pointer. */
29159 return iterative_hash_object (t, 0);
29162 /* Compare two 'auto's. */
29164 inline bool
29165 auto_hash::equal (tree t1, tree t2)
29167 if (t1 == t2)
29168 return true;
29170 tree c1 = PLACEHOLDER_TYPE_CONSTRAINTS (t1);
29171 tree c2 = PLACEHOLDER_TYPE_CONSTRAINTS (t2);
29173 /* Two unconstrained autos are distinct. */
29174 if (!c1 || !c2)
29175 return false;
29177 return equivalent_placeholder_constraints (c1, c2);
29180 /* for_each_template_parm callback for extract_autos: if t is a (possibly
29181 constrained) auto, add it to the vector. */
29183 static int
29184 extract_autos_r (tree t, void *data)
29186 hash_table<auto_hash> &hash = *(hash_table<auto_hash>*)data;
29187 if (is_auto (t) && !template_placeholder_p (t))
29189 /* All the autos were built with index 0; fix that up now. */
29190 tree *p = hash.find_slot (t, INSERT);
29191 unsigned idx;
29192 if (*p)
29193 /* If this is a repeated constrained-type-specifier, use the index we
29194 chose before. */
29195 idx = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (*p));
29196 else
29198 /* Otherwise this is new, so use the current count. */
29199 *p = t;
29200 idx = hash.elements () - 1;
29202 TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (t)) = idx;
29205 /* Always keep walking. */
29206 return 0;
29209 /* Return a TREE_VEC of the 'auto's used in type under the Concepts TS, which
29210 says they can appear anywhere in the type. */
29212 static tree
29213 extract_autos (tree type)
29215 hash_set<tree> visited;
29216 hash_table<auto_hash> hash (2);
29218 for_each_template_parm (type, extract_autos_r, &hash, &visited, true);
29220 tree tree_vec = make_tree_vec (hash.elements());
29221 for (tree elt : hash)
29223 unsigned i = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (elt));
29224 TREE_VEC_ELT (tree_vec, i)
29225 = build_tree_list (NULL_TREE, TYPE_NAME (elt));
29228 return tree_vec;
29231 /* The stem for deduction guide names. */
29232 const char *const dguide_base = "__dguide_";
29234 /* Return the name for a deduction guide for class template TMPL. */
29236 tree
29237 dguide_name (tree tmpl)
29239 tree type = (TYPE_P (tmpl) ? tmpl : TREE_TYPE (tmpl));
29240 tree tname = TYPE_IDENTIFIER (type);
29241 char *buf = (char *) alloca (1 + strlen (dguide_base)
29242 + IDENTIFIER_LENGTH (tname));
29243 memcpy (buf, dguide_base, strlen (dguide_base));
29244 memcpy (buf + strlen (dguide_base), IDENTIFIER_POINTER (tname),
29245 IDENTIFIER_LENGTH (tname) + 1);
29246 tree dname = get_identifier (buf);
29247 TREE_TYPE (dname) = type;
29248 return dname;
29251 /* True if NAME is the name of a deduction guide. */
29253 bool
29254 dguide_name_p (tree name)
29256 return (TREE_CODE (name) == IDENTIFIER_NODE
29257 && TREE_TYPE (name)
29258 && startswith (IDENTIFIER_POINTER (name), dguide_base));
29261 /* True if FN is a deduction guide. */
29263 bool
29264 deduction_guide_p (const_tree fn)
29266 if (DECL_P (fn))
29267 if (tree name = DECL_NAME (fn))
29268 return dguide_name_p (name);
29269 return false;
29272 /* True if FN is the copy deduction guide, i.e. A(A)->A. */
29274 bool
29275 copy_guide_p (const_tree fn)
29277 gcc_assert (deduction_guide_p (fn));
29278 if (!DECL_ARTIFICIAL (fn))
29279 return false;
29280 tree parms = FUNCTION_FIRST_USER_PARMTYPE (DECL_TI_TEMPLATE (fn));
29281 return (TREE_CHAIN (parms) == void_list_node
29282 && same_type_p (TREE_VALUE (parms), TREE_TYPE (DECL_NAME (fn))));
29285 /* True if FN is a guide generated from a constructor template. */
29287 bool
29288 template_guide_p (const_tree fn)
29290 gcc_assert (deduction_guide_p (fn));
29291 if (!DECL_ARTIFICIAL (fn))
29292 return false;
29293 tree tmpl = DECL_TI_TEMPLATE (fn);
29294 if (tree org = DECL_ABSTRACT_ORIGIN (tmpl))
29295 return PRIMARY_TEMPLATE_P (org);
29296 return false;
29299 /* True if FN is an aggregate initialization guide or the copy deduction
29300 guide. */
29302 bool
29303 builtin_guide_p (const_tree fn)
29305 if (!deduction_guide_p (fn))
29306 return false;
29307 if (!DECL_ARTIFICIAL (fn))
29308 /* Explicitly declared. */
29309 return false;
29310 if (DECL_ABSTRACT_ORIGIN (fn))
29311 /* Derived from a constructor. */
29312 return false;
29313 return true;
29316 /* OLDDECL is a _DECL for a template parameter. Return a similar parameter at
29317 LEVEL:INDEX, using tsubst_args and complain for substitution into non-type
29318 template parameter types. Note that the handling of template template
29319 parameters relies on current_template_parms being set appropriately for the
29320 new template. */
29322 static tree
29323 rewrite_template_parm (tree olddecl, unsigned index, unsigned level,
29324 tree tsubst_args, tsubst_flags_t complain)
29326 if (olddecl == error_mark_node)
29327 return error_mark_node;
29329 tree oldidx = get_template_parm_index (olddecl);
29331 tree newtype;
29332 if (TREE_CODE (olddecl) == TYPE_DECL
29333 || TREE_CODE (olddecl) == TEMPLATE_DECL)
29335 tree oldtype = TREE_TYPE (olddecl);
29336 newtype = cxx_make_type (TREE_CODE (oldtype));
29337 TYPE_MAIN_VARIANT (newtype) = newtype;
29339 else
29341 newtype = TREE_TYPE (olddecl);
29342 if (type_uses_auto (newtype))
29344 // Substitute once to fix references to other template parameters.
29345 newtype = tsubst (newtype, tsubst_args,
29346 complain|tf_partial, NULL_TREE);
29347 // Now substitute again to reduce the level of the auto.
29348 newtype = tsubst (newtype, current_template_args (),
29349 complain, NULL_TREE);
29351 else
29352 newtype = tsubst (newtype, tsubst_args,
29353 complain, NULL_TREE);
29356 tree newdecl
29357 = build_decl (DECL_SOURCE_LOCATION (olddecl), TREE_CODE (olddecl),
29358 DECL_NAME (olddecl), newtype);
29359 SET_DECL_TEMPLATE_PARM_P (newdecl);
29361 tree newidx;
29362 if (TREE_CODE (olddecl) == TYPE_DECL
29363 || TREE_CODE (olddecl) == TEMPLATE_DECL)
29365 newidx = TEMPLATE_TYPE_PARM_INDEX (newtype)
29366 = build_template_parm_index (index, level, level,
29367 newdecl, newtype);
29368 TEMPLATE_PARM_PARAMETER_PACK (newidx)
29369 = TEMPLATE_PARM_PARAMETER_PACK (oldidx);
29370 TYPE_STUB_DECL (newtype) = TYPE_NAME (newtype) = newdecl;
29372 if (TREE_CODE (olddecl) == TEMPLATE_DECL)
29374 DECL_TEMPLATE_RESULT (newdecl)
29375 = build_decl (DECL_SOURCE_LOCATION (olddecl), TYPE_DECL,
29376 DECL_NAME (olddecl), newtype);
29377 DECL_ARTIFICIAL (DECL_TEMPLATE_RESULT (newdecl)) = true;
29378 // First create a copy (ttargs) of tsubst_args with an
29379 // additional level for the template template parameter's own
29380 // template parameters (ttparms).
29381 tree ttparms = (INNERMOST_TEMPLATE_PARMS
29382 (DECL_TEMPLATE_PARMS (olddecl)));
29383 const int depth = TMPL_ARGS_DEPTH (tsubst_args);
29384 tree ttargs = make_tree_vec (depth + 1);
29385 for (int i = 0; i < depth; ++i)
29386 TREE_VEC_ELT (ttargs, i) = TMPL_ARGS_LEVEL (tsubst_args, i + 1);
29387 TREE_VEC_ELT (ttargs, depth)
29388 = template_parms_level_to_args (ttparms);
29389 // Substitute ttargs into ttparms to fix references to
29390 // other template parameters.
29391 ttparms = tsubst_template_parms_level (ttparms, ttargs,
29392 complain|tf_partial);
29393 // Now substitute again with args based on tparms, to reduce
29394 // the level of the ttparms.
29395 ttargs = current_template_args ();
29396 ttparms = tsubst_template_parms_level (ttparms, ttargs,
29397 complain);
29398 // Finally, tack the adjusted parms onto tparms.
29399 ttparms = tree_cons (size_int (level + 1), ttparms,
29400 copy_node (current_template_parms));
29401 // As with all template template parms, the parameter list captured
29402 // by this template template parm that corresponds to its own level
29403 // should be empty. This avoids infinite recursion when structurally
29404 // comparing two such rewritten template template parms (PR102479).
29405 gcc_assert (!TREE_VEC_LENGTH
29406 (TREE_VALUE (TREE_CHAIN (DECL_TEMPLATE_PARMS (olddecl)))));
29407 gcc_assert (TMPL_PARMS_DEPTH (TREE_CHAIN (ttparms)) == level);
29408 TREE_VALUE (TREE_CHAIN (ttparms)) = make_tree_vec (0);
29409 // All done.
29410 DECL_TEMPLATE_PARMS (newdecl) = ttparms;
29413 if (TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (olddecl)))
29414 SET_TYPE_STRUCTURAL_EQUALITY (newtype);
29415 else
29416 TYPE_CANONICAL (newtype) = canonical_type_parameter (newtype);
29418 else
29420 tree oldconst = TEMPLATE_PARM_DECL (oldidx);
29421 tree newconst
29422 = build_decl (DECL_SOURCE_LOCATION (oldconst),
29423 TREE_CODE (oldconst),
29424 DECL_NAME (oldconst), newtype);
29425 TREE_CONSTANT (newconst) = TREE_CONSTANT (newdecl)
29426 = TREE_READONLY (newconst) = TREE_READONLY (newdecl) = true;
29427 SET_DECL_TEMPLATE_PARM_P (newconst);
29428 newidx = build_template_parm_index (index, level, level,
29429 newconst, newtype);
29430 TEMPLATE_PARM_PARAMETER_PACK (newidx)
29431 = TEMPLATE_PARM_PARAMETER_PACK (oldidx);
29432 DECL_INITIAL (newdecl) = DECL_INITIAL (newconst) = newidx;
29435 return newdecl;
29438 /* As rewrite_template_parm, but for the whole TREE_LIST representing a
29439 template parameter. */
29441 static tree
29442 rewrite_tparm_list (tree oldelt, unsigned index, unsigned level,
29443 tree targs, unsigned targs_index, tsubst_flags_t complain)
29445 tree olddecl = TREE_VALUE (oldelt);
29446 tree newdecl = rewrite_template_parm (olddecl, index, level,
29447 targs, complain);
29448 if (newdecl == error_mark_node)
29449 return error_mark_node;
29450 tree newdef = tsubst_template_arg (TREE_PURPOSE (oldelt),
29451 targs, complain, NULL_TREE);
29452 tree list = build_tree_list (newdef, newdecl);
29453 TEMPLATE_PARM_CONSTRAINTS (list)
29454 = tsubst_constraint_info (TEMPLATE_PARM_CONSTRAINTS (oldelt),
29455 targs, complain, NULL_TREE);
29456 int depth = TMPL_ARGS_DEPTH (targs);
29457 TMPL_ARG (targs, depth, targs_index) = template_parm_to_arg (list);
29458 return list;
29461 /* Returns a C++17 class deduction guide template based on the constructor
29462 CTOR. As a special case, CTOR can be a RECORD_TYPE for an implicit default
29463 guide, REFERENCE_TYPE for an implicit copy/move guide, or TREE_LIST for an
29464 aggregate initialization guide. OUTER_ARGS are the template arguments
29465 for the enclosing scope of the class. */
29467 static tree
29468 build_deduction_guide (tree type, tree ctor, tree outer_args, tsubst_flags_t complain)
29470 tree tparms, targs, fparms, fargs, ci;
29471 bool memtmpl = false;
29472 bool explicit_p;
29473 location_t loc;
29474 tree fn_tmpl = NULL_TREE;
29476 if (outer_args)
29478 ++processing_template_decl;
29479 type = tsubst (type, outer_args, complain, CLASSTYPE_TI_TEMPLATE (type));
29480 --processing_template_decl;
29483 if (!DECL_DECLARES_FUNCTION_P (ctor))
29485 if (TYPE_P (ctor))
29487 bool copy_p = TYPE_REF_P (ctor);
29488 if (copy_p)
29489 fparms = tree_cons (NULL_TREE, type, void_list_node);
29490 else
29491 fparms = void_list_node;
29493 else if (TREE_CODE (ctor) == TREE_LIST)
29494 fparms = ctor;
29495 else
29496 gcc_unreachable ();
29498 tree ctmpl = CLASSTYPE_TI_TEMPLATE (type);
29499 tparms = DECL_TEMPLATE_PARMS (ctmpl);
29500 targs = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
29501 ci = NULL_TREE;
29502 fargs = NULL_TREE;
29503 loc = DECL_SOURCE_LOCATION (ctmpl);
29504 explicit_p = false;
29506 else
29508 ++processing_template_decl;
29509 bool ok = true;
29511 complain |= tf_dguide;
29513 fn_tmpl
29514 = (TREE_CODE (ctor) == TEMPLATE_DECL ? ctor
29515 : DECL_TI_TEMPLATE (ctor));
29516 if (outer_args)
29517 fn_tmpl = tsubst (fn_tmpl, outer_args, complain, ctor);
29518 ctor = DECL_TEMPLATE_RESULT (fn_tmpl);
29520 tparms = DECL_TEMPLATE_PARMS (fn_tmpl);
29521 /* If type is a member class template, DECL_TI_ARGS (ctor) will have
29522 fully specialized args for the enclosing class. Strip those off, as
29523 the deduction guide won't have those template parameters. */
29524 targs = get_innermost_template_args (DECL_TI_ARGS (ctor),
29525 TMPL_PARMS_DEPTH (tparms));
29526 /* Discard the 'this' parameter. */
29527 fparms = FUNCTION_ARG_CHAIN (ctor);
29528 fargs = TREE_CHAIN (DECL_ARGUMENTS (ctor));
29529 ci = get_constraints (ctor);
29530 loc = DECL_SOURCE_LOCATION (ctor);
29531 explicit_p = DECL_NONCONVERTING_P (ctor);
29533 if (PRIMARY_TEMPLATE_P (fn_tmpl))
29535 memtmpl = true;
29537 /* For a member template constructor, we need to flatten the two
29538 template parameter lists into one, and then adjust the function
29539 signature accordingly. This gets...complicated. */
29540 tree save_parms = current_template_parms;
29542 /* For a member template we should have two levels of parms/args, one
29543 for the class and one for the constructor. We stripped
29544 specialized args for further enclosing classes above. */
29545 const int depth = 2;
29546 gcc_assert (TMPL_ARGS_DEPTH (targs) == depth);
29548 /* Template args for translating references to the two-level template
29549 parameters into references to the one-level template parameters we
29550 are creating. */
29551 tree tsubst_args = copy_node (targs);
29552 TMPL_ARGS_LEVEL (tsubst_args, depth)
29553 = copy_node (TMPL_ARGS_LEVEL (tsubst_args, depth));
29555 /* Template parms for the constructor template. */
29556 tree ftparms = TREE_VALUE (tparms);
29557 unsigned flen = TREE_VEC_LENGTH (ftparms);
29558 /* Template parms for the class template. */
29559 tparms = TREE_CHAIN (tparms);
29560 tree ctparms = TREE_VALUE (tparms);
29561 unsigned clen = TREE_VEC_LENGTH (ctparms);
29562 /* Template parms for the deduction guide start as a copy of the
29563 template parms for the class. We set current_template_parms for
29564 lookup_template_class_1. */
29565 current_template_parms = tparms = copy_node (tparms);
29566 tree new_vec = TREE_VALUE (tparms) = make_tree_vec (flen + clen);
29567 for (unsigned i = 0; i < clen; ++i)
29568 TREE_VEC_ELT (new_vec, i) = TREE_VEC_ELT (ctparms, i);
29570 /* Now we need to rewrite the constructor parms to append them to the
29571 class parms. */
29572 for (unsigned i = 0; i < flen; ++i)
29574 unsigned index = i + clen;
29575 unsigned level = 1;
29576 tree oldelt = TREE_VEC_ELT (ftparms, i);
29577 tree newelt
29578 = rewrite_tparm_list (oldelt, index, level,
29579 tsubst_args, i, complain);
29580 if (newelt == error_mark_node)
29581 ok = false;
29582 TREE_VEC_ELT (new_vec, index) = newelt;
29585 /* Now we have a final set of template parms to substitute into the
29586 function signature. */
29587 targs = template_parms_to_args (tparms);
29588 fparms = tsubst_arg_types (fparms, tsubst_args, NULL_TREE,
29589 complain, ctor);
29590 if (fparms == error_mark_node)
29591 ok = false;
29592 if (ci)
29594 if (outer_args)
29595 /* FIXME: We'd like to avoid substituting outer template
29596 arguments into the constraint ahead of time, but the
29597 construction of tsubst_args assumes that outer arguments
29598 are already substituted in. */
29599 ci = tsubst_constraint_info (ci, outer_args, complain, ctor);
29600 ci = tsubst_constraint_info (ci, tsubst_args, complain, ctor);
29603 /* Parms are to have DECL_CHAIN tsubsted, which would be skipped if
29604 cp_unevaluated_operand. */
29605 cp_evaluated ev;
29606 fargs = tsubst (fargs, tsubst_args, complain, ctor);
29607 current_template_parms = save_parms;
29609 else
29611 /* Substitute in the same arguments to rewrite class members into
29612 references to members of an unknown specialization. */
29613 cp_evaluated ev;
29614 fparms = tsubst_arg_types (fparms, targs, NULL_TREE, complain, ctor);
29615 fargs = tsubst (fargs, targs, complain, ctor);
29616 if (ci)
29618 if (outer_args)
29619 /* FIXME: As above. */
29620 ci = tsubst_constraint_info (ci, outer_args, complain, ctor);
29621 ci = tsubst_constraint_info (ci, targs, complain, ctor);
29625 --processing_template_decl;
29626 if (!ok)
29627 return error_mark_node;
29630 if (!memtmpl)
29632 /* Copy the parms so we can set DECL_PRIMARY_TEMPLATE. */
29633 tparms = copy_node (tparms);
29634 INNERMOST_TEMPLATE_PARMS (tparms)
29635 = copy_node (INNERMOST_TEMPLATE_PARMS (tparms));
29638 tree fntype = build_function_type (type, fparms);
29639 tree ded_fn = build_lang_decl_loc (loc,
29640 FUNCTION_DECL,
29641 dguide_name (type), fntype);
29642 DECL_ARGUMENTS (ded_fn) = fargs;
29643 DECL_ARTIFICIAL (ded_fn) = true;
29644 DECL_NONCONVERTING_P (ded_fn) = explicit_p;
29645 tree ded_tmpl = build_template_decl (ded_fn, tparms, /*member*/false);
29646 DECL_ARTIFICIAL (ded_tmpl) = true;
29647 DECL_TEMPLATE_INFO (ded_fn) = build_template_info (ded_tmpl, targs);
29648 DECL_PRIMARY_TEMPLATE (ded_tmpl) = ded_tmpl;
29649 if (DECL_P (ctor))
29650 DECL_ABSTRACT_ORIGIN (ded_tmpl) = fn_tmpl;
29651 if (ci)
29652 set_constraints (ded_tmpl, ci);
29654 return ded_tmpl;
29657 /* Add to LIST the member types for the reshaped initializer CTOR. */
29659 static tree
29660 collect_ctor_idx_types (tree ctor, tree list, tree elt = NULL_TREE)
29662 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (ctor);
29663 tree idx, val; unsigned i;
29664 FOR_EACH_CONSTRUCTOR_ELT (v, i, idx, val)
29666 tree ftype = elt ? elt : TREE_TYPE (idx);
29667 if (BRACE_ENCLOSED_INITIALIZER_P (val)
29668 && CONSTRUCTOR_BRACES_ELIDED_P (val))
29670 tree subelt = NULL_TREE;
29671 if (TREE_CODE (ftype) == ARRAY_TYPE)
29672 subelt = TREE_TYPE (ftype);
29673 list = collect_ctor_idx_types (val, list, subelt);
29674 continue;
29676 tree arg = NULL_TREE;
29677 if (i == v->length() - 1
29678 && PACK_EXPANSION_P (ftype))
29679 /* Give the trailing pack expansion parameter a default argument to
29680 match aggregate initialization behavior, even if we deduce the
29681 length of the pack separately to more than we have initializers. */
29682 arg = build_constructor (init_list_type_node, NULL);
29683 /* if ei is of array type and xi is a braced-init-list or string literal,
29684 Ti is an rvalue reference to the declared type of ei */
29685 STRIP_ANY_LOCATION_WRAPPER (val);
29686 if (TREE_CODE (ftype) == ARRAY_TYPE
29687 && (BRACE_ENCLOSED_INITIALIZER_P (val)
29688 || TREE_CODE (val) == STRING_CST))
29690 if (TREE_CODE (val) == STRING_CST)
29691 ftype = cp_build_qualified_type
29692 (ftype, cp_type_quals (ftype) | TYPE_QUAL_CONST);
29693 ftype = (cp_build_reference_type
29694 (ftype, BRACE_ENCLOSED_INITIALIZER_P (val)));
29696 list = tree_cons (arg, ftype, list);
29699 return list;
29702 /* Return whether ETYPE is, or is derived from, a specialization of TMPL. */
29704 static bool
29705 is_spec_or_derived (tree etype, tree tmpl)
29707 if (!etype || !CLASS_TYPE_P (etype))
29708 return false;
29710 etype = cv_unqualified (etype);
29711 tree type = TREE_TYPE (tmpl);
29712 tree tparms = (INNERMOST_TEMPLATE_PARMS
29713 (DECL_TEMPLATE_PARMS (tmpl)));
29714 tree targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
29715 int err = unify (tparms, targs, type, etype,
29716 UNIFY_ALLOW_DERIVED, /*explain*/false);
29717 ggc_free (targs);
29718 return !err;
29721 static tree alias_ctad_tweaks (tree, tree);
29723 /* Return a C++20 aggregate deduction candidate for TYPE initialized from
29724 INIT. */
29726 static tree
29727 maybe_aggr_guide (tree tmpl, tree init, vec<tree,va_gc> *args)
29729 if (cxx_dialect < cxx20)
29730 return NULL_TREE;
29732 if (init == NULL_TREE)
29733 return NULL_TREE;
29735 if (DECL_ALIAS_TEMPLATE_P (tmpl))
29737 tree under = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
29738 tree tinfo = get_template_info (under);
29739 if (tree guide = maybe_aggr_guide (TI_TEMPLATE (tinfo), init, args))
29740 return alias_ctad_tweaks (tmpl, guide);
29741 return NULL_TREE;
29744 /* We might be creating a guide for a class member template, e.g.,
29746 template<typename U> struct A {
29747 template<typename T> struct B { T t; };
29750 At this point, A will have been instantiated. Below, we need to
29751 use both A<U>::B<T> (TEMPLATE_TYPE) and A<int>::B<T> (TYPE) types. */
29752 const bool member_template_p
29753 = (DECL_TEMPLATE_INFO (tmpl)
29754 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (tmpl)));
29755 tree type = TREE_TYPE (tmpl);
29756 tree template_type = (member_template_p
29757 ? TREE_TYPE (DECL_TI_TEMPLATE (tmpl))
29758 : type);
29759 if (!CP_AGGREGATE_TYPE_P (template_type))
29760 return NULL_TREE;
29762 /* No aggregate candidate for copy-initialization. */
29763 if (args->length() == 1)
29765 tree val = (*args)[0];
29766 if (is_spec_or_derived (TREE_TYPE (val), tmpl))
29767 return NULL_TREE;
29770 /* If we encounter a problem, we just won't add the candidate. */
29771 tsubst_flags_t complain = tf_none;
29773 tree parms = NULL_TREE;
29774 if (BRACE_ENCLOSED_INITIALIZER_P (init))
29776 init = reshape_init (template_type, init, complain);
29777 if (init == error_mark_node)
29778 return NULL_TREE;
29779 parms = collect_ctor_idx_types (init, parms);
29780 /* If we're creating a deduction guide for a member class template,
29781 we've used the original template pattern type for the reshape_init
29782 above; this is done because we want PARMS to be a template parameter
29783 type, something that can be deduced when used as a function template
29784 parameter. At this point the outer class template has already been
29785 partially instantiated (we deferred the deduction until the enclosing
29786 scope is non-dependent). Therefore we have to partially instantiate
29787 PARMS, so that its template level is properly reduced and we don't get
29788 mismatches when deducing types using the guide with PARMS. */
29789 if (member_template_p)
29791 ++processing_template_decl;
29792 parms = tsubst (parms, DECL_TI_ARGS (tmpl), complain, init);
29793 --processing_template_decl;
29796 else if (TREE_CODE (init) == TREE_LIST)
29798 int len = list_length (init);
29799 for (tree field = TYPE_FIELDS (type);
29800 len;
29801 --len, field = DECL_CHAIN (field))
29803 field = next_aggregate_field (field);
29804 if (!field)
29805 return NULL_TREE;
29806 tree ftype = finish_decltype_type (field, true, complain);
29807 parms = tree_cons (NULL_TREE, ftype, parms);
29810 else
29811 /* Aggregate initialization doesn't apply to an initializer expression. */
29812 return NULL_TREE;
29814 if (parms)
29816 tree last = parms;
29817 parms = nreverse (parms);
29818 TREE_CHAIN (last) = void_list_node;
29819 tree guide = build_deduction_guide (type, parms, NULL_TREE, complain);
29820 return guide;
29823 return NULL_TREE;
29826 /* UGUIDES are the deduction guides for the underlying template of alias
29827 template TMPL; adjust them to be deduction guides for TMPL. */
29829 static tree
29830 alias_ctad_tweaks (tree tmpl, tree uguides)
29832 /* [over.match.class.deduct]: When resolving a placeholder for a deduced
29833 class type (9.2.8.2) where the template-name names an alias template A,
29834 the defining-type-id of A must be of the form
29836 typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
29838 as specified in 9.2.8.2. The guides of A are the set of functions or
29839 function templates formed as follows. For each function or function
29840 template f in the guides of the template named by the simple-template-id
29841 of the defining-type-id, the template arguments of the return type of f
29842 are deduced from the defining-type-id of A according to the process in
29843 13.10.2.5 with the exception that deduction does not fail if not all
29844 template arguments are deduced. Let g denote the result of substituting
29845 these deductions into f. If substitution succeeds, form a function or
29846 function template f' with the following properties and add it to the set
29847 of guides of A:
29849 * The function type of f' is the function type of g.
29851 * If f is a function template, f' is a function template whose template
29852 parameter list consists of all the template parameters of A (including
29853 their default template arguments) that appear in the above deductions or
29854 (recursively) in their default template arguments, followed by the
29855 template parameters of f that were not deduced (including their default
29856 template arguments), otherwise f' is not a function template.
29858 * The associated constraints (13.5.2) are the conjunction of the
29859 associated constraints of g and a constraint that is satisfied if and only
29860 if the arguments of A are deducible (see below) from the return type.
29862 * If f is a copy deduction candidate (12.4.1.8), then f' is considered to
29863 be so as well.
29865 * If f was generated from a deduction-guide (12.4.1.8), then f' is
29866 considered to be so as well.
29868 * The explicit-specifier of f' is the explicit-specifier of g (if
29869 any). */
29871 /* This implementation differs from the above in two significant ways:
29873 1) We include all template parameters of A, not just some.
29874 2) The added constraint is same_type instead of deducible.
29876 I believe that while it's probably possible to construct a testcase that
29877 behaves differently with this simplification, it should have the same
29878 effect for real uses. Including all template parameters means that we
29879 deduce all parameters of A when resolving the call, so when we're in the
29880 constraint we don't need to deduce them again, we can just check whether
29881 the deduction produced the desired result. */
29883 tsubst_flags_t complain = tf_warning_or_error;
29884 tree atype = TREE_TYPE (tmpl);
29885 tree aguides = NULL_TREE;
29886 tree atparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
29887 unsigned natparms = TREE_VEC_LENGTH (atparms);
29888 tree utype = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
29889 for (ovl_iterator iter (uguides); iter; ++iter)
29891 tree f = *iter;
29892 tree in_decl = f;
29893 location_t loc = DECL_SOURCE_LOCATION (f);
29894 tree ret = TREE_TYPE (TREE_TYPE (f));
29895 tree fprime = f;
29896 if (TREE_CODE (f) == TEMPLATE_DECL)
29898 processing_template_decl_sentinel ptds (/*reset*/false);
29899 ++processing_template_decl;
29901 /* Deduce template arguments for f from the type-id of A. */
29902 tree ftparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (f));
29903 unsigned len = TREE_VEC_LENGTH (ftparms);
29904 tree targs = make_tree_vec (len);
29905 int err = unify (ftparms, targs, ret, utype, UNIFY_ALLOW_NONE, false);
29906 if (err)
29907 continue;
29909 /* The number of parms for f' is the number of parms for A plus
29910 non-deduced parms of f. */
29911 unsigned ndlen = 0;
29912 unsigned j;
29913 for (unsigned i = 0; i < len; ++i)
29914 if (TREE_VEC_ELT (targs, i) == NULL_TREE)
29915 ++ndlen;
29916 tree gtparms = make_tree_vec (natparms + ndlen);
29918 /* Set current_template_parms as in build_deduction_guide. */
29919 auto ctp = make_temp_override (current_template_parms);
29920 current_template_parms = copy_node (DECL_TEMPLATE_PARMS (tmpl));
29921 TREE_VALUE (current_template_parms) = gtparms;
29923 /* First copy over the parms of A. */
29924 for (j = 0; j < natparms; ++j)
29925 TREE_VEC_ELT (gtparms, j) = TREE_VEC_ELT (atparms, j);
29926 /* Now rewrite the non-deduced parms of f. */
29927 for (unsigned i = 0; ndlen && i < len; ++i)
29928 if (TREE_VEC_ELT (targs, i) == NULL_TREE)
29930 --ndlen;
29931 unsigned index = j++;
29932 unsigned level = 1;
29933 tree oldlist = TREE_VEC_ELT (ftparms, i);
29934 tree list = rewrite_tparm_list (oldlist, index, level,
29935 targs, i, complain);
29936 TREE_VEC_ELT (gtparms, index) = list;
29938 gtparms = build_tree_list (size_one_node, gtparms);
29940 /* Substitute the deduced arguments plus the rewritten template
29941 parameters into f to get g. This covers the type, copyness,
29942 guideness, and explicit-specifier. */
29943 tree g;
29945 /* Parms are to have DECL_CHAIN tsubsted, which would be skipped
29946 if cp_unevaluated_operand. */
29947 cp_evaluated ev;
29948 g = tsubst_decl (DECL_TEMPLATE_RESULT (f), targs, complain);
29950 if (g == error_mark_node)
29951 continue;
29952 DECL_USE_TEMPLATE (g) = 0;
29953 fprime = build_template_decl (g, gtparms, false);
29954 DECL_TEMPLATE_RESULT (fprime) = g;
29955 TREE_TYPE (fprime) = TREE_TYPE (g);
29956 tree gtargs = template_parms_to_args (gtparms);
29957 DECL_TEMPLATE_INFO (g) = build_template_info (fprime, gtargs);
29958 DECL_PRIMARY_TEMPLATE (fprime) = fprime;
29960 /* Substitute the associated constraints. */
29961 tree ci = get_constraints (f);
29962 if (ci)
29963 ci = tsubst_constraint_info (ci, targs, complain, in_decl);
29964 if (ci == error_mark_node)
29965 continue;
29967 /* Add a constraint that the return type matches the instantiation of
29968 A with the same template arguments. */
29969 ret = TREE_TYPE (TREE_TYPE (fprime));
29970 if (!same_type_p (atype, ret)
29971 /* FIXME this should mean they don't compare as equivalent. */
29972 || dependent_alias_template_spec_p (atype, nt_opaque))
29974 tree same = finish_trait_expr (loc, CPTK_IS_SAME, atype, ret);
29975 ci = append_constraint (ci, same);
29978 if (ci)
29980 remove_constraints (fprime);
29981 set_constraints (fprime, ci);
29984 else
29986 /* For a non-template deduction guide, if the arguments of A aren't
29987 deducible from the return type, don't add the candidate. */
29988 tree targs = make_tree_vec (natparms);
29989 int err = unify (atparms, targs, utype, ret, UNIFY_ALLOW_NONE, false);
29990 for (unsigned i = 0; !err && i < natparms; ++i)
29991 if (TREE_VEC_ELT (targs, i) == NULL_TREE)
29992 err = true;
29993 if (err)
29994 continue;
29997 aguides = lookup_add (fprime, aguides);
30000 return aguides;
30003 /* Return artificial deduction guides built from the constructors of class
30004 template TMPL. */
30006 static tree
30007 ctor_deduction_guides_for (tree tmpl, tsubst_flags_t complain)
30009 tree type = TREE_TYPE (tmpl);
30010 tree outer_args = NULL_TREE;
30011 if (DECL_CLASS_SCOPE_P (tmpl)
30012 && CLASSTYPE_TEMPLATE_INSTANTIATION (DECL_CONTEXT (tmpl)))
30014 outer_args = copy_node (CLASSTYPE_TI_ARGS (type));
30015 gcc_assert (TMPL_ARGS_DEPTH (outer_args) > 1);
30016 --TREE_VEC_LENGTH (outer_args);
30017 type = TREE_TYPE (most_general_template (tmpl));
30020 tree cands = NULL_TREE;
30022 for (ovl_iterator iter (CLASSTYPE_CONSTRUCTORS (type)); iter; ++iter)
30024 /* Skip inherited constructors. */
30025 if (iter.using_p ())
30026 continue;
30028 tree guide = build_deduction_guide (type, *iter, outer_args, complain);
30029 cands = lookup_add (guide, cands);
30032 /* Add implicit default constructor deduction guide. */
30033 if (!TYPE_HAS_USER_CONSTRUCTOR (type))
30035 tree guide = build_deduction_guide (type, type, outer_args,
30036 complain);
30037 cands = lookup_add (guide, cands);
30040 /* Add copy guide. */
30042 tree gtype = build_reference_type (type);
30043 tree guide = build_deduction_guide (type, gtype, outer_args,
30044 complain);
30045 cands = lookup_add (guide, cands);
30048 return cands;
30051 static GTY((deletable)) hash_map<tree, tree_pair_p> *dguide_cache;
30053 /* Return the non-aggregate deduction guides for deducible template TMPL. The
30054 aggregate candidate is added separately because it depends on the
30055 initializer. Set ANY_DGUIDES_P if we find a non-implicit deduction
30056 guide. */
30058 static tree
30059 deduction_guides_for (tree tmpl, bool &any_dguides_p, tsubst_flags_t complain)
30061 tree guides = NULL_TREE;
30062 if (DECL_ALIAS_TEMPLATE_P (tmpl))
30064 tree under = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30065 tree tinfo = get_template_info (under);
30066 guides = deduction_guides_for (TI_TEMPLATE (tinfo), any_dguides_p,
30067 complain);
30069 else
30071 guides = lookup_qualified_name (CP_DECL_CONTEXT (tmpl),
30072 dguide_name (tmpl),
30073 LOOK_want::NORMAL, /*complain*/false);
30074 if (guides == error_mark_node)
30075 guides = NULL_TREE;
30076 else
30077 any_dguides_p = true;
30080 /* Cache the deduction guides for a template. We also remember the result of
30081 lookup, and rebuild everything if it changes; should be very rare. */
30082 tree_pair_p cache = NULL;
30083 if (tree_pair_p &r
30084 = hash_map_safe_get_or_insert<hm_ggc> (dguide_cache, tmpl))
30086 cache = r;
30087 if (cache->purpose == guides)
30088 return cache->value;
30090 else
30092 r = cache = ggc_cleared_alloc<tree_pair_s> ();
30093 cache->purpose = guides;
30096 tree cands = NULL_TREE;
30097 if (DECL_ALIAS_TEMPLATE_P (tmpl))
30098 cands = alias_ctad_tweaks (tmpl, guides);
30099 else
30101 cands = ctor_deduction_guides_for (tmpl, complain);
30102 for (ovl_iterator it (guides); it; ++it)
30103 cands = lookup_add (*it, cands);
30106 cache->value = cands;
30107 return cands;
30110 /* Return whether TMPL is a (class template argument-) deducible template. */
30112 bool
30113 ctad_template_p (tree tmpl)
30115 /* A deducible template is either a class template or is an alias template
30116 whose defining-type-id is of the form
30118 typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
30120 where the nested-name-specifier (if any) is non-dependent and the
30121 template-name of the simple-template-id names a deducible template. */
30123 if (DECL_CLASS_TEMPLATE_P (tmpl)
30124 || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
30125 return true;
30126 if (!DECL_ALIAS_TEMPLATE_P (tmpl))
30127 return false;
30128 tree orig = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30129 if (tree tinfo = get_template_info (orig))
30130 return ctad_template_p (TI_TEMPLATE (tinfo));
30131 return false;
30134 /* Deduce template arguments for the class template placeholder PTYPE for
30135 template TMPL based on the initializer INIT, and return the resulting
30136 type. */
30138 static tree
30139 do_class_deduction (tree ptype, tree tmpl, tree init,
30140 int flags, tsubst_flags_t complain)
30142 /* We should have handled this in the caller. */
30143 if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
30144 return ptype;
30146 /* If the class was erroneous, don't try to deduce, because that
30147 can generate a lot of diagnostic. */
30148 if (TREE_TYPE (tmpl)
30149 && TYPE_LANG_SPECIFIC (TREE_TYPE (tmpl))
30150 && CLASSTYPE_ERRONEOUS (TREE_TYPE (tmpl)))
30151 return ptype;
30153 /* Wait until the enclosing scope is non-dependent. */
30154 if (DECL_CLASS_SCOPE_P (tmpl)
30155 && dependent_type_p (DECL_CONTEXT (tmpl)))
30156 return ptype;
30158 /* Initializing one placeholder from another. */
30159 if (init
30160 && (TREE_CODE (init) == TEMPLATE_PARM_INDEX
30161 || (TREE_CODE (init) == EXPR_PACK_EXPANSION
30162 && (TREE_CODE (PACK_EXPANSION_PATTERN (init))
30163 == TEMPLATE_PARM_INDEX)))
30164 && is_auto (TREE_TYPE (init))
30165 && CLASS_PLACEHOLDER_TEMPLATE (TREE_TYPE (init)) == tmpl)
30166 return cp_build_qualified_type (TREE_TYPE (init), cp_type_quals (ptype));
30168 if (!ctad_template_p (tmpl))
30170 if (complain & tf_error)
30171 error ("non-deducible template %qT used without template arguments", tmpl);
30172 return error_mark_node;
30174 else if (cxx_dialect < cxx20 && DECL_ALIAS_TEMPLATE_P (tmpl))
30176 if (complain & tf_error)
30178 /* Be permissive with equivalent alias templates. */
30179 tree u = get_underlying_template (tmpl);
30180 diagnostic_t dk = (u == tmpl) ? DK_ERROR : DK_PEDWARN;
30181 bool complained
30182 = emit_diagnostic (dk, input_location, 0,
30183 "alias template deduction only available "
30184 "with %<-std=c++20%> or %<-std=gnu++20%>");
30185 if (u == tmpl)
30186 return error_mark_node;
30187 else if (complained)
30189 inform (input_location, "use %qD directly instead", u);
30190 tmpl = u;
30193 else
30194 return error_mark_node;
30197 /* Wait until the initializer is non-dependent. */
30198 if (type_dependent_expression_p (init))
30199 return ptype;
30201 /* Don't bother with the alias rules for an equivalent template. */
30202 tmpl = get_underlying_template (tmpl);
30204 tree type = TREE_TYPE (tmpl);
30206 bool try_list_cand = false;
30207 bool list_init_p = false;
30209 releasing_vec rv_args = NULL;
30210 vec<tree,va_gc> *&args = *&rv_args;
30211 if (init == NULL_TREE)
30212 args = make_tree_vector ();
30213 else if (BRACE_ENCLOSED_INITIALIZER_P (init))
30215 list_init_p = true;
30216 try_list_cand = true;
30217 if (CONSTRUCTOR_NELTS (init) == 1
30218 && !CONSTRUCTOR_IS_DESIGNATED_INIT (init))
30220 /* As an exception, the first phase in 16.3.1.7 (considering the
30221 initializer list as a single argument) is omitted if the
30222 initializer list consists of a single expression of type cv U,
30223 where U is a specialization of C or a class derived from a
30224 specialization of C. */
30225 tree elt = CONSTRUCTOR_ELT (init, 0)->value;
30226 if (is_spec_or_derived (TREE_TYPE (elt), tmpl))
30227 try_list_cand = false;
30229 if (try_list_cand || is_std_init_list (type))
30230 args = make_tree_vector_single (init);
30231 else
30232 args = make_tree_vector_from_ctor (init);
30234 else if (TREE_CODE (init) == TREE_LIST)
30235 args = make_tree_vector_from_list (init);
30236 else
30237 args = make_tree_vector_single (init);
30239 /* Do this now to avoid problems with erroneous args later on. */
30240 args = resolve_args (args, complain);
30241 if (args == NULL)
30242 return error_mark_node;
30244 bool any_dguides_p = false;
30245 tree cands = deduction_guides_for (tmpl, any_dguides_p, complain);
30246 if (cands == error_mark_node)
30247 return error_mark_node;
30249 /* Prune explicit deduction guides in copy-initialization context (but
30250 not copy-list-initialization). */
30251 bool elided = false;
30252 if (!list_init_p && (flags & LOOKUP_ONLYCONVERTING))
30254 for (lkp_iterator iter (cands); !elided && iter; ++iter)
30255 if (DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
30256 elided = true;
30258 if (elided)
30260 /* Found a nonconverting guide, prune the candidates. */
30261 tree pruned = NULL_TREE;
30262 for (lkp_iterator iter (cands); iter; ++iter)
30263 if (!DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
30264 pruned = lookup_add (*iter, pruned);
30266 cands = pruned;
30270 if (!any_dguides_p)
30271 if (tree guide = maybe_aggr_guide (tmpl, init, args))
30272 cands = lookup_add (guide, cands);
30274 tree fndecl = error_mark_node;
30276 /* If this is list-initialization and the class has a list guide, first
30277 try deducing from the list as a single argument, as [over.match.list]. */
30278 if (try_list_cand)
30280 tree list_cands = NULL_TREE;
30281 for (tree dg : lkp_range (cands))
30282 if (is_list_ctor (dg))
30283 list_cands = lookup_add (dg, list_cands);
30284 if (list_cands)
30285 fndecl = perform_dguide_overload_resolution (list_cands, args, tf_none);
30286 if (fndecl == error_mark_node)
30288 /* That didn't work, now try treating the list as a sequence of
30289 arguments. */
30290 release_tree_vector (args);
30291 args = make_tree_vector_from_ctor (init);
30292 args = resolve_args (args, complain);
30293 if (args == NULL)
30294 return error_mark_node;
30298 if (elided && !cands)
30300 error ("cannot deduce template arguments for copy-initialization"
30301 " of %qT, as it has no non-explicit deduction guides or "
30302 "user-declared constructors", type);
30303 return error_mark_node;
30305 else if (!cands && fndecl == error_mark_node)
30307 error ("cannot deduce template arguments of %qT, as it has no viable "
30308 "deduction guides", type);
30309 return error_mark_node;
30312 if (fndecl == error_mark_node)
30313 fndecl = perform_dguide_overload_resolution (cands, args, tf_none);
30315 if (fndecl == error_mark_node)
30317 if (complain & tf_warning_or_error)
30319 error ("class template argument deduction failed:");
30320 perform_dguide_overload_resolution (cands, args, complain);
30321 if (elided)
30322 inform (input_location, "explicit deduction guides not considered "
30323 "for copy-initialization");
30325 return error_mark_node;
30327 /* [over.match.list]/1: In copy-list-initialization, if an explicit
30328 constructor is chosen, the initialization is ill-formed. */
30329 else if (flags & LOOKUP_ONLYCONVERTING)
30331 if (DECL_NONCONVERTING_P (fndecl))
30333 if (complain & tf_warning_or_error)
30335 // TODO: Pass down location from cp_finish_decl.
30336 error ("class template argument deduction for %qT failed: "
30337 "explicit deduction guide selected in "
30338 "copy-list-initialization", type);
30339 inform (DECL_SOURCE_LOCATION (fndecl),
30340 "explicit deduction guide declared here");
30343 return error_mark_node;
30347 /* If CTAD succeeded but the type doesn't have any explicit deduction
30348 guides, this deduction might not be what the user intended. */
30349 if (fndecl != error_mark_node && !any_dguides_p && (complain & tf_warning))
30351 if ((!DECL_IN_SYSTEM_HEADER (fndecl)
30352 || global_dc->dc_warn_system_headers)
30353 && warning (OPT_Wctad_maybe_unsupported,
30354 "%qT may not intend to support class template argument "
30355 "deduction", type))
30356 inform (input_location, "add a deduction guide to suppress this "
30357 "warning");
30360 return cp_build_qualified_type (TREE_TYPE (TREE_TYPE (fndecl)),
30361 cp_type_quals (ptype));
30364 /* Return true if INIT is an unparenthesized id-expression or an
30365 unparenthesized class member access. Used for the argument of
30366 decltype(auto). */
30368 bool
30369 unparenthesized_id_or_class_member_access_p (tree init)
30371 STRIP_ANY_LOCATION_WRAPPER (init);
30373 /* We need to be able to tell '(r)' and 'r' apart (when it's of
30374 reference type). Only the latter is an id-expression. */
30375 if (REFERENCE_REF_P (init)
30376 && !REF_PARENTHESIZED_P (init))
30377 init = TREE_OPERAND (init, 0);
30378 return (DECL_P (init)
30379 || ((TREE_CODE (init) == COMPONENT_REF
30380 || TREE_CODE (init) == SCOPE_REF)
30381 && !REF_PARENTHESIZED_P (init)));
30384 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
30385 from INIT. AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.
30386 The CONTEXT determines the context in which auto deduction is performed
30387 and is used to control error diagnostics. FLAGS are the LOOKUP_* flags.
30389 OUTER_TARGS is used during template argument deduction (context == adc_unify)
30390 to properly substitute the result. It's also used in the adc_unify and
30391 adc_requirement contexts to communicate the necessary template arguments
30392 to satisfaction. OUTER_TARGS is ignored in other contexts.
30394 For partial-concept-ids, extra args may be appended to the list of deduced
30395 template arguments prior to determining constraint satisfaction. */
30397 tree
30398 do_auto_deduction (tree type, tree init, tree auto_node,
30399 tsubst_flags_t complain, auto_deduction_context context,
30400 tree outer_targs, int flags)
30402 if (init == error_mark_node)
30403 return error_mark_node;
30405 if (init && type_dependent_expression_p (init)
30406 && context != adc_unify)
30407 /* Defining a subset of type-dependent expressions that we can deduce
30408 from ahead of time isn't worth the trouble. */
30409 return type;
30411 /* Similarly, we can't deduce from another undeduced decl. */
30412 if (init && undeduced_auto_decl (init))
30413 return type;
30415 /* We may be doing a partial substitution, but we still want to replace
30416 auto_node. */
30417 complain &= ~tf_partial;
30419 /* In C++23, we must deduce the type to int&& for code like
30420 decltype(auto) f(int&& x) { return (x); }
30422 auto&& f(int x) { return x; }
30423 so we use treat_lvalue_as_rvalue_p. But don't do it for
30424 decltype(auto) f(int x) { return x; }
30425 where we should deduce 'int' rather than 'int&&'; transmogrifying
30426 INIT to an rvalue would break that. */
30427 tree r;
30428 if (cxx_dialect >= cxx23
30429 && context == adc_return_type
30430 && (!AUTO_IS_DECLTYPE (auto_node)
30431 || !unparenthesized_id_or_class_member_access_p (init))
30432 && (r = treat_lvalue_as_rvalue_p (maybe_undo_parenthesized_ref (init),
30433 /*return*/true)))
30434 init = r;
30436 if (tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node))
30437 /* C++17 class template argument deduction. */
30438 return do_class_deduction (type, tmpl, init, flags, complain);
30440 if (init == NULL_TREE || TREE_TYPE (init) == NULL_TREE)
30441 /* Nothing we can do with this, even in deduction context. */
30442 return type;
30444 location_t loc = cp_expr_loc_or_input_loc (init);
30446 /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
30447 with either a new invented type template parameter U or, if the
30448 initializer is a braced-init-list (8.5.4), with
30449 std::initializer_list<U>. */
30450 if (BRACE_ENCLOSED_INITIALIZER_P (init))
30452 if (!DIRECT_LIST_INIT_P (init))
30453 type = listify_autos (type, auto_node);
30454 else if (CONSTRUCTOR_NELTS (init) == 1)
30455 init = CONSTRUCTOR_ELT (init, 0)->value;
30456 else
30458 if (complain & tf_warning_or_error)
30460 if (permerror (loc, "direct-list-initialization of "
30461 "%<auto%> requires exactly one element"))
30462 inform (loc,
30463 "for deduction to %<std::initializer_list%>, use copy-"
30464 "list-initialization (i.e. add %<=%> before the %<{%>)");
30466 type = listify_autos (type, auto_node);
30470 if (type == error_mark_node)
30471 return error_mark_node;
30473 if (BRACE_ENCLOSED_INITIALIZER_P (init))
30475 /* We don't recurse here because we can't deduce from a nested
30476 initializer_list. */
30477 if (CONSTRUCTOR_ELTS (init))
30478 for (constructor_elt &elt : CONSTRUCTOR_ELTS (init))
30479 elt.value = resolve_nondeduced_context (elt.value, complain);
30481 else
30482 init = resolve_nondeduced_context (init, complain);
30484 tree targs;
30485 if (context == adc_decomp_type
30486 && auto_node == type
30487 && init != error_mark_node
30488 && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
30490 /* [dcl.struct.bind]/1 - if decomposition declaration has no ref-qualifiers
30491 and initializer has array type, deduce cv-qualified array type. */
30492 targs = make_tree_vec (1);
30493 TREE_VEC_ELT (targs, 0) = TREE_TYPE (init);
30495 else if (AUTO_IS_DECLTYPE (auto_node))
30497 const bool id = unparenthesized_id_or_class_member_access_p (init);
30498 tree deduced = finish_decltype_type (init, id, complain);
30499 deduced = canonicalize_type_argument (deduced, complain);
30500 if (deduced == error_mark_node)
30501 return error_mark_node;
30502 targs = make_tree_vec (1);
30503 TREE_VEC_ELT (targs, 0) = deduced;
30505 else
30507 if (error_operand_p (init))
30508 return error_mark_node;
30510 tree parms = build_tree_list (NULL_TREE, type);
30511 tree tparms;
30513 if (flag_concepts_ts)
30514 tparms = extract_autos (type);
30515 else
30517 tparms = make_tree_vec (1);
30518 TREE_VEC_ELT (tparms, 0)
30519 = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
30522 targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
30523 int val = type_unification_real (tparms, targs, parms, &init, 1, 0,
30524 DEDUCE_CALL,
30525 NULL, /*explain_p=*/false);
30526 if (val > 0)
30528 if (processing_template_decl)
30529 /* Try again at instantiation time. */
30530 return type;
30531 if (type && type != error_mark_node
30532 && (complain & tf_error))
30533 /* If type is error_mark_node a diagnostic must have been
30534 emitted by now. Also, having a mention to '<type error>'
30535 in the diagnostic is not really useful to the user. */
30537 if (cfun
30538 && FNDECL_USED_AUTO (current_function_decl)
30539 && (auto_node
30540 == DECL_SAVED_AUTO_RETURN_TYPE (current_function_decl))
30541 && LAMBDA_FUNCTION_P (current_function_decl))
30542 error_at (loc, "unable to deduce lambda return type from %qE",
30543 init);
30544 else
30545 error_at (loc, "unable to deduce %qT from %qE", type, init);
30546 type_unification_real (tparms, targs, parms, &init, 1, 0,
30547 DEDUCE_CALL,
30548 NULL, /*explain_p=*/true);
30550 return error_mark_node;
30554 /* Check any placeholder constraints against the deduced type. */
30555 if (processing_template_decl && context == adc_unify)
30556 /* Constraints will be checked after deduction. */;
30557 else if (tree constr = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (auto_node)))
30559 if (processing_template_decl)
30561 gcc_checking_assert (context == adc_variable_type
30562 || context == adc_return_type
30563 || context == adc_decomp_type);
30564 gcc_checking_assert (!type_dependent_expression_p (init));
30565 /* If the constraint is dependent, we need to wait until
30566 instantiation time to resolve the placeholder. */
30567 if (placeholder_type_constraint_dependent_p (constr))
30568 return type;
30571 if (context == adc_return_type
30572 || context == adc_variable_type
30573 || context == adc_decomp_type)
30574 if (tree fn = current_function_decl)
30575 if (DECL_TEMPLATE_INFO (fn) || LAMBDA_FUNCTION_P (fn))
30577 outer_targs = DECL_TEMPLATE_INFO (fn)
30578 ? DECL_TI_ARGS (fn) : NULL_TREE;
30579 if (LAMBDA_FUNCTION_P (fn))
30581 /* As in satisfy_declaration_constraints. */
30582 tree regen_args = lambda_regenerating_args (fn);
30583 if (outer_targs)
30584 outer_targs = add_to_template_args (regen_args, outer_targs);
30585 else
30586 outer_targs = regen_args;
30590 tree full_targs = add_to_template_args (outer_targs, targs);
30592 /* HACK: Compensate for callers not always communicating all levels of
30593 outer template arguments by filling in the outermost missing levels
30594 with dummy levels before checking satisfaction. We'll still crash
30595 if the constraint depends on a template argument belonging to one of
30596 these missing levels, but this hack otherwise allows us to handle a
30597 large subset of possible constraints (including all non-dependent
30598 constraints). */
30599 if (int missing_levels = (TEMPLATE_TYPE_ORIG_LEVEL (auto_node)
30600 - TMPL_ARGS_DEPTH (full_targs)))
30602 tree dummy_levels = make_tree_vec (missing_levels);
30603 for (int i = 0; i < missing_levels; ++i)
30604 TREE_VEC_ELT (dummy_levels, i) = make_tree_vec (0);
30605 full_targs = add_to_template_args (dummy_levels, full_targs);
30608 if (!constraints_satisfied_p (auto_node, full_targs))
30610 if (complain & tf_warning_or_error)
30612 auto_diagnostic_group d;
30613 switch (context)
30615 case adc_unspecified:
30616 case adc_unify:
30617 error_at (loc, "placeholder constraints not satisfied");
30618 break;
30619 case adc_variable_type:
30620 case adc_decomp_type:
30621 error_at (loc, "deduced initializer does not satisfy "
30622 "placeholder constraints");
30623 break;
30624 case adc_return_type:
30625 error_at (loc, "deduced return type does not satisfy "
30626 "placeholder constraints");
30627 break;
30628 case adc_requirement:
30629 error_at (loc, "deduced expression type does not satisfy "
30630 "placeholder constraints");
30631 break;
30633 diagnose_constraints (loc, auto_node, full_targs);
30635 return error_mark_node;
30639 if (TEMPLATE_TYPE_LEVEL (auto_node) == 1)
30640 /* The outer template arguments are already substituted into type
30641 (but we still may have used them for constraint checking above). */;
30642 else if (context == adc_unify)
30643 targs = add_to_template_args (outer_targs, targs);
30644 else if (processing_template_decl)
30645 targs = add_to_template_args (current_template_args (), targs);
30646 return tsubst (type, targs, complain, NULL_TREE);
30649 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
30650 result. */
30652 tree
30653 splice_late_return_type (tree type, tree late_return_type)
30655 if (late_return_type)
30657 gcc_assert (is_auto (type) || seen_error ());
30658 return late_return_type;
30661 if (tree auto_node = find_type_usage (type, is_auto))
30662 if (TEMPLATE_TYPE_LEVEL (auto_node) <= current_template_depth)
30664 /* In an abbreviated function template we didn't know we were dealing
30665 with a function template when we saw the auto return type, so rebuild
30666 the return type using an auto with the correct level. */
30667 tree new_auto = make_auto_1 (TYPE_IDENTIFIER (auto_node), false);
30668 tree auto_vec = make_tree_vec (1);
30669 TREE_VEC_ELT (auto_vec, 0) = new_auto;
30670 tree targs = add_outermost_template_args (current_template_args (),
30671 auto_vec);
30672 /* Also rebuild the constraint info in terms of the new auto. */
30673 if (tree ci = PLACEHOLDER_TYPE_CONSTRAINTS_INFO (auto_node))
30674 PLACEHOLDER_TYPE_CONSTRAINTS_INFO (new_auto)
30675 = build_tree_list (current_template_parms,
30676 tsubst_constraint (TREE_VALUE (ci), targs,
30677 tf_none, NULL_TREE));
30678 TYPE_CANONICAL (new_auto) = canonical_type_parameter (new_auto);
30679 return tsubst (type, targs, tf_none, NULL_TREE);
30681 return type;
30684 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto' or
30685 'decltype(auto)' or a deduced class template. */
30687 bool
30688 is_auto (const_tree type)
30690 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
30691 && (TYPE_IDENTIFIER (type) == auto_identifier
30692 || TYPE_IDENTIFIER (type) == decltype_auto_identifier))
30693 return true;
30694 else
30695 return false;
30698 /* for_each_template_parm callback for type_uses_auto. */
30701 is_auto_r (tree tp, void */*data*/)
30703 return is_auto (tp);
30706 /* Returns the TEMPLATE_TYPE_PARM in TYPE representing `auto' iff TYPE contains
30707 a use of `auto'. Returns NULL_TREE otherwise. */
30709 tree
30710 type_uses_auto (tree type)
30712 if (type == NULL_TREE)
30713 return NULL_TREE;
30714 else if (flag_concepts_ts)
30716 /* The Concepts TS allows multiple autos in one type-specifier; just
30717 return the first one we find, do_auto_deduction will collect all of
30718 them. */
30719 if (uses_template_parms (type))
30720 return for_each_template_parm (type, is_auto_r, /*data*/NULL,
30721 /*visited*/NULL, /*nondeduced*/false);
30722 else
30723 return NULL_TREE;
30725 else
30726 return find_type_usage (type, is_auto);
30729 /* Report ill-formed occurrences of auto types in ARGUMENTS. If
30730 concepts are enabled, auto is acceptable in template arguments, but
30731 only when TEMPL identifies a template class. Return TRUE if any
30732 such errors were reported. */
30734 bool
30735 check_auto_in_tmpl_args (tree tmpl, tree args)
30737 if (!flag_concepts_ts)
30738 /* Only the concepts TS allows 'auto' as a type-id; it'd otherwise
30739 have already been rejected by the parser more generally. */
30740 return false;
30742 /* If there were previous errors, nevermind. */
30743 if (!args || TREE_CODE (args) != TREE_VEC)
30744 return false;
30746 /* If TMPL is an identifier, we're parsing and we can't tell yet
30747 whether TMPL is supposed to be a type, a function or a variable.
30748 We'll only be able to tell during template substitution, so we
30749 expect to be called again then. If concepts are enabled and we
30750 know we have a type, we're ok. */
30751 if (identifier_p (tmpl)
30752 || (DECL_P (tmpl)
30753 && (DECL_TYPE_TEMPLATE_P (tmpl)
30754 || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))))
30755 return false;
30757 /* Quickly search for any occurrences of auto; usually there won't
30758 be any, and then we'll avoid allocating the vector. */
30759 if (!type_uses_auto (args))
30760 return false;
30762 bool errors = false;
30764 tree vec = extract_autos (args);
30765 for (int i = 0; i < TREE_VEC_LENGTH (vec); i++)
30767 tree xauto = TREE_VALUE (TREE_VEC_ELT (vec, i));
30768 error_at (DECL_SOURCE_LOCATION (xauto),
30769 "invalid use of %qT in template argument", xauto);
30770 errors = true;
30773 return errors;
30776 /* Recursively walk over && expressions searching for EXPR. Return a reference
30777 to that expression. */
30779 static tree *find_template_requirement (tree *t, tree key)
30781 if (*t == key)
30782 return t;
30783 if (TREE_CODE (*t) == TRUTH_ANDIF_EXPR)
30785 if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 0), key))
30786 return p;
30787 if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 1), key))
30788 return p;
30790 return 0;
30793 /* Convert the generic type parameters in PARM that match the types given in the
30794 range [START_IDX, END_IDX) from the current_template_parms into generic type
30795 packs. */
30797 tree
30798 convert_generic_types_to_packs (tree parm, int start_idx, int end_idx)
30800 tree current = current_template_parms;
30801 int depth = TMPL_PARMS_DEPTH (current);
30802 current = INNERMOST_TEMPLATE_PARMS (current);
30803 tree replacement = make_tree_vec (TREE_VEC_LENGTH (current));
30805 for (int i = 0; i < start_idx; ++i)
30806 TREE_VEC_ELT (replacement, i)
30807 = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
30809 for (int i = start_idx; i < end_idx; ++i)
30811 /* Create a distinct parameter pack type from the current parm and add it
30812 to the replacement args to tsubst below into the generic function
30813 parameter. */
30814 tree node = TREE_VEC_ELT (current, i);
30815 tree o = TREE_TYPE (TREE_VALUE (node));
30816 tree t = copy_type (o);
30817 TEMPLATE_TYPE_PARM_INDEX (t)
30818 = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (o),
30819 t, 0, 0, tf_none);
30820 TREE_TYPE (TEMPLATE_TYPE_DECL (t)) = t;
30821 TYPE_STUB_DECL (t) = TYPE_NAME (t) = TEMPLATE_TYPE_DECL (t);
30822 TYPE_MAIN_VARIANT (t) = t;
30823 TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
30824 TYPE_CANONICAL (t) = canonical_type_parameter (t);
30825 TREE_VEC_ELT (replacement, i) = t;
30827 /* Replace the current template parameter with new pack. */
30828 TREE_VALUE (node) = TREE_CHAIN (t);
30830 /* Surgically adjust the associated constraint of adjusted parameter
30831 and it's corresponding contribution to the current template
30832 requirements. */
30833 if (tree constr = TEMPLATE_PARM_CONSTRAINTS (node))
30835 tree id = unpack_concept_check (constr);
30836 TREE_VEC_ELT (TREE_OPERAND (id, 1), 0) = t;
30837 tree fold = finish_left_unary_fold_expr (constr, TRUTH_ANDIF_EXPR);
30838 TEMPLATE_PARM_CONSTRAINTS (node) = fold;
30840 /* If there was a constraint, we also need to replace that in
30841 the template requirements, which we've already built. */
30842 tree *reqs = &TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
30843 reqs = find_template_requirement (reqs, constr);
30844 *reqs = fold;
30848 for (int i = end_idx, e = TREE_VEC_LENGTH (current); i < e; ++i)
30849 TREE_VEC_ELT (replacement, i)
30850 = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
30852 /* If there are more levels then build up the replacement with the outer
30853 template parms. */
30854 if (depth > 1)
30855 replacement = add_to_template_args (template_parms_to_args
30856 (TREE_CHAIN (current_template_parms)),
30857 replacement);
30859 return tsubst (parm, replacement, tf_none, NULL_TREE);
30862 /* __integer_pack(N) in a pack expansion expands to a sequence of numbers from
30863 0..N-1. */
30865 void
30866 declare_integer_pack (void)
30868 tree ipfn = push_library_fn (get_identifier ("__integer_pack"),
30869 build_function_type_list (integer_type_node,
30870 integer_type_node,
30871 NULL_TREE),
30872 NULL_TREE, ECF_CONST);
30873 DECL_DECLARED_CONSTEXPR_P (ipfn) = true;
30874 set_decl_built_in_function (ipfn, BUILT_IN_FRONTEND,
30875 CP_BUILT_IN_INTEGER_PACK);
30878 /* Walk the decl or type specialization table calling FN on each
30879 entry. */
30881 void
30882 walk_specializations (bool decls_p,
30883 void (*fn) (bool decls_p, spec_entry *entry, void *data),
30884 void *data)
30886 spec_hash_table *table = decls_p ? decl_specializations
30887 : type_specializations;
30888 spec_hash_table::iterator end (table->end ());
30889 for (spec_hash_table::iterator iter (table->begin ()); iter != end; ++iter)
30890 fn (decls_p, *iter, data);
30893 /* Lookup the specialization of *ELT, in the decl or type
30894 specialization table. Return the SPEC that's already there, or
30895 NULL if nothing. */
30897 tree
30898 match_mergeable_specialization (bool decl_p, spec_entry *elt)
30900 hash_table<spec_hasher> *specializations
30901 = decl_p ? decl_specializations : type_specializations;
30902 hashval_t hash = spec_hasher::hash (elt);
30903 auto *slot = specializations->find_slot_with_hash (elt, hash, NO_INSERT);
30905 if (slot)
30906 return (*slot)->spec;
30908 return NULL_TREE;
30911 /* Return flags encoding whether SPEC is on the instantiation and/or
30912 specialization lists of TMPL. */
30914 unsigned
30915 get_mergeable_specialization_flags (tree tmpl, tree decl)
30917 unsigned flags = 0;
30919 for (tree inst = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
30920 inst; inst = TREE_CHAIN (inst))
30921 if (TREE_VALUE (inst) == decl)
30923 flags |= 1;
30924 break;
30927 if (CLASS_TYPE_P (TREE_TYPE (decl))
30928 && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl))
30929 && CLASSTYPE_USE_TEMPLATE (TREE_TYPE (decl)) == 2)
30930 /* Only need to search if DECL is a partial specialization. */
30931 for (tree part = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
30932 part; part = TREE_CHAIN (part))
30933 if (TREE_VALUE (part) == decl)
30935 flags |= 2;
30936 break;
30939 return flags;
30942 /* Add a new specialization described by SPEC. DECL is the
30943 maybe-template decl and FLAGS is as returned from
30944 get_mergeable_specialization_flags. */
30946 void
30947 add_mergeable_specialization (bool decl_p, bool alias_p, spec_entry *elt,
30948 tree decl, unsigned flags)
30950 hashval_t hash = spec_hasher::hash (elt);
30951 if (decl_p)
30953 auto *slot = decl_specializations->find_slot_with_hash (elt, hash, INSERT);
30955 gcc_checking_assert (!*slot);
30956 auto entry = ggc_alloc<spec_entry> ();
30957 *entry = *elt;
30958 *slot = entry;
30960 if (alias_p)
30962 elt->spec = TREE_TYPE (elt->spec);
30963 gcc_checking_assert (elt->spec);
30967 if (!decl_p || alias_p)
30969 auto *slot = type_specializations->find_slot_with_hash (elt, hash, INSERT);
30971 /* We don't distinguish different constrained partial type
30972 specializations, so there could be duplicates. Everything else
30973 must be new. */
30974 if (!(flags & 2 && *slot))
30976 gcc_checking_assert (!*slot);
30978 auto entry = ggc_alloc<spec_entry> ();
30979 *entry = *elt;
30980 *slot = entry;
30984 if (flags & 1)
30985 DECL_TEMPLATE_INSTANTIATIONS (elt->tmpl)
30986 = tree_cons (elt->args, decl, DECL_TEMPLATE_INSTANTIATIONS (elt->tmpl));
30988 if (flags & 2)
30990 /* A partial specialization. */
30991 tree cons = tree_cons (elt->args, decl,
30992 DECL_TEMPLATE_SPECIALIZATIONS (elt->tmpl));
30993 TREE_TYPE (cons) = decl_p ? TREE_TYPE (elt->spec) : elt->spec;
30994 DECL_TEMPLATE_SPECIALIZATIONS (elt->tmpl) = cons;
30998 /* Set up the hash tables for template instantiations. */
31000 void
31001 init_template_processing (void)
31003 decl_specializations = hash_table<spec_hasher>::create_ggc (37);
31004 type_specializations = hash_table<spec_hasher>::create_ggc (37);
31006 if (cxx_dialect >= cxx11)
31007 declare_integer_pack ();
31010 /* Print stats about the template hash tables for -fstats. */
31012 void
31013 print_template_statistics (void)
31015 fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
31016 "%f collisions\n", (long) decl_specializations->size (),
31017 (long) decl_specializations->elements (),
31018 decl_specializations->collisions ());
31019 fprintf (stderr, "type_specializations: size %ld, %ld elements, "
31020 "%f collisions\n", (long) type_specializations->size (),
31021 (long) type_specializations->elements (),
31022 type_specializations->collisions ());
31025 #if CHECKING_P
31027 namespace selftest {
31029 /* Verify that build_non_dependent_expr () works, for various expressions,
31030 and that location wrappers don't affect the results. */
31032 static void
31033 test_build_non_dependent_expr ()
31035 location_t loc = BUILTINS_LOCATION;
31037 /* Verify constants, without and with location wrappers. */
31038 tree int_cst = build_int_cst (integer_type_node, 42);
31039 ASSERT_EQ (int_cst, build_non_dependent_expr (int_cst));
31041 tree wrapped_int_cst = maybe_wrap_with_location (int_cst, loc);
31042 ASSERT_TRUE (location_wrapper_p (wrapped_int_cst));
31043 ASSERT_EQ (wrapped_int_cst, build_non_dependent_expr (wrapped_int_cst));
31045 tree string_lit = build_string (4, "foo");
31046 TREE_TYPE (string_lit) = char_array_type_node;
31047 string_lit = fix_string_type (string_lit);
31048 ASSERT_EQ (string_lit, build_non_dependent_expr (string_lit));
31050 tree wrapped_string_lit = maybe_wrap_with_location (string_lit, loc);
31051 ASSERT_TRUE (location_wrapper_p (wrapped_string_lit));
31052 ASSERT_EQ (wrapped_string_lit,
31053 build_non_dependent_expr (wrapped_string_lit));
31056 /* Verify that type_dependent_expression_p () works correctly, even
31057 in the presence of location wrapper nodes. */
31059 static void
31060 test_type_dependent_expression_p ()
31062 location_t loc = BUILTINS_LOCATION;
31064 tree name = get_identifier ("foo");
31066 /* If no templates are involved, nothing is type-dependent. */
31067 gcc_assert (!processing_template_decl);
31068 ASSERT_FALSE (type_dependent_expression_p (name));
31070 ++processing_template_decl;
31072 /* Within a template, an unresolved name is always type-dependent. */
31073 ASSERT_TRUE (type_dependent_expression_p (name));
31075 /* Ensure it copes with NULL_TREE and errors. */
31076 ASSERT_FALSE (type_dependent_expression_p (NULL_TREE));
31077 ASSERT_FALSE (type_dependent_expression_p (error_mark_node));
31079 /* A USING_DECL in a template should be type-dependent, even if wrapped
31080 with a location wrapper (PR c++/83799). */
31081 tree using_decl = build_lang_decl (USING_DECL, name, NULL_TREE);
31082 TREE_TYPE (using_decl) = integer_type_node;
31083 ASSERT_TRUE (type_dependent_expression_p (using_decl));
31084 tree wrapped_using_decl = maybe_wrap_with_location (using_decl, loc);
31085 ASSERT_TRUE (location_wrapper_p (wrapped_using_decl));
31086 ASSERT_TRUE (type_dependent_expression_p (wrapped_using_decl));
31088 --processing_template_decl;
31091 /* Run all of the selftests within this file. */
31093 void
31094 cp_pt_cc_tests ()
31096 test_build_non_dependent_expr ();
31097 test_type_dependent_expression_p ();
31100 } // namespace selftest
31102 #endif /* #if CHECKING_P */
31104 #include "gt-cp-pt.h"