ada: Fix wrong resolution for hidden discriminant in predicate
[official-gcc.git] / gcc / cp / pt.cc
blob076f788281efaa70e506967eef21e15dbd762185
1 /* Handle parameterized types (templates) for GNU -*- C++ -*-.
2 Copyright (C) 1992-2023 Free Software Foundation, Inc.
3 Written by Ken Raeburn (raeburn@cygnus.com) while at Watchmaker Computing.
4 Rewritten by Jason Merrill (jason@cygnus.com).
6 This file is part of GCC.
8 GCC is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3, or (at your option)
11 any later version.
13 GCC is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3. If not see
20 <http://www.gnu.org/licenses/>. */
22 /* Known bugs or deficiencies include:
24 all methods must be provided in header files; can't use a source
25 file that contains only the method templates and "just win".
27 Fixed by: C++20 modules. */
29 #include "config.h"
30 #define INCLUDE_ALGORITHM // for std::equal
31 #include "system.h"
32 #include "coretypes.h"
33 #include "cp-tree.h"
34 #include "timevar.h"
35 #include "stringpool.h"
36 #include "varasm.h"
37 #include "attribs.h"
38 #include "stor-layout.h"
39 #include "intl.h"
40 #include "c-family/c-objc.h"
41 #include "cp-objcp-common.h"
42 #include "toplev.h"
43 #include "tree-iterator.h"
44 #include "type-utils.h"
45 #include "gimplify.h"
46 #include "gcc-rich-location.h"
47 #include "selftest.h"
48 #include "target.h"
50 /* The type of functions taking a tree, and some additional data, and
51 returning an int. */
52 typedef int (*tree_fn_t) (tree, void*);
54 /* The PENDING_TEMPLATES is a list of templates whose instantiations
55 have been deferred, either because their definitions were not yet
56 available, or because we were putting off doing the work. */
57 struct GTY ((chain_next ("%h.next"))) pending_template
59 struct pending_template *next;
60 struct tinst_level *tinst;
63 static GTY(()) struct pending_template *pending_templates;
64 static GTY(()) struct pending_template *last_pending_template;
66 int processing_template_parmlist;
67 static int template_header_count;
69 static vec<int> inline_parm_levels;
71 static GTY(()) struct tinst_level *current_tinst_level;
73 static GTY(()) vec<tree, va_gc> *saved_access_scope;
75 /* Live only within one (recursive) call to tsubst_expr. We use
76 this to pass the statement expression node from the STMT_EXPR
77 to the EXPR_STMT that is its result. */
78 static tree cur_stmt_expr;
80 // -------------------------------------------------------------------------- //
81 // Local Specialization Stack
83 // Implementation of the RAII helper for creating new local
84 // specializations.
85 local_specialization_stack::local_specialization_stack (lss_policy policy)
86 : saved (local_specializations)
88 if (policy == lss_nop)
90 else if (policy == lss_blank || !saved)
91 local_specializations = new hash_map<tree, tree>;
92 else
93 local_specializations = new hash_map<tree, tree>(*saved);
96 local_specialization_stack::~local_specialization_stack ()
98 if (local_specializations != saved)
100 delete local_specializations;
101 local_specializations = saved;
105 /* True if we've recursed into fn_type_unification too many times. */
106 static bool excessive_deduction_depth;
108 struct spec_hasher : ggc_ptr_hash<spec_entry>
110 static hashval_t hash (tree, tree);
111 static hashval_t hash (spec_entry *);
112 static bool equal (spec_entry *, spec_entry *);
115 /* The general template is not in these tables. */
116 typedef hash_table<spec_hasher> spec_hash_table;
117 static GTY (()) spec_hash_table *decl_specializations;
118 static GTY (()) spec_hash_table *type_specializations;
120 /* Contains canonical template parameter types. The vector is indexed by
121 the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
122 TREE_LIST, whose TREE_VALUEs contain the canonical template
123 parameters of various types and levels. */
124 static GTY(()) vec<tree, va_gc> *canonical_template_parms;
126 #define UNIFY_ALLOW_NONE 0
127 #define UNIFY_ALLOW_MORE_CV_QUAL 1
128 #define UNIFY_ALLOW_LESS_CV_QUAL 2
129 #define UNIFY_ALLOW_DERIVED 4
130 #define UNIFY_ALLOW_INTEGER 8
131 #define UNIFY_ALLOW_OUTER_LEVEL 16
132 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
133 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
135 enum template_base_result {
136 tbr_incomplete_type,
137 tbr_ambiguous_baseclass,
138 tbr_success
141 static bool resolve_overloaded_unification (tree, tree, tree, tree,
142 unification_kind_t, int,
143 bool);
144 static int try_one_overload (tree, tree, tree, tree, tree,
145 unification_kind_t, int, bool, bool);
146 static int unify (tree, tree, tree, tree, int, bool);
147 static void add_pending_template (tree);
148 static tree reopen_tinst_level (struct tinst_level *);
149 static tree tsubst_initializer_list (tree, tree);
150 static tree get_partial_spec_bindings (tree, tree, tree);
151 static void tsubst_enum (tree, tree, tree);
152 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
153 static int check_non_deducible_conversion (tree, tree, unification_kind_t, int,
154 struct conversion **, bool);
155 static int maybe_adjust_types_for_deduction (tree, unification_kind_t,
156 tree*, tree*, tree);
157 static int type_unification_real (tree, tree, tree, const tree *,
158 unsigned int, int, unification_kind_t,
159 vec<deferred_access_check, va_gc> **,
160 bool);
161 static void note_template_header (int);
162 static tree convert_nontype_argument_function (tree, tree, tsubst_flags_t);
163 static tree convert_nontype_argument (tree, tree, tsubst_flags_t);
164 static tree convert_template_argument (tree, tree, tree,
165 tsubst_flags_t, int, tree);
166 static tree for_each_template_parm (tree, tree_fn_t, void*,
167 hash_set<tree> *, bool, tree_fn_t = NULL);
168 static tree expand_template_argument_pack (tree);
169 static tree build_template_parm_index (int, int, int, tree, tree);
170 static bool inline_needs_template_parms (tree, bool);
171 static void push_inline_template_parms_recursive (tree, int);
172 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
173 static int mark_template_parm (tree, void *);
174 static int template_parm_this_level_p (tree, void *);
175 static tree tsubst_friend_function (tree, tree);
176 static tree tsubst_friend_class (tree, tree);
177 static int can_complete_type_without_circularity (tree);
178 static tree get_bindings (tree, tree, tree, bool);
179 static int template_decl_level (tree);
180 static int check_cv_quals_for_unify (int, tree, tree);
181 static int unify_pack_expansion (tree, tree, tree,
182 tree, unification_kind_t, bool, bool);
183 static tree copy_template_args (tree);
184 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
185 static void tsubst_each_template_parm_constraints (tree, tree, tsubst_flags_t);
186 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
187 static tree tsubst_aggr_type_1 (tree, tree, tsubst_flags_t, tree, int);
188 static tree tsubst_arg_types (tree, tree, tree, tsubst_flags_t, tree);
189 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
190 static bool check_specialization_scope (void);
191 static tree process_partial_specialization (tree);
192 static enum template_base_result get_template_base (tree, tree, tree, tree,
193 bool , tree *);
194 static tree try_class_unification (tree, tree, tree, tree, bool);
195 static bool class_nttp_const_wrapper_p (tree t);
196 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
197 tree, tree);
198 static bool template_template_parm_bindings_ok_p (tree, tree);
199 static void tsubst_default_arguments (tree, tsubst_flags_t);
200 static tree for_each_template_parm_r (tree *, int *, void *);
201 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
202 static void copy_default_args_to_explicit_spec (tree);
203 static bool invalid_nontype_parm_type_p (tree, tsubst_flags_t);
204 static bool dependent_template_arg_p (tree);
205 static bool dependent_type_p_r (tree);
206 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
207 static tree tsubst_decl (tree, tree, tsubst_flags_t);
208 static tree tsubst_scope (tree, tree, tsubst_flags_t, tree);
209 static void perform_instantiation_time_access_checks (tree, tree);
210 static tree listify (tree);
211 static tree listify_autos (tree, tree);
212 static tree tsubst_template_parm (tree, tree, tsubst_flags_t);
213 static tree instantiate_alias_template (tree, tree, tsubst_flags_t);
214 static bool complex_alias_template_p (const_tree tmpl);
215 static tree get_underlying_template (tree);
216 static tree tsubst_attributes (tree, tree, tsubst_flags_t, tree);
217 static tree canonicalize_expr_argument (tree, tsubst_flags_t);
218 static tree make_argument_pack (tree);
219 static tree enclosing_instantiation_of (tree tctx);
220 static void instantiate_body (tree pattern, tree args, tree d, bool nested);
221 static tree maybe_dependent_member_ref (tree, tree, tsubst_flags_t, tree);
222 static void mark_template_arguments_used (tree, tree);
223 static bool uses_outer_template_parms (tree);
225 /* Make the current scope suitable for access checking when we are
226 processing T. T can be FUNCTION_DECL for instantiated function
227 template, VAR_DECL for static member variable, or TYPE_DECL for
228 for a class or alias template (needed by instantiate_decl). */
230 void
231 push_access_scope (tree t)
233 gcc_assert (VAR_OR_FUNCTION_DECL_P (t)
234 || TREE_CODE (t) == TYPE_DECL);
236 if (DECL_FRIEND_CONTEXT (t))
237 push_nested_class (DECL_FRIEND_CONTEXT (t));
238 else if (DECL_IMPLICIT_TYPEDEF_P (t)
239 && CLASS_TYPE_P (TREE_TYPE (t)))
240 push_nested_class (TREE_TYPE (t));
241 else if (DECL_CLASS_SCOPE_P (t))
242 push_nested_class (DECL_CONTEXT (t));
243 else if (deduction_guide_p (t) && DECL_ARTIFICIAL (t))
244 /* An artificial deduction guide should have the same access as
245 the constructor. */
246 push_nested_class (TREE_TYPE (TREE_TYPE (t)));
247 else
248 push_to_top_level ();
250 if (TREE_CODE (t) == FUNCTION_DECL)
252 vec_safe_push (saved_access_scope, current_function_decl);
253 current_function_decl = t;
257 /* Restore the scope set up by push_access_scope. T is the node we
258 are processing. */
260 void
261 pop_access_scope (tree t)
263 if (TREE_CODE (t) == FUNCTION_DECL)
264 current_function_decl = saved_access_scope->pop();
266 if (DECL_FRIEND_CONTEXT (t)
267 || (DECL_IMPLICIT_TYPEDEF_P (t)
268 && CLASS_TYPE_P (TREE_TYPE (t)))
269 || DECL_CLASS_SCOPE_P (t)
270 || (deduction_guide_p (t) && DECL_ARTIFICIAL (t)))
271 pop_nested_class ();
272 else
273 pop_from_top_level ();
276 /* Do any processing required when DECL (a member template
277 declaration) is finished. Returns the TEMPLATE_DECL corresponding
278 to DECL, unless it is a specialization, in which case the DECL
279 itself is returned. */
281 tree
282 finish_member_template_decl (tree decl)
284 if (decl == error_mark_node)
285 return error_mark_node;
287 gcc_assert (DECL_P (decl));
289 if (TREE_CODE (decl) == TYPE_DECL)
291 tree type;
293 type = TREE_TYPE (decl);
294 if (type == error_mark_node)
295 return error_mark_node;
296 if (MAYBE_CLASS_TYPE_P (type)
297 && CLASSTYPE_TEMPLATE_INFO (type)
298 && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
300 tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
301 check_member_template (tmpl);
302 return tmpl;
304 return NULL_TREE;
306 else if (TREE_CODE (decl) == FIELD_DECL)
307 error_at (DECL_SOURCE_LOCATION (decl),
308 "data member %qD cannot be a member template", decl);
309 else if (DECL_TEMPLATE_INFO (decl))
311 if (!DECL_TEMPLATE_SPECIALIZATION (decl))
313 check_member_template (DECL_TI_TEMPLATE (decl));
314 return DECL_TI_TEMPLATE (decl);
316 else
317 return decl;
319 else
320 error_at (DECL_SOURCE_LOCATION (decl),
321 "invalid member template declaration %qD", decl);
323 return error_mark_node;
326 /* Create a template info node. */
328 tree
329 build_template_info (tree template_decl, tree template_args)
331 tree result = make_node (TEMPLATE_INFO);
332 TI_TEMPLATE (result) = template_decl;
333 TI_ARGS (result) = template_args;
334 return result;
337 /* Return the template info node corresponding to T, whatever T is. */
339 tree
340 get_template_info (const_tree t)
342 tree tinfo = NULL_TREE;
344 if (!t || t == error_mark_node)
345 return NULL;
347 if (TREE_CODE (t) == NAMESPACE_DECL
348 || TREE_CODE (t) == PARM_DECL)
349 return NULL;
351 if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
352 tinfo = DECL_TEMPLATE_INFO (t);
354 if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
355 t = TREE_TYPE (t);
357 if (OVERLOAD_TYPE_P (t))
358 tinfo = TYPE_TEMPLATE_INFO (t);
359 else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
360 tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
362 return tinfo;
365 /* Returns the template nesting level of the indicated class TYPE.
367 For example, in:
368 template <class T>
369 struct A
371 template <class U>
372 struct B {};
375 A<T>::B<U> has depth two, while A<T> has depth one.
376 Both A<T>::B<int> and A<int>::B<U> have depth one, if
377 they are instantiations, not specializations.
379 This function is guaranteed to return 0 if passed NULL_TREE so
380 that, for example, `template_class_depth (current_class_type)' is
381 always safe. */
384 template_class_depth (tree type)
386 int depth;
388 for (depth = 0; type && TREE_CODE (type) != NAMESPACE_DECL; )
390 tree tinfo = get_template_info (type);
392 if (tinfo
393 && TREE_CODE (TI_TEMPLATE (tinfo)) == TEMPLATE_DECL
394 && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
395 && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
396 ++depth;
398 if (DECL_P (type))
400 if (tree fctx = DECL_FRIEND_CONTEXT (type))
401 type = fctx;
402 else
403 type = CP_DECL_CONTEXT (type);
405 else if (LAMBDA_TYPE_P (type) && LAMBDA_TYPE_EXTRA_SCOPE (type))
406 type = LAMBDA_TYPE_EXTRA_SCOPE (type);
407 else
408 type = CP_TYPE_CONTEXT (type);
411 return depth;
414 /* Return TRUE if NODE instantiates a template that has arguments of
415 its own, be it directly a primary template or indirectly through a
416 partial specializations. */
417 static bool
418 instantiates_primary_template_p (tree node)
420 tree tinfo = get_template_info (node);
421 if (!tinfo)
422 return false;
424 tree tmpl = TI_TEMPLATE (tinfo);
425 if (PRIMARY_TEMPLATE_P (tmpl))
426 return true;
428 if (!DECL_TEMPLATE_SPECIALIZATION (tmpl))
429 return false;
431 /* So now we know we have a specialization, but it could be a full
432 or a partial specialization. To tell which, compare the depth of
433 its template arguments with those of its context. */
435 tree ctxt = DECL_CONTEXT (tmpl);
436 tree ctinfo = get_template_info (ctxt);
437 if (!ctinfo)
438 return true;
440 return (TMPL_ARGS_DEPTH (TI_ARGS (tinfo))
441 > TMPL_ARGS_DEPTH (TI_ARGS (ctinfo)));
444 /* Subroutine of maybe_begin_member_template_processing.
445 Returns true if processing DECL needs us to push template parms. */
447 static bool
448 inline_needs_template_parms (tree decl, bool nsdmi)
450 if (!decl || (!nsdmi && ! DECL_TEMPLATE_INFO (decl)))
451 return false;
453 return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
454 > (current_template_depth + DECL_TEMPLATE_SPECIALIZATION (decl)));
457 /* Subroutine of maybe_begin_member_template_processing.
458 Push the template parms in PARMS, starting from LEVELS steps into the
459 chain, and ending at the beginning, since template parms are listed
460 innermost first. */
462 static void
463 push_inline_template_parms_recursive (tree parmlist, int levels)
465 tree parms = TREE_VALUE (parmlist);
466 int i;
468 if (levels > 1)
469 push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
471 ++processing_template_decl;
472 current_template_parms
473 = tree_cons (size_int (current_template_depth + 1),
474 parms, current_template_parms);
475 TEMPLATE_PARMS_CONSTRAINTS (current_template_parms)
476 = TEMPLATE_PARMS_CONSTRAINTS (parmlist);
477 TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
479 begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
480 NULL);
481 for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
483 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
485 if (error_operand_p (parm))
486 continue;
488 gcc_assert (DECL_P (parm));
490 switch (TREE_CODE (parm))
492 case TYPE_DECL:
493 case TEMPLATE_DECL:
494 pushdecl (parm);
495 break;
497 case PARM_DECL:
498 /* Push the CONST_DECL. */
499 pushdecl (TEMPLATE_PARM_DECL (DECL_INITIAL (parm)));
500 break;
502 default:
503 gcc_unreachable ();
508 /* Restore the template parameter context for a member template, a
509 friend template defined in a class definition, or a non-template
510 member of template class. */
512 void
513 maybe_begin_member_template_processing (tree decl)
515 tree parms;
516 int levels = 0;
517 bool nsdmi = TREE_CODE (decl) == FIELD_DECL;
519 if (nsdmi)
521 tree ctx = DECL_CONTEXT (decl);
522 decl = (CLASSTYPE_TEMPLATE_INFO (ctx)
523 /* Disregard full specializations (c++/60999). */
524 && uses_template_parms (ctx)
525 ? CLASSTYPE_TI_TEMPLATE (ctx) : NULL_TREE);
528 if (inline_needs_template_parms (decl, nsdmi))
530 parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
531 levels = TMPL_PARMS_DEPTH (parms) - current_template_depth;
533 if (DECL_TEMPLATE_SPECIALIZATION (decl))
535 --levels;
536 parms = TREE_CHAIN (parms);
539 push_inline_template_parms_recursive (parms, levels);
542 /* Remember how many levels of template parameters we pushed so that
543 we can pop them later. */
544 inline_parm_levels.safe_push (levels);
547 /* Undo the effects of maybe_begin_member_template_processing. */
549 void
550 maybe_end_member_template_processing (void)
552 int i;
553 int last;
555 if (inline_parm_levels.length () == 0)
556 return;
558 last = inline_parm_levels.pop ();
559 for (i = 0; i < last; ++i)
561 --processing_template_decl;
562 current_template_parms = TREE_CHAIN (current_template_parms);
563 poplevel (0, 0, 0);
567 /* Return a new template argument vector which contains all of ARGS,
568 but has as its innermost set of arguments the EXTRA_ARGS. */
570 tree
571 add_to_template_args (tree args, tree extra_args)
573 tree new_args;
574 int extra_depth;
575 int i;
576 int j;
578 if (args == NULL_TREE || extra_args == error_mark_node)
579 return extra_args;
581 extra_depth = TMPL_ARGS_DEPTH (extra_args);
582 new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
584 for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
585 SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
587 for (j = 1; j <= extra_depth; ++j, ++i)
588 SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
590 return new_args;
593 /* Like add_to_template_args, but only the outermost ARGS are added to
594 the EXTRA_ARGS. In particular, all but TMPL_ARGS_DEPTH
595 (EXTRA_ARGS) levels are added. This function is used to combine
596 the template arguments from a partial instantiation with the
597 template arguments used to attain the full instantiation from the
598 partial instantiation.
600 If ARGS is a TEMPLATE_DECL, use its parameters as args. */
602 tree
603 add_outermost_template_args (tree args, tree extra_args)
605 tree new_args;
607 if (!args)
608 return extra_args;
609 if (TREE_CODE (args) == TEMPLATE_DECL)
611 tree ti = get_template_info (DECL_TEMPLATE_RESULT (args));
612 args = TI_ARGS (ti);
615 /* If there are more levels of EXTRA_ARGS than there are ARGS,
616 something very fishy is going on. */
617 gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
619 /* If *all* the new arguments will be the EXTRA_ARGS, just return
620 them. */
621 if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
622 return extra_args;
624 /* For the moment, we make ARGS look like it contains fewer levels. */
625 TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
627 new_args = add_to_template_args (args, extra_args);
629 /* Now, we restore ARGS to its full dimensions. */
630 TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
632 return new_args;
635 /* Return the N levels of innermost template arguments from the ARGS. */
637 tree
638 get_innermost_template_args (tree args, int n)
640 tree new_args;
641 int extra_levels;
642 int i;
644 gcc_assert (n >= 0);
646 /* If N is 1, just return the innermost set of template arguments. */
647 if (n == 1)
648 return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
650 /* If we're not removing anything, just return the arguments we were
651 given. */
652 extra_levels = TMPL_ARGS_DEPTH (args) - n;
653 gcc_assert (extra_levels >= 0);
654 if (extra_levels == 0)
655 return args;
657 /* Make a new set of arguments, not containing the outer arguments. */
658 new_args = make_tree_vec (n);
659 for (i = 1; i <= n; ++i)
660 SET_TMPL_ARGS_LEVEL (new_args, i,
661 TMPL_ARGS_LEVEL (args, i + extra_levels));
663 return new_args;
666 /* The inverse of get_innermost_template_args: Return all but the innermost
667 EXTRA_LEVELS levels of template arguments from the ARGS. */
669 static tree
670 strip_innermost_template_args (tree args, int extra_levels)
672 tree new_args;
673 int n = TMPL_ARGS_DEPTH (args) - extra_levels;
674 int i;
676 gcc_assert (n >= 0);
678 /* If N is 1, just return the outermost set of template arguments. */
679 if (n == 1)
680 return TMPL_ARGS_LEVEL (args, 1);
682 /* If we're not removing anything, just return the arguments we were
683 given. */
684 gcc_assert (extra_levels >= 0);
685 if (extra_levels == 0)
686 return args;
688 /* Make a new set of arguments, not containing the inner arguments. */
689 new_args = make_tree_vec (n);
690 for (i = 1; i <= n; ++i)
691 SET_TMPL_ARGS_LEVEL (new_args, i,
692 TMPL_ARGS_LEVEL (args, i));
694 return new_args;
697 /* We've got a template header coming up; push to a new level for storing
698 the parms. */
700 void
701 begin_template_parm_list (void)
703 /* We use a non-tag-transparent scope here, which causes pushtag to
704 put tags in this scope, rather than in the enclosing class or
705 namespace scope. This is the right thing, since we want
706 TEMPLATE_DECLS, and not TYPE_DECLS for template classes. For a
707 global template class, push_template_decl handles putting the
708 TEMPLATE_DECL into top-level scope. For a nested template class,
709 e.g.:
711 template <class T> struct S1 {
712 template <class T> struct S2 {};
715 pushtag contains special code to insert the TEMPLATE_DECL for S2
716 at the right scope. */
717 begin_scope (sk_template_parms, NULL);
718 ++processing_template_decl;
719 ++processing_template_parmlist;
720 note_template_header (0);
722 /* Add a dummy parameter level while we process the parameter list. */
723 current_template_parms
724 = tree_cons (size_int (current_template_depth + 1),
725 make_tree_vec (0),
726 current_template_parms);
729 /* This routine is called when a specialization is declared. If it is
730 invalid to declare a specialization here, an error is reported and
731 false is returned, otherwise this routine will return true. */
733 static bool
734 check_specialization_scope (void)
736 tree scope = current_scope ();
738 /* [temp.expl.spec]
740 An explicit specialization shall be declared in the namespace of
741 which the template is a member, or, for member templates, in the
742 namespace of which the enclosing class or enclosing class
743 template is a member. An explicit specialization of a member
744 function, member class or static data member of a class template
745 shall be declared in the namespace of which the class template
746 is a member. */
747 if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
749 error ("explicit specialization in non-namespace scope %qD", scope);
750 return false;
753 /* [temp.expl.spec]
755 In an explicit specialization declaration for a member of a class
756 template or a member template that appears in namespace scope,
757 the member template and some of its enclosing class templates may
758 remain unspecialized, except that the declaration shall not
759 explicitly specialize a class member template if its enclosing
760 class templates are not explicitly specialized as well. */
761 if (current_template_parms)
763 error ("enclosing class templates are not explicitly specialized");
764 return false;
767 return true;
770 /* We've just seen template <>. */
772 bool
773 begin_specialization (void)
775 begin_scope (sk_template_spec, NULL);
776 note_template_header (1);
777 return check_specialization_scope ();
780 /* Called at then end of processing a declaration preceded by
781 template<>. */
783 void
784 end_specialization (void)
786 finish_scope ();
787 reset_specialization ();
790 /* Any template <>'s that we have seen thus far are not referring to a
791 function specialization. */
793 void
794 reset_specialization (void)
796 processing_specialization = 0;
797 template_header_count = 0;
800 /* We've just seen a template header. If SPECIALIZATION is nonzero,
801 it was of the form template <>. */
803 static void
804 note_template_header (int specialization)
806 processing_specialization = specialization;
807 template_header_count++;
810 /* We're beginning an explicit instantiation. */
812 void
813 begin_explicit_instantiation (void)
815 gcc_assert (!processing_explicit_instantiation);
816 processing_explicit_instantiation = true;
820 void
821 end_explicit_instantiation (void)
823 gcc_assert (processing_explicit_instantiation);
824 processing_explicit_instantiation = false;
827 /* An explicit specialization or partial specialization of TMPL is being
828 declared. Check that the namespace in which the specialization is
829 occurring is permissible. Returns false iff it is invalid to
830 specialize TMPL in the current namespace. */
832 static bool
833 check_specialization_namespace (tree tmpl)
835 tree tpl_ns = decl_namespace_context (tmpl);
837 /* [tmpl.expl.spec]
839 An explicit specialization shall be declared in a namespace enclosing the
840 specialized template. An explicit specialization whose declarator-id is
841 not qualified shall be declared in the nearest enclosing namespace of the
842 template, or, if the namespace is inline (7.3.1), any namespace from its
843 enclosing namespace set. */
844 if (current_scope() != DECL_CONTEXT (tmpl)
845 && !at_namespace_scope_p ())
847 error ("specialization of %qD must appear at namespace scope", tmpl);
848 return false;
851 if (is_nested_namespace (current_namespace, tpl_ns, cxx_dialect < cxx11))
852 /* Same or enclosing namespace. */
853 return true;
854 else
856 auto_diagnostic_group d;
857 if (permerror (input_location,
858 "specialization of %qD in different namespace", tmpl))
859 inform (DECL_SOURCE_LOCATION (tmpl),
860 " from definition of %q#D", tmpl);
861 return false;
865 /* SPEC is an explicit instantiation. Check that it is valid to
866 perform this explicit instantiation in the current namespace. */
868 static void
869 check_explicit_instantiation_namespace (tree spec)
871 tree ns;
873 /* DR 275: An explicit instantiation shall appear in an enclosing
874 namespace of its template. */
875 ns = decl_namespace_context (spec);
876 if (!is_nested_namespace (current_namespace, ns))
877 permerror (input_location, "explicit instantiation of %qD in namespace %qD "
878 "(which does not enclose namespace %qD)",
879 spec, current_namespace, ns);
882 /* Returns true if TYPE is a new partial specialization that needs to be
883 set up. This may also modify TYPE to point to the correct (new or
884 existing) constrained partial specialization. */
886 static bool
887 maybe_new_partial_specialization (tree& type)
889 /* An implicit instantiation of an incomplete type implies
890 the definition of a new class template.
892 template<typename T>
893 struct S;
895 template<typename T>
896 struct S<T*>;
898 Here, S<T*> is an implicit instantiation of S whose type
899 is incomplete. */
900 if (CLASSTYPE_IMPLICIT_INSTANTIATION (type) && !COMPLETE_TYPE_P (type))
901 return true;
903 /* It can also be the case that TYPE is a completed specialization.
904 Continuing the previous example, suppose we also declare:
906 template<typename T>
907 requires Integral<T>
908 struct S<T*>;
910 Here, S<T*> refers to the specialization S<T*> defined
911 above. However, we need to differentiate definitions because
912 we intend to define a new partial specialization. In this case,
913 we rely on the fact that the constraints are different for
914 this declaration than that above.
916 Note that we also get here for injected class names and
917 late-parsed template definitions. We must ensure that we
918 do not create new type declarations for those cases. */
919 if (flag_concepts && CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
921 tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
922 tree args = CLASSTYPE_TI_ARGS (type);
924 /* If there are no template parameters, this cannot be a new
925 partial template specialization? */
926 if (!current_template_parms)
927 return false;
929 /* The injected-class-name is not a new partial specialization. */
930 if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
931 return false;
933 /* If the constraints are not the same as those of the primary
934 then, we can probably create a new specialization. */
935 tree type_constr = current_template_constraints ();
937 if (type == TREE_TYPE (tmpl))
939 tree main_constr = get_constraints (tmpl);
940 if (equivalent_constraints (type_constr, main_constr))
941 return false;
944 /* Also, if there's a pre-existing specialization with matching
945 constraints, then this also isn't new. */
946 tree specs = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
947 while (specs)
949 tree spec_tmpl = TREE_VALUE (specs);
950 tree spec_args = TREE_PURPOSE (specs);
951 tree spec_constr = get_constraints (spec_tmpl);
952 if (comp_template_args (args, spec_args)
953 && equivalent_constraints (type_constr, spec_constr))
955 type = TREE_TYPE (spec_tmpl);
956 return false;
958 specs = TREE_CHAIN (specs);
961 /* Create a new type node (and corresponding type decl)
962 for the newly declared specialization. */
963 tree t = make_class_type (TREE_CODE (type));
964 CLASSTYPE_DECLARED_CLASS (t) = CLASSTYPE_DECLARED_CLASS (type);
965 SET_TYPE_TEMPLATE_INFO (t, build_template_info (tmpl, args));
967 /* We only need a separate type node for storing the definition of this
968 partial specialization; uses of S<T*> are unconstrained, so all are
969 equivalent. So keep TYPE_CANONICAL the same. */
970 TYPE_CANONICAL (t) = TYPE_CANONICAL (type);
972 /* Build the corresponding type decl. */
973 tree d = create_implicit_typedef (DECL_NAME (tmpl), t);
974 DECL_CONTEXT (d) = TYPE_CONTEXT (t);
975 DECL_SOURCE_LOCATION (d) = input_location;
976 TREE_PRIVATE (d) = (current_access_specifier == access_private_node);
977 TREE_PROTECTED (d) = (current_access_specifier == access_protected_node);
979 set_instantiating_module (d);
980 DECL_MODULE_EXPORT_P (d) = DECL_MODULE_EXPORT_P (tmpl);
982 type = t;
983 return true;
986 return false;
989 /* The TYPE is being declared. If it is a template type, that means it
990 is a partial specialization. Do appropriate error-checking. */
992 tree
993 maybe_process_partial_specialization (tree type)
995 tree context;
997 if (type == error_mark_node)
998 return error_mark_node;
1000 /* A lambda that appears in specialization context is not itself a
1001 specialization. */
1002 if (CLASS_TYPE_P (type) && CLASSTYPE_LAMBDA_EXPR (type))
1003 return type;
1005 /* An injected-class-name is not a specialization. */
1006 if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
1007 return type;
1009 if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
1011 error ("name of class shadows template template parameter %qD",
1012 TYPE_NAME (type));
1013 return error_mark_node;
1016 context = TYPE_CONTEXT (type);
1018 if (TYPE_ALIAS_P (type))
1020 tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (type);
1022 if (tinfo && DECL_ALIAS_TEMPLATE_P (TI_TEMPLATE (tinfo)))
1023 error ("specialization of alias template %qD",
1024 TI_TEMPLATE (tinfo));
1025 else
1026 error ("explicit specialization of non-template %qT", type);
1027 return error_mark_node;
1029 else if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
1031 /* This is for ordinary explicit specialization and partial
1032 specialization of a template class such as:
1034 template <> class C<int>;
1038 template <class T> class C<T*>;
1040 Make sure that `C<int>' and `C<T*>' are implicit instantiations. */
1042 if (maybe_new_partial_specialization (type))
1044 if (!check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type))
1045 && !at_namespace_scope_p ())
1046 return error_mark_node;
1047 SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
1048 DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
1049 if (processing_template_decl)
1051 tree decl = push_template_decl (TYPE_MAIN_DECL (type));
1052 if (decl == error_mark_node)
1053 return error_mark_node;
1054 return TREE_TYPE (decl);
1057 else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
1058 error ("specialization of %qT after instantiation", type);
1059 else if (errorcount && !processing_specialization
1060 && CLASSTYPE_TEMPLATE_SPECIALIZATION (type)
1061 && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
1062 /* Trying to define a specialization either without a template<> header
1063 or in an inappropriate place. We've already given an error, so just
1064 bail now so we don't actually define the specialization. */
1065 return error_mark_node;
1067 else if (CLASS_TYPE_P (type)
1068 && !CLASSTYPE_USE_TEMPLATE (type)
1069 && CLASSTYPE_TEMPLATE_INFO (type)
1070 && context && CLASS_TYPE_P (context)
1071 && CLASSTYPE_TEMPLATE_INFO (context))
1073 /* This is for an explicit specialization of member class
1074 template according to [temp.expl.spec/18]:
1076 template <> template <class U> class C<int>::D;
1078 The context `C<int>' must be an implicit instantiation.
1079 Otherwise this is just a member class template declared
1080 earlier like:
1082 template <> class C<int> { template <class U> class D; };
1083 template <> template <class U> class C<int>::D;
1085 In the first case, `C<int>::D' is a specialization of `C<T>::D'
1086 while in the second case, `C<int>::D' is a primary template
1087 and `C<T>::D' may not exist. */
1089 if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
1090 && !COMPLETE_TYPE_P (type))
1092 tree t;
1093 tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
1095 if (current_namespace
1096 != decl_namespace_context (tmpl))
1098 if (permerror (input_location,
1099 "specialization of %qD in different namespace",
1100 type))
1101 inform (DECL_SOURCE_LOCATION (tmpl),
1102 "from definition of %q#D", tmpl);
1105 /* Check for invalid specialization after instantiation:
1107 template <> template <> class C<int>::D<int>;
1108 template <> template <class U> class C<int>::D; */
1110 for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
1111 t; t = TREE_CHAIN (t))
1113 tree inst = TREE_VALUE (t);
1114 if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst)
1115 || !COMPLETE_OR_OPEN_TYPE_P (inst))
1117 /* We already have a full specialization of this partial
1118 instantiation, or a full specialization has been
1119 looked up but not instantiated. Reassign it to the
1120 new member specialization template. */
1121 spec_entry elt;
1122 spec_entry *entry;
1124 elt.tmpl = most_general_template (tmpl);
1125 elt.args = CLASSTYPE_TI_ARGS (inst);
1126 elt.spec = inst;
1128 type_specializations->remove_elt (&elt);
1130 elt.tmpl = tmpl;
1131 CLASSTYPE_TI_ARGS (inst)
1132 = elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
1134 spec_entry **slot
1135 = type_specializations->find_slot (&elt, INSERT);
1136 entry = ggc_alloc<spec_entry> ();
1137 *entry = elt;
1138 *slot = entry;
1140 else
1141 /* But if we've had an implicit instantiation, that's a
1142 problem ([temp.expl.spec]/6). */
1143 error ("specialization %qT after instantiation %qT",
1144 type, inst);
1147 /* Mark TYPE as a specialization. And as a result, we only
1148 have one level of template argument for the innermost
1149 class template. */
1150 SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
1151 DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
1152 CLASSTYPE_TI_ARGS (type)
1153 = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
1156 else if (processing_specialization)
1158 /* Someday C++0x may allow for enum template specialization. */
1159 if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
1160 && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
1161 pedwarn (input_location, OPT_Wpedantic, "template specialization "
1162 "of %qD not allowed by ISO C++", type);
1163 else
1165 error ("explicit specialization of non-template %qT", type);
1166 return error_mark_node;
1170 return type;
1173 /* Make sure ARGS doesn't use any inappropriate typedefs; we should have
1174 gone through coerce_template_parms by now. */
1176 static void
1177 verify_unstripped_args_1 (tree inner)
1179 for (int i = 0; i < TREE_VEC_LENGTH (inner); ++i)
1181 tree arg = TREE_VEC_ELT (inner, i);
1182 if (TREE_CODE (arg) == TEMPLATE_DECL)
1183 /* OK */;
1184 else if (TYPE_P (arg))
1185 gcc_assert (strip_typedefs (arg, NULL) == arg);
1186 else if (ARGUMENT_PACK_P (arg))
1187 verify_unstripped_args_1 (ARGUMENT_PACK_ARGS (arg));
1188 else if (strip_typedefs (TREE_TYPE (arg), NULL) != TREE_TYPE (arg))
1189 /* Allow typedefs on the type of a non-type argument, since a
1190 parameter can have them. */;
1191 else
1192 gcc_assert (strip_typedefs_expr (arg, NULL) == arg);
1196 static void
1197 verify_unstripped_args (tree args)
1199 ++processing_template_decl;
1200 if (!any_dependent_template_arguments_p (args))
1201 verify_unstripped_args_1 (INNERMOST_TEMPLATE_ARGS (args));
1202 --processing_template_decl;
1205 /* Retrieve the specialization (in the sense of [temp.spec] - a
1206 specialization is either an instantiation or an explicit
1207 specialization) of TMPL for the given template ARGS. If there is
1208 no such specialization, return NULL_TREE. The ARGS are a vector of
1209 arguments, or a vector of vectors of arguments, in the case of
1210 templates with more than one level of parameters.
1212 If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
1213 then we search for a partial specialization matching ARGS. This
1214 parameter is ignored if TMPL is not a class template.
1216 We can also look up a FIELD_DECL, if it is a lambda capture pack; the
1217 result is a NONTYPE_ARGUMENT_PACK. */
1219 static tree
1220 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
1222 if (tmpl == NULL_TREE)
1223 return NULL_TREE;
1225 if (args == error_mark_node)
1226 return NULL_TREE;
1228 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL
1229 || TREE_CODE (tmpl) == FIELD_DECL);
1231 /* There should be as many levels of arguments as there are
1232 levels of parameters. */
1233 gcc_assert (TMPL_ARGS_DEPTH (args)
1234 == (TREE_CODE (tmpl) == TEMPLATE_DECL
1235 ? TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl))
1236 : template_class_depth (DECL_CONTEXT (tmpl))));
1238 if (flag_checking)
1239 verify_unstripped_args (args);
1241 /* Lambda functions in templates aren't instantiated normally, but through
1242 tsubst_lambda_expr. */
1243 if (lambda_fn_in_template_p (tmpl))
1244 return NULL_TREE;
1246 spec_entry elt;
1247 elt.tmpl = tmpl;
1248 elt.args = args;
1249 elt.spec = NULL_TREE;
1251 spec_hash_table *specializations;
1252 if (DECL_CLASS_TEMPLATE_P (tmpl))
1253 specializations = type_specializations;
1254 else
1255 specializations = decl_specializations;
1257 if (hash == 0)
1258 hash = spec_hasher::hash (&elt);
1259 if (spec_entry *found = specializations->find_with_hash (&elt, hash))
1260 return found->spec;
1262 return NULL_TREE;
1265 /* Like retrieve_specialization, but for local declarations. */
1267 tree
1268 retrieve_local_specialization (tree tmpl)
1270 if (local_specializations == NULL)
1271 return NULL_TREE;
1273 tree *slot = local_specializations->get (tmpl);
1274 return slot ? *slot : NULL_TREE;
1277 /* Returns nonzero iff DECL is a specialization of TMPL. */
1280 is_specialization_of (tree decl, tree tmpl)
1282 tree t;
1284 if (TREE_CODE (decl) == FUNCTION_DECL)
1286 for (t = decl;
1287 t != NULL_TREE;
1288 t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1289 if (t == tmpl)
1290 return 1;
1292 else
1294 gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1296 for (t = TREE_TYPE (decl);
1297 t != NULL_TREE;
1298 t = CLASSTYPE_USE_TEMPLATE (t)
1299 ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1300 if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1301 return 1;
1304 return 0;
1307 /* Returns nonzero iff DECL is a specialization of friend declaration
1308 FRIEND_DECL according to [temp.friend]. */
1310 bool
1311 is_specialization_of_friend (tree decl, tree friend_decl)
1313 bool need_template = true;
1314 int template_depth;
1316 gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1317 || TREE_CODE (decl) == TYPE_DECL);
1319 /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1320 of a template class, we want to check if DECL is a specialization
1321 if this. */
1322 if (TREE_CODE (friend_decl) == FUNCTION_DECL
1323 && DECL_CLASS_SCOPE_P (friend_decl)
1324 && DECL_TEMPLATE_INFO (friend_decl)
1325 && !DECL_USE_TEMPLATE (friend_decl))
1327 /* We want a TEMPLATE_DECL for `is_specialization_of'. */
1328 friend_decl = DECL_TI_TEMPLATE (friend_decl);
1329 need_template = false;
1331 else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1332 && !PRIMARY_TEMPLATE_P (friend_decl))
1333 need_template = false;
1335 /* There is nothing to do if this is not a template friend. */
1336 if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1337 return false;
1339 if (is_specialization_of (decl, friend_decl))
1340 return true;
1342 /* [temp.friend/6]
1343 A member of a class template may be declared to be a friend of a
1344 non-template class. In this case, the corresponding member of
1345 every specialization of the class template is a friend of the
1346 class granting friendship.
1348 For example, given a template friend declaration
1350 template <class T> friend void A<T>::f();
1352 the member function below is considered a friend
1354 template <> struct A<int> {
1355 void f();
1358 For this type of template friend, TEMPLATE_DEPTH below will be
1359 nonzero. To determine if DECL is a friend of FRIEND, we first
1360 check if the enclosing class is a specialization of another. */
1362 template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1363 if (template_depth
1364 && DECL_CLASS_SCOPE_P (decl)
1365 && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1366 CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1368 /* Next, we check the members themselves. In order to handle
1369 a few tricky cases, such as when FRIEND_DECL's are
1371 template <class T> friend void A<T>::g(T t);
1372 template <class T> template <T t> friend void A<T>::h();
1374 and DECL's are
1376 void A<int>::g(int);
1377 template <int> void A<int>::h();
1379 we need to figure out ARGS, the template arguments from
1380 the context of DECL. This is required for template substitution
1381 of `T' in the function parameter of `g' and template parameter
1382 of `h' in the above examples. Here ARGS corresponds to `int'. */
1384 tree context = DECL_CONTEXT (decl);
1385 tree args = NULL_TREE;
1386 int current_depth = 0;
1388 while (current_depth < template_depth)
1390 if (CLASSTYPE_TEMPLATE_INFO (context))
1392 if (current_depth == 0)
1393 args = TYPE_TI_ARGS (context);
1394 else
1395 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1396 current_depth++;
1398 context = TYPE_CONTEXT (context);
1401 if (TREE_CODE (decl) == FUNCTION_DECL)
1403 bool is_template;
1404 tree friend_type;
1405 tree decl_type;
1406 tree friend_args_type;
1407 tree decl_args_type;
1409 /* Make sure that both DECL and FRIEND_DECL are templates or
1410 non-templates. */
1411 is_template = DECL_TEMPLATE_INFO (decl)
1412 && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1413 if (need_template ^ is_template)
1414 return false;
1415 else if (is_template)
1417 /* If both are templates, check template parameter list. */
1418 tree friend_parms
1419 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1420 args, tf_none);
1421 if (!comp_template_parms
1422 (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1423 friend_parms))
1424 return false;
1426 decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1428 else
1429 decl_type = TREE_TYPE (decl);
1431 friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1432 tf_none, NULL_TREE);
1433 if (friend_type == error_mark_node)
1434 return false;
1436 /* Check if return types match. */
1437 if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1438 return false;
1440 /* Check if function parameter types match, ignoring the
1441 `this' parameter. */
1442 friend_args_type = TYPE_ARG_TYPES (friend_type);
1443 decl_args_type = TYPE_ARG_TYPES (decl_type);
1444 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1445 friend_args_type = TREE_CHAIN (friend_args_type);
1446 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1447 decl_args_type = TREE_CHAIN (decl_args_type);
1449 return compparms (decl_args_type, friend_args_type);
1451 else
1453 /* DECL is a TYPE_DECL */
1454 bool is_template;
1455 tree decl_type = TREE_TYPE (decl);
1457 /* Make sure that both DECL and FRIEND_DECL are templates or
1458 non-templates. */
1459 is_template
1460 = CLASSTYPE_TEMPLATE_INFO (decl_type)
1461 && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1463 if (need_template ^ is_template)
1464 return false;
1465 else if (is_template)
1467 tree friend_parms;
1468 /* If both are templates, check the name of the two
1469 TEMPLATE_DECL's first because is_friend didn't. */
1470 if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1471 != DECL_NAME (friend_decl))
1472 return false;
1474 /* Now check template parameter list. */
1475 friend_parms
1476 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1477 args, tf_none);
1478 return comp_template_parms
1479 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1480 friend_parms);
1482 else
1483 return (DECL_NAME (decl)
1484 == DECL_NAME (friend_decl));
1487 return false;
1490 /* Register the specialization SPEC as a specialization of TMPL with
1491 the indicated ARGS. IS_FRIEND indicates whether the specialization
1492 is actually just a friend declaration. ATTRLIST is the list of
1493 attributes that the specialization is declared with or NULL when
1494 it isn't. Returns SPEC, or an equivalent prior declaration, if
1495 available.
1497 We also store instantiations of field packs in the hash table, even
1498 though they are not themselves templates, to make lookup easier. */
1500 static tree
1501 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1502 hashval_t hash)
1504 tree fn;
1506 gcc_assert ((TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec))
1507 || (TREE_CODE (tmpl) == FIELD_DECL
1508 && TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK));
1510 if (TREE_CODE (spec) == FUNCTION_DECL
1511 && uses_template_parms (DECL_TI_ARGS (spec)))
1512 /* This is the FUNCTION_DECL for a partial instantiation. Don't
1513 register it; we want the corresponding TEMPLATE_DECL instead.
1514 We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1515 the more obvious `uses_template_parms (spec)' to avoid problems
1516 with default function arguments. In particular, given
1517 something like this:
1519 template <class T> void f(T t1, T t = T())
1521 the default argument expression is not substituted for in an
1522 instantiation unless and until it is actually needed. */
1523 return spec;
1525 spec_entry elt;
1526 elt.tmpl = tmpl;
1527 elt.args = args;
1528 elt.spec = spec;
1530 if (hash == 0)
1531 hash = spec_hasher::hash (&elt);
1533 spec_entry **slot = decl_specializations->find_slot_with_hash (&elt, hash, INSERT);
1534 if (*slot)
1535 fn = (*slot)->spec;
1536 else
1537 fn = NULL_TREE;
1539 /* We can sometimes try to re-register a specialization that we've
1540 already got. In particular, regenerate_decl_from_template calls
1541 duplicate_decls which will update the specialization list. But,
1542 we'll still get called again here anyhow. It's more convenient
1543 to simply allow this than to try to prevent it. */
1544 if (fn == spec)
1545 return spec;
1546 else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1548 if (DECL_TEMPLATE_INSTANTIATION (fn))
1550 if (DECL_ODR_USED (fn)
1551 || DECL_EXPLICIT_INSTANTIATION (fn))
1553 error ("specialization of %qD after instantiation",
1554 fn);
1555 return error_mark_node;
1557 else
1559 tree clone;
1560 /* This situation should occur only if the first
1561 specialization is an implicit instantiation, the
1562 second is an explicit specialization, and the
1563 implicit instantiation has not yet been used. That
1564 situation can occur if we have implicitly
1565 instantiated a member function and then specialized
1566 it later.
1568 We can also wind up here if a friend declaration that
1569 looked like an instantiation turns out to be a
1570 specialization:
1572 template <class T> void foo(T);
1573 class S { friend void foo<>(int) };
1574 template <> void foo(int);
1576 We transform the existing DECL in place so that any
1577 pointers to it become pointers to the updated
1578 declaration.
1580 If there was a definition for the template, but not
1581 for the specialization, we want this to look as if
1582 there were no definition, and vice versa. */
1583 DECL_INITIAL (fn) = NULL_TREE;
1584 duplicate_decls (spec, fn, /*hiding=*/is_friend);
1586 /* The call to duplicate_decls will have applied
1587 [temp.expl.spec]:
1589 An explicit specialization of a function template
1590 is inline only if it is explicitly declared to be,
1591 and independently of whether its function template
1594 to the primary function; now copy the inline bits to
1595 the various clones. */
1596 FOR_EACH_CLONE (clone, fn)
1598 DECL_DECLARED_INLINE_P (clone)
1599 = DECL_DECLARED_INLINE_P (fn);
1600 DECL_SOURCE_LOCATION (clone)
1601 = DECL_SOURCE_LOCATION (fn);
1602 DECL_DELETED_FN (clone)
1603 = DECL_DELETED_FN (fn);
1605 check_specialization_namespace (tmpl);
1607 return fn;
1610 else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1612 tree dd = duplicate_decls (spec, fn, /*hiding=*/is_friend);
1613 if (dd == error_mark_node)
1614 /* We've already complained in duplicate_decls. */
1615 return error_mark_node;
1617 if (dd == NULL_TREE && DECL_INITIAL (spec))
1618 /* Dup decl failed, but this is a new definition. Set the
1619 line number so any errors match this new
1620 definition. */
1621 DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1623 return fn;
1626 else if (fn)
1627 return duplicate_decls (spec, fn, /*hiding=*/is_friend);
1629 /* A specialization must be declared in the same namespace as the
1630 template it is specializing. */
1631 if (DECL_P (spec) && DECL_TEMPLATE_SPECIALIZATION (spec)
1632 && !check_specialization_namespace (tmpl))
1633 DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1635 spec_entry *entry = ggc_alloc<spec_entry> ();
1636 gcc_assert (tmpl && args && spec);
1637 *entry = elt;
1638 *slot = entry;
1639 if ((TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1640 && PRIMARY_TEMPLATE_P (tmpl)
1641 && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1642 || variable_template_p (tmpl))
1643 /* If TMPL is a forward declaration of a template function, keep a list
1644 of all specializations in case we need to reassign them to a friend
1645 template later in tsubst_friend_function.
1647 Also keep a list of all variable template instantiations so that
1648 process_partial_specialization can check whether a later partial
1649 specialization would have used it. */
1650 DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1651 = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1653 return spec;
1656 /* Restricts tree and type comparisons. */
1657 int comparing_specializations;
1658 int comparing_dependent_aliases;
1660 /* Returns true iff two spec_entry nodes are equivalent. */
1662 bool
1663 spec_hasher::equal (spec_entry *e1, spec_entry *e2)
1665 int equal;
1667 ++comparing_specializations;
1668 ++comparing_dependent_aliases;
1669 ++processing_template_decl;
1670 equal = (e1->tmpl == e2->tmpl
1671 && comp_template_args (e1->args, e2->args));
1672 if (equal && flag_concepts
1673 /* tmpl could be a FIELD_DECL for a capture pack. */
1674 && TREE_CODE (e1->tmpl) == TEMPLATE_DECL
1675 && VAR_P (DECL_TEMPLATE_RESULT (e1->tmpl))
1676 && uses_template_parms (e1->args))
1678 /* Partial specializations of a variable template can be distinguished by
1679 constraints. */
1680 tree c1 = e1->spec ? get_constraints (e1->spec) : NULL_TREE;
1681 tree c2 = e2->spec ? get_constraints (e2->spec) : NULL_TREE;
1682 equal = equivalent_constraints (c1, c2);
1684 --processing_template_decl;
1685 --comparing_dependent_aliases;
1686 --comparing_specializations;
1688 return equal;
1691 /* Returns a hash for a template TMPL and template arguments ARGS. */
1693 static hashval_t
1694 hash_tmpl_and_args (tree tmpl, tree args)
1696 hashval_t val = iterative_hash_object (DECL_UID (tmpl), 0);
1697 return iterative_hash_template_arg (args, val);
1700 hashval_t
1701 spec_hasher::hash (tree tmpl, tree args)
1703 ++comparing_specializations;
1704 hashval_t val = hash_tmpl_and_args (tmpl, args);
1705 --comparing_specializations;
1706 return val;
1709 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1710 ignoring SPEC. */
1712 hashval_t
1713 spec_hasher::hash (spec_entry *e)
1715 return spec_hasher::hash (e->tmpl, e->args);
1718 /* Recursively calculate a hash value for a template argument ARG, for use
1719 in the hash tables of template specializations. We must be
1720 careful to (at least) skip the same entities template_args_equal
1721 does. */
1723 hashval_t
1724 iterative_hash_template_arg (tree arg, hashval_t val)
1726 if (arg == NULL_TREE)
1727 return iterative_hash_object (arg, val);
1729 if (!TYPE_P (arg))
1730 /* Strip nop-like things, but not the same as STRIP_NOPS. */
1731 while (CONVERT_EXPR_P (arg)
1732 || TREE_CODE (arg) == NON_LVALUE_EXPR
1733 || class_nttp_const_wrapper_p (arg))
1734 arg = TREE_OPERAND (arg, 0);
1736 enum tree_code code = TREE_CODE (arg);
1738 val = iterative_hash_object (code, val);
1740 switch (code)
1742 case ARGUMENT_PACK_SELECT:
1743 /* Getting here with an ARGUMENT_PACK_SELECT means we're probably
1744 preserving it in a hash table, which is bad because it will change
1745 meaning when gen_elem_of_pack_expansion_instantiation changes the
1746 ARGUMENT_PACK_SELECT_INDEX. */
1747 gcc_unreachable ();
1749 case ERROR_MARK:
1750 return val;
1752 case IDENTIFIER_NODE:
1753 return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1755 case TREE_VEC:
1756 for (tree elt : tree_vec_range (arg))
1757 val = iterative_hash_template_arg (elt, val);
1758 return val;
1760 case TYPE_PACK_EXPANSION:
1761 case EXPR_PACK_EXPANSION:
1762 val = iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1763 return iterative_hash_template_arg (PACK_EXPANSION_EXTRA_ARGS (arg), val);
1765 case TYPE_ARGUMENT_PACK:
1766 case NONTYPE_ARGUMENT_PACK:
1767 return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1769 case TREE_LIST:
1770 for (; arg; arg = TREE_CHAIN (arg))
1771 val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1772 return val;
1774 case OVERLOAD:
1775 for (lkp_iterator iter (arg); iter; ++iter)
1776 val = iterative_hash_template_arg (*iter, val);
1777 return val;
1779 case CONSTRUCTOR:
1781 iterative_hash_template_arg (TREE_TYPE (arg), val);
1782 for (auto &e: CONSTRUCTOR_ELTS (arg))
1784 val = iterative_hash_template_arg (e.index, val);
1785 val = iterative_hash_template_arg (e.value, val);
1787 return val;
1790 case PARM_DECL:
1791 if (!DECL_ARTIFICIAL (arg))
1793 val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1794 val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
1796 return iterative_hash_template_arg (TREE_TYPE (arg), val);
1798 case TARGET_EXPR:
1799 return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1801 case PTRMEM_CST:
1802 val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1803 return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1805 case TEMPLATE_PARM_INDEX:
1806 val = iterative_hash_template_arg
1807 (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1808 val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1809 return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1811 case TRAIT_EXPR:
1812 val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1813 val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1814 return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1816 case BASELINK:
1817 val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1818 val);
1819 return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1820 val);
1822 case MODOP_EXPR:
1823 val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1824 code = TREE_CODE (TREE_OPERAND (arg, 1));
1825 val = iterative_hash_object (code, val);
1826 return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1828 case LAMBDA_EXPR:
1829 /* [temp.over.link] Two lambda-expressions are never considered
1830 equivalent.
1832 So just hash the closure type. */
1833 return iterative_hash_template_arg (TREE_TYPE (arg), val);
1835 case CAST_EXPR:
1836 case IMPLICIT_CONV_EXPR:
1837 case STATIC_CAST_EXPR:
1838 case REINTERPRET_CAST_EXPR:
1839 case CONST_CAST_EXPR:
1840 case DYNAMIC_CAST_EXPR:
1841 case NEW_EXPR:
1842 val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1843 /* Now hash operands as usual. */
1844 break;
1846 case CALL_EXPR:
1848 tree fn = CALL_EXPR_FN (arg);
1849 if (tree name = call_expr_dependent_name (arg))
1851 if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
1852 val = iterative_hash_template_arg (TREE_OPERAND (fn, 1), val);
1853 fn = name;
1855 val = iterative_hash_template_arg (fn, val);
1856 call_expr_arg_iterator ai;
1857 for (tree x = first_call_expr_arg (arg, &ai); x;
1858 x = next_call_expr_arg (&ai))
1859 val = iterative_hash_template_arg (x, val);
1860 return val;
1863 default:
1864 break;
1867 char tclass = TREE_CODE_CLASS (code);
1868 switch (tclass)
1870 case tcc_type:
1871 if (tree ats = alias_template_specialization_p (arg, nt_transparent))
1873 // We want an alias specialization that survived strip_typedefs
1874 // to hash differently from its TYPE_CANONICAL, to avoid hash
1875 // collisions that compare as different in template_args_equal.
1876 // These could be dependent specializations that strip_typedefs
1877 // left alone, or untouched specializations because
1878 // coerce_template_parms returns the unconverted template
1879 // arguments if it sees incomplete argument packs.
1880 tree ti = TYPE_ALIAS_TEMPLATE_INFO (ats);
1881 return hash_tmpl_and_args (TI_TEMPLATE (ti), TI_ARGS (ti));
1884 switch (code)
1886 case DECLTYPE_TYPE:
1887 val = iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1888 break;
1890 case TYPENAME_TYPE:
1891 if (comparing_specializations)
1893 /* Hash the components that are relevant to TYPENAME_TYPE
1894 equivalence as determined by structural_comptypes. We
1895 can only coherently do this when comparing_specializations
1896 is set, because otherwise structural_comptypes tries
1897 resolving TYPENAME_TYPE via the current instantiation. */
1898 tree context = TYPE_MAIN_VARIANT (TYPE_CONTEXT (arg));
1899 tree fullname = TYPENAME_TYPE_FULLNAME (arg);
1900 val = iterative_hash_template_arg (context, val);
1901 val = iterative_hash_template_arg (fullname, val);
1903 break;
1905 default:
1906 if (tree canonical = TYPE_CANONICAL (arg))
1907 val = iterative_hash_object (TYPE_HASH (canonical), val);
1908 break;
1911 return val;
1913 case tcc_declaration:
1914 case tcc_constant:
1915 return iterative_hash_expr (arg, val);
1917 default:
1918 gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1919 for (int i = 0, n = cp_tree_operand_length (arg); i < n; ++i)
1920 val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1921 return val;
1925 /* Unregister the specialization SPEC as a specialization of TMPL.
1926 Replace it with NEW_SPEC, if NEW_SPEC is non-NULL. Returns true
1927 if the SPEC was listed as a specialization of TMPL.
1929 Note that SPEC has been ggc_freed, so we can't look inside it. */
1931 bool
1932 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1934 spec_entry *entry;
1935 spec_entry elt;
1937 elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1938 elt.args = TI_ARGS (tinfo);
1939 elt.spec = NULL_TREE;
1941 entry = decl_specializations->find (&elt);
1942 if (entry != NULL)
1944 gcc_assert (entry->spec == spec || entry->spec == new_spec);
1945 gcc_assert (new_spec != NULL_TREE);
1946 entry->spec = new_spec;
1947 return 1;
1950 return 0;
1953 /* Like register_specialization, but for local declarations. We are
1954 registering SPEC, an instantiation of TMPL. */
1956 void
1957 register_local_specialization (tree spec, tree tmpl)
1959 gcc_assert (tmpl != spec);
1960 local_specializations->put (tmpl, spec);
1963 /* Registers T as a specialization of itself. This is used to preserve
1964 the references to already-parsed parameters when instantiating
1965 postconditions. */
1967 void
1968 register_local_identity (tree t)
1970 local_specializations->put (t, t);
1973 /* TYPE is a class type. Returns true if TYPE is an explicitly
1974 specialized class. */
1976 bool
1977 explicit_class_specialization_p (tree type)
1979 if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1980 return false;
1981 return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1984 /* Print the list of functions at FNS, going through all the overloads
1985 for each element of the list. Alternatively, FNS cannot be a
1986 TREE_LIST, in which case it will be printed together with all the
1987 overloads.
1989 MORE and *STR should respectively be FALSE and NULL when the function
1990 is called from the outside. They are used internally on recursive
1991 calls. print_candidates manages the two parameters and leaves NULL
1992 in *STR when it ends. */
1994 static void
1995 print_candidates_1 (tree fns, char **str, bool more = false)
1997 if (TREE_CODE (fns) == TREE_LIST)
1998 for (; fns; fns = TREE_CHAIN (fns))
1999 print_candidates_1 (TREE_VALUE (fns), str, more || TREE_CHAIN (fns));
2000 else
2001 for (lkp_iterator iter (fns); iter;)
2003 tree cand = *iter;
2004 ++iter;
2006 const char *pfx = *str;
2007 if (!pfx)
2009 if (more || iter)
2010 pfx = _("candidates are:");
2011 else
2012 pfx = _("candidate is:");
2013 *str = get_spaces (pfx);
2015 inform (DECL_SOURCE_LOCATION (cand), "%s %#qD", pfx, cand);
2019 /* Print the list of candidate FNS in an error message. FNS can also
2020 be a TREE_LIST of non-functions in the case of an ambiguous lookup. */
2022 void
2023 print_candidates (tree fns)
2025 char *str = NULL;
2026 print_candidates_1 (fns, &str);
2027 free (str);
2030 /* Get a (possibly) constrained template declaration for the
2031 purpose of ordering candidates. */
2032 static tree
2033 get_template_for_ordering (tree list)
2035 gcc_assert (TREE_CODE (list) == TREE_LIST);
2036 tree f = TREE_VALUE (list);
2037 if (tree ti = DECL_TEMPLATE_INFO (f))
2038 return TI_TEMPLATE (ti);
2039 return f;
2042 /* Among candidates having the same signature, return the
2043 most constrained or NULL_TREE if there is no best candidate.
2044 If the signatures of candidates vary (e.g., template
2045 specialization vs. member function), then there can be no
2046 most constrained.
2048 Note that we don't compare constraints on the functions
2049 themselves, but rather those of their templates. */
2050 static tree
2051 most_constrained_function (tree candidates)
2053 // Try to find the best candidate in a first pass.
2054 tree champ = candidates;
2055 for (tree c = TREE_CHAIN (champ); c; c = TREE_CHAIN (c))
2057 int winner = more_constrained (get_template_for_ordering (champ),
2058 get_template_for_ordering (c));
2059 if (winner == -1)
2060 champ = c; // The candidate is more constrained
2061 else if (winner == 0)
2062 return NULL_TREE; // Neither is more constrained
2065 // Verify that the champ is better than previous candidates.
2066 for (tree c = candidates; c != champ; c = TREE_CHAIN (c)) {
2067 if (!more_constrained (get_template_for_ordering (champ),
2068 get_template_for_ordering (c)))
2069 return NULL_TREE;
2072 return champ;
2076 /* Returns the template (one of the functions given by TEMPLATE_ID)
2077 which can be specialized to match the indicated DECL with the
2078 explicit template args given in TEMPLATE_ID. The DECL may be
2079 NULL_TREE if none is available. In that case, the functions in
2080 TEMPLATE_ID are non-members.
2082 If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
2083 specialization of a member template.
2085 The TEMPLATE_COUNT is the number of references to qualifying
2086 template classes that appeared in the name of the function. See
2087 check_explicit_specialization for a more accurate description.
2089 TSK indicates what kind of template declaration (if any) is being
2090 declared. TSK_TEMPLATE indicates that the declaration given by
2091 DECL, though a FUNCTION_DECL, has template parameters, and is
2092 therefore a template function.
2094 The template args (those explicitly specified and those deduced)
2095 are output in a newly created vector *TARGS_OUT.
2097 If it is impossible to determine the result, an error message is
2098 issued. The error_mark_node is returned to indicate failure. */
2100 static tree
2101 determine_specialization (tree template_id,
2102 tree decl,
2103 tree* targs_out,
2104 int need_member_template,
2105 int template_count,
2106 tmpl_spec_kind tsk)
2108 tree fns;
2109 tree targs;
2110 tree explicit_targs;
2111 tree candidates = NULL_TREE;
2113 /* A TREE_LIST of templates of which DECL may be a specialization.
2114 The TREE_VALUE of each node is a TEMPLATE_DECL. The
2115 corresponding TREE_PURPOSE is the set of template arguments that,
2116 when used to instantiate the template, would produce a function
2117 with the signature of DECL. */
2118 tree templates = NULL_TREE;
2119 int header_count;
2120 cp_binding_level *b;
2122 *targs_out = NULL_TREE;
2124 if (template_id == error_mark_node || decl == error_mark_node)
2125 return error_mark_node;
2127 /* We shouldn't be specializing a member template of an
2128 unspecialized class template; we already gave an error in
2129 check_specialization_scope, now avoid crashing. */
2130 if (!VAR_P (decl)
2131 && template_count && DECL_CLASS_SCOPE_P (decl)
2132 && template_class_depth (DECL_CONTEXT (decl)) > 0)
2134 gcc_assert (errorcount);
2135 return error_mark_node;
2138 fns = TREE_OPERAND (template_id, 0);
2139 explicit_targs = TREE_OPERAND (template_id, 1);
2141 if (fns == error_mark_node)
2142 return error_mark_node;
2144 /* Check for baselinks. */
2145 if (BASELINK_P (fns))
2146 fns = BASELINK_FUNCTIONS (fns);
2148 if (TREE_CODE (decl) == FUNCTION_DECL && !is_overloaded_fn (fns))
2150 error_at (DECL_SOURCE_LOCATION (decl),
2151 "%qD is not a function template", fns);
2152 return error_mark_node;
2154 else if (VAR_P (decl) && !variable_template_p (fns))
2156 error ("%qD is not a variable template", fns);
2157 return error_mark_node;
2160 /* Count the number of template headers specified for this
2161 specialization. */
2162 header_count = 0;
2163 for (b = current_binding_level;
2164 b->kind == sk_template_parms;
2165 b = b->level_chain)
2166 ++header_count;
2168 tree orig_fns = fns;
2169 bool header_mismatch = false;
2171 if (variable_template_p (fns))
2173 tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (fns));
2174 targs = coerce_template_parms (parms, explicit_targs, fns,
2175 tf_warning_or_error);
2176 if (targs != error_mark_node
2177 && constraints_satisfied_p (fns, targs))
2178 templates = tree_cons (targs, fns, templates);
2180 else for (lkp_iterator iter (fns); iter; ++iter)
2182 tree fn = *iter;
2184 if (TREE_CODE (fn) == TEMPLATE_DECL)
2186 tree decl_arg_types;
2187 tree fn_arg_types;
2189 /* In case of explicit specialization, we need to check if
2190 the number of template headers appearing in the specialization
2191 is correct. This is usually done in check_explicit_specialization,
2192 but the check done there cannot be exhaustive when specializing
2193 member functions. Consider the following code:
2195 template <> void A<int>::f(int);
2196 template <> template <> void A<int>::f(int);
2198 Assuming that A<int> is not itself an explicit specialization
2199 already, the first line specializes "f" which is a non-template
2200 member function, whilst the second line specializes "f" which
2201 is a template member function. So both lines are syntactically
2202 correct, and check_explicit_specialization does not reject
2203 them.
2205 Here, we can do better, as we are matching the specialization
2206 against the declarations. We count the number of template
2207 headers, and we check if they match TEMPLATE_COUNT + 1
2208 (TEMPLATE_COUNT is the number of qualifying template classes,
2209 plus there must be another header for the member template
2210 itself).
2212 Notice that if header_count is zero, this is not a
2213 specialization but rather a template instantiation, so there
2214 is no check we can perform here. */
2215 if (header_count && header_count != template_count + 1)
2217 header_mismatch = true;
2218 continue;
2221 /* Check that the number of template arguments at the
2222 innermost level for DECL is the same as for FN. */
2223 if (current_binding_level->kind == sk_template_parms
2224 && !current_binding_level->explicit_spec_p
2225 && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
2226 != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
2227 (current_template_parms))))
2228 continue;
2230 /* DECL might be a specialization of FN. */
2231 decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2232 fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
2234 /* For a non-static member function, we need to make sure
2235 that the const qualification is the same. Since
2236 get_bindings does not try to merge the "this" parameter,
2237 we must do the comparison explicitly. */
2238 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn))
2240 if (!same_type_p (TREE_VALUE (fn_arg_types),
2241 TREE_VALUE (decl_arg_types)))
2242 continue;
2244 /* And the ref-qualification. */
2245 if (type_memfn_rqual (TREE_TYPE (decl))
2246 != type_memfn_rqual (TREE_TYPE (fn)))
2247 continue;
2250 /* Skip the "this" parameter and, for constructors of
2251 classes with virtual bases, the VTT parameter. A
2252 full specialization of a constructor will have a VTT
2253 parameter, but a template never will. */
2254 decl_arg_types
2255 = skip_artificial_parms_for (decl, decl_arg_types);
2256 fn_arg_types
2257 = skip_artificial_parms_for (fn, fn_arg_types);
2259 /* Function templates cannot be specializations; there are
2260 no partial specializations of functions. Therefore, if
2261 the type of DECL does not match FN, there is no
2262 match.
2264 Note that it should never be the case that we have both
2265 candidates added here, and for regular member functions
2266 below. */
2267 if (tsk == tsk_template)
2269 if (!comp_template_parms (DECL_TEMPLATE_PARMS (fn),
2270 current_template_parms))
2271 continue;
2272 if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2273 TREE_TYPE (TREE_TYPE (fn))))
2274 continue;
2275 if (!compparms (fn_arg_types, decl_arg_types))
2276 continue;
2278 tree freq = get_constraints (fn);
2279 tree dreq = get_constraints (decl);
2280 if (!freq != !dreq)
2281 continue;
2282 if (freq)
2284 /* C++20 CA104: Substitute directly into the
2285 constraint-expression. */
2286 tree fargs = DECL_TI_ARGS (fn);
2287 tsubst_flags_t complain = tf_none;
2288 freq = tsubst_constraint_info (freq, fargs, complain, fn);
2289 if (!cp_tree_equal (freq, dreq))
2290 continue;
2293 candidates = tree_cons (NULL_TREE, fn, candidates);
2294 continue;
2297 /* See whether this function might be a specialization of this
2298 template. Suppress access control because we might be trying
2299 to make this specialization a friend, and we have already done
2300 access control for the declaration of the specialization. */
2301 push_deferring_access_checks (dk_no_check);
2302 targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
2303 pop_deferring_access_checks ();
2305 if (!targs)
2306 /* We cannot deduce template arguments that when used to
2307 specialize TMPL will produce DECL. */
2308 continue;
2310 if (uses_template_parms (targs))
2311 /* We deduced something involving 'auto', which isn't a valid
2312 template argument. */
2313 continue;
2315 /* Save this template, and the arguments deduced. */
2316 templates = tree_cons (targs, fn, templates);
2318 else if (need_member_template)
2319 /* FN is an ordinary member function, and we need a
2320 specialization of a member template. */
2322 else if (TREE_CODE (fn) != FUNCTION_DECL)
2323 /* We can get IDENTIFIER_NODEs here in certain erroneous
2324 cases. */
2326 else if (!DECL_FUNCTION_MEMBER_P (fn))
2327 /* This is just an ordinary non-member function. Nothing can
2328 be a specialization of that. */
2330 else if (DECL_ARTIFICIAL (fn))
2331 /* Cannot specialize functions that are created implicitly. */
2333 else
2335 tree decl_arg_types;
2337 /* This is an ordinary member function. However, since
2338 we're here, we can assume its enclosing class is a
2339 template class. For example,
2341 template <typename T> struct S { void f(); };
2342 template <> void S<int>::f() {}
2344 Here, S<int>::f is a non-template, but S<int> is a
2345 template class. If FN has the same type as DECL, we
2346 might be in business. */
2348 if (!DECL_TEMPLATE_INFO (fn))
2349 /* Its enclosing class is an explicit specialization
2350 of a template class. This is not a candidate. */
2351 continue;
2353 if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2354 TREE_TYPE (TREE_TYPE (fn))))
2355 /* The return types differ. */
2356 continue;
2358 /* Adjust the type of DECL in case FN is a static member. */
2359 decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2360 if (DECL_STATIC_FUNCTION_P (fn)
2361 && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2362 decl_arg_types = TREE_CHAIN (decl_arg_types);
2364 if (!compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
2365 decl_arg_types))
2366 continue;
2368 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
2369 && (type_memfn_rqual (TREE_TYPE (decl))
2370 != type_memfn_rqual (TREE_TYPE (fn))))
2371 continue;
2373 // If the deduced arguments do not satisfy the constraints,
2374 // this is not a candidate.
2375 if (flag_concepts && !constraints_satisfied_p (fn))
2376 continue;
2378 // Add the candidate.
2379 candidates = tree_cons (NULL_TREE, fn, candidates);
2383 if (templates && TREE_CHAIN (templates))
2385 /* We have:
2387 [temp.expl.spec]
2389 It is possible for a specialization with a given function
2390 signature to be instantiated from more than one function
2391 template. In such cases, explicit specification of the
2392 template arguments must be used to uniquely identify the
2393 function template specialization being specialized.
2395 Note that here, there's no suggestion that we're supposed to
2396 determine which of the candidate templates is most
2397 specialized. However, we, also have:
2399 [temp.func.order]
2401 Partial ordering of overloaded function template
2402 declarations is used in the following contexts to select
2403 the function template to which a function template
2404 specialization refers:
2406 -- when an explicit specialization refers to a function
2407 template.
2409 So, we do use the partial ordering rules, at least for now.
2410 This extension can only serve to make invalid programs valid,
2411 so it's safe. And, there is strong anecdotal evidence that
2412 the committee intended the partial ordering rules to apply;
2413 the EDG front end has that behavior, and John Spicer claims
2414 that the committee simply forgot to delete the wording in
2415 [temp.expl.spec]. */
2416 tree tmpl = most_specialized_instantiation (templates);
2417 if (tmpl != error_mark_node)
2419 templates = tmpl;
2420 TREE_CHAIN (templates) = NULL_TREE;
2424 // Concepts allows multiple declarations of member functions
2425 // with the same signature. Like above, we need to rely on
2426 // on the partial ordering of those candidates to determine which
2427 // is the best.
2428 if (flag_concepts && candidates && TREE_CHAIN (candidates))
2430 if (tree cand = most_constrained_function (candidates))
2432 candidates = cand;
2433 TREE_CHAIN (cand) = NULL_TREE;
2437 if (templates == NULL_TREE && candidates == NULL_TREE)
2439 error ("template-id %qD for %q+D does not match any template "
2440 "declaration", template_id, decl);
2441 if (header_mismatch)
2442 inform (DECL_SOURCE_LOCATION (decl),
2443 "saw %d %<template<>%>, need %d for "
2444 "specializing a member function template",
2445 header_count, template_count + 1);
2446 print_candidates (orig_fns);
2447 return error_mark_node;
2449 else if ((templates && TREE_CHAIN (templates))
2450 || (candidates && TREE_CHAIN (candidates))
2451 || (templates && candidates))
2453 error ("ambiguous template specialization %qD for %q+D",
2454 template_id, decl);
2455 candidates = chainon (candidates, templates);
2456 print_candidates (candidates);
2457 return error_mark_node;
2460 /* We have one, and exactly one, match. */
2461 if (candidates)
2463 tree fn = TREE_VALUE (candidates);
2464 *targs_out = copy_node (DECL_TI_ARGS (fn));
2466 /* Propagate the candidate's constraints to the declaration. */
2467 if (tsk != tsk_template)
2468 set_constraints (decl, get_constraints (fn));
2470 /* DECL is a re-declaration or partial instantiation of a template
2471 function. */
2472 if (TREE_CODE (fn) == TEMPLATE_DECL)
2473 return fn;
2474 /* It was a specialization of an ordinary member function in a
2475 template class. */
2476 return DECL_TI_TEMPLATE (fn);
2479 /* It was a specialization of a template. */
2480 tree tmpl = TREE_VALUE (templates);
2481 *targs_out = add_outermost_template_args (tmpl, TREE_PURPOSE (templates));
2483 /* Propagate the template's constraints to the declaration. */
2484 if (tsk != tsk_template)
2485 set_constraints (decl, get_constraints (tmpl));
2487 return tmpl;
2490 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2491 but with the default argument values filled in from those in the
2492 TMPL_TYPES. */
2494 static tree
2495 copy_default_args_to_explicit_spec_1 (tree spec_types,
2496 tree tmpl_types)
2498 tree new_spec_types;
2500 if (!spec_types)
2501 return NULL_TREE;
2503 if (spec_types == void_list_node)
2504 return void_list_node;
2506 /* Substitute into the rest of the list. */
2507 new_spec_types =
2508 copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2509 TREE_CHAIN (tmpl_types));
2511 /* Add the default argument for this parameter. */
2512 return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2513 TREE_VALUE (spec_types),
2514 new_spec_types);
2517 /* DECL is an explicit specialization. Replicate default arguments
2518 from the template it specializes. (That way, code like:
2520 template <class T> void f(T = 3);
2521 template <> void f(double);
2522 void g () { f (); }
2524 works, as required.) An alternative approach would be to look up
2525 the correct default arguments at the call-site, but this approach
2526 is consistent with how implicit instantiations are handled. */
2528 static void
2529 copy_default_args_to_explicit_spec (tree decl)
2531 tree tmpl;
2532 tree spec_types;
2533 tree tmpl_types;
2534 tree new_spec_types;
2535 tree old_type;
2536 tree new_type;
2537 tree t;
2538 tree object_type = NULL_TREE;
2539 tree in_charge = NULL_TREE;
2540 tree vtt = NULL_TREE;
2542 /* See if there's anything we need to do. */
2543 tmpl = DECL_TI_TEMPLATE (decl);
2544 tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2545 for (t = tmpl_types; t; t = TREE_CHAIN (t))
2546 if (TREE_PURPOSE (t))
2547 break;
2548 if (!t)
2549 return;
2551 old_type = TREE_TYPE (decl);
2552 spec_types = TYPE_ARG_TYPES (old_type);
2554 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2556 /* Remove the this pointer, but remember the object's type for
2557 CV quals. */
2558 object_type = TREE_TYPE (TREE_VALUE (spec_types));
2559 spec_types = TREE_CHAIN (spec_types);
2560 tmpl_types = TREE_CHAIN (tmpl_types);
2562 if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2564 /* DECL may contain more parameters than TMPL due to the extra
2565 in-charge parameter in constructors and destructors. */
2566 in_charge = spec_types;
2567 spec_types = TREE_CHAIN (spec_types);
2569 if (DECL_HAS_VTT_PARM_P (decl))
2571 vtt = spec_types;
2572 spec_types = TREE_CHAIN (spec_types);
2576 /* Compute the merged default arguments. */
2577 new_spec_types =
2578 copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2580 /* Compute the new FUNCTION_TYPE. */
2581 if (object_type)
2583 if (vtt)
2584 new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2585 TREE_VALUE (vtt),
2586 new_spec_types);
2588 if (in_charge)
2589 /* Put the in-charge parameter back. */
2590 new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2591 TREE_VALUE (in_charge),
2592 new_spec_types);
2594 new_type = build_method_type_directly (object_type,
2595 TREE_TYPE (old_type),
2596 new_spec_types);
2598 else
2599 new_type = build_function_type (TREE_TYPE (old_type),
2600 new_spec_types);
2601 new_type = cp_build_type_attribute_variant (new_type,
2602 TYPE_ATTRIBUTES (old_type));
2603 new_type = cxx_copy_lang_qualifiers (new_type, old_type);
2605 TREE_TYPE (decl) = new_type;
2608 /* Return the number of template headers we expect to see for a definition
2609 or specialization of CTYPE or one of its non-template members. */
2612 num_template_headers_for_class (tree ctype)
2614 int num_templates = 0;
2616 while (ctype && CLASS_TYPE_P (ctype))
2618 /* You're supposed to have one `template <...>' for every
2619 template class, but you don't need one for a full
2620 specialization. For example:
2622 template <class T> struct S{};
2623 template <> struct S<int> { void f(); };
2624 void S<int>::f () {}
2626 is correct; there shouldn't be a `template <>' for the
2627 definition of `S<int>::f'. */
2628 if (!CLASSTYPE_TEMPLATE_INFO (ctype))
2629 /* If CTYPE does not have template information of any
2630 kind, then it is not a template, nor is it nested
2631 within a template. */
2632 break;
2633 if (explicit_class_specialization_p (ctype))
2634 break;
2635 if (PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (ctype)))
2636 ++num_templates;
2638 ctype = TYPE_CONTEXT (ctype);
2641 return num_templates;
2644 /* Do a simple sanity check on the template headers that precede the
2645 variable declaration DECL. */
2647 void
2648 check_template_variable (tree decl)
2650 tree ctx = CP_DECL_CONTEXT (decl);
2651 int wanted = num_template_headers_for_class (ctx);
2652 if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)
2653 && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl)))
2655 if (cxx_dialect < cxx14)
2656 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wc__14_extensions,
2657 "variable templates only available with "
2658 "%<-std=c++14%> or %<-std=gnu++14%>");
2660 // Namespace-scope variable templates should have a template header.
2661 ++wanted;
2663 if (template_header_count > wanted)
2665 auto_diagnostic_group d;
2666 bool warned = pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2667 "too many template headers for %qD "
2668 "(should be %d)",
2669 decl, wanted);
2670 if (warned && CLASS_TYPE_P (ctx)
2671 && CLASSTYPE_TEMPLATE_SPECIALIZATION (ctx))
2672 inform (DECL_SOURCE_LOCATION (decl),
2673 "members of an explicitly specialized class are defined "
2674 "without a template header");
2678 /* An explicit specialization whose declarator-id or class-head-name is not
2679 qualified shall be declared in the nearest enclosing namespace of the
2680 template, or, if the namespace is inline (7.3.1), any namespace from its
2681 enclosing namespace set.
2683 If the name declared in the explicit instantiation is an unqualified name,
2684 the explicit instantiation shall appear in the namespace where its template
2685 is declared or, if that namespace is inline (7.3.1), any namespace from its
2686 enclosing namespace set. */
2688 void
2689 check_unqualified_spec_or_inst (tree t, location_t loc)
2691 tree tmpl = most_general_template (t);
2692 if (DECL_NAMESPACE_SCOPE_P (tmpl)
2693 && !is_nested_namespace (current_namespace,
2694 CP_DECL_CONTEXT (tmpl), true))
2696 if (processing_specialization)
2697 permerror (loc, "explicit specialization of %qD outside its "
2698 "namespace must use a nested-name-specifier", tmpl);
2699 else if (processing_explicit_instantiation
2700 && cxx_dialect >= cxx11)
2701 /* This was allowed in C++98, so only pedwarn. */
2702 pedwarn (loc, OPT_Wpedantic, "explicit instantiation of %qD "
2703 "outside its namespace must use a nested-name-"
2704 "specifier", tmpl);
2708 /* Warn for a template specialization SPEC that is missing some of a set
2709 of function or type attributes that the template TEMPL is declared with.
2710 ATTRLIST is a list of additional attributes that SPEC should be taken
2711 to ultimately be declared with. */
2713 static void
2714 warn_spec_missing_attributes (tree tmpl, tree spec, tree attrlist)
2716 if (DECL_FUNCTION_TEMPLATE_P (tmpl))
2717 tmpl = DECL_TEMPLATE_RESULT (tmpl);
2719 /* Avoid warning if the difference between the primary and
2720 the specialization is not in one of the attributes below. */
2721 const char* const blacklist[] = {
2722 "alloc_align", "alloc_size", "assume_aligned", "format",
2723 "format_arg", "malloc", "nonnull", NULL
2726 /* Put together a list of the black listed attributes that the primary
2727 template is declared with that the specialization is not, in case
2728 it's not apparent from the most recent declaration of the primary. */
2729 pretty_printer str;
2730 unsigned nattrs = decls_mismatched_attributes (tmpl, spec, attrlist,
2731 blacklist, &str);
2733 if (!nattrs)
2734 return;
2736 auto_diagnostic_group d;
2737 if (warning_at (DECL_SOURCE_LOCATION (spec), OPT_Wmissing_attributes,
2738 "explicit specialization %q#D may be missing attributes",
2739 spec))
2740 inform (DECL_SOURCE_LOCATION (tmpl),
2741 nattrs > 1
2742 ? G_("missing primary template attributes %s")
2743 : G_("missing primary template attribute %s"),
2744 pp_formatted_text (&str));
2747 /* Check to see if the function just declared, as indicated in
2748 DECLARATOR, and in DECL, is a specialization of a function
2749 template. We may also discover that the declaration is an explicit
2750 instantiation at this point.
2752 Returns DECL, or an equivalent declaration that should be used
2753 instead if all goes well. Issues an error message if something is
2754 amiss. Returns error_mark_node if the error is not easily
2755 recoverable.
2757 FLAGS is a bitmask consisting of the following flags:
2759 2: The function has a definition.
2760 4: The function is a friend.
2762 The TEMPLATE_COUNT is the number of references to qualifying
2763 template classes that appeared in the name of the function. For
2764 example, in
2766 template <class T> struct S { void f(); };
2767 void S<int>::f();
2769 the TEMPLATE_COUNT would be 1. However, explicitly specialized
2770 classes are not counted in the TEMPLATE_COUNT, so that in
2772 template <class T> struct S {};
2773 template <> struct S<int> { void f(); }
2774 template <> void S<int>::f();
2776 the TEMPLATE_COUNT would be 0. (Note that this declaration is
2777 invalid; there should be no template <>.)
2779 If the function is a specialization, it is marked as such via
2780 DECL_TEMPLATE_SPECIALIZATION. Furthermore, its DECL_TEMPLATE_INFO
2781 is set up correctly, and it is added to the list of specializations
2782 for that template. */
2784 tree
2785 check_explicit_specialization (tree declarator,
2786 tree decl,
2787 int template_count,
2788 int flags,
2789 tree attrlist)
2791 int have_def = flags & 2;
2792 int is_friend = flags & 4;
2793 bool is_concept = flags & 8;
2794 int specialization = 0;
2795 int explicit_instantiation = 0;
2796 int member_specialization = 0;
2797 tree ctype = DECL_CLASS_CONTEXT (decl);
2798 tree dname = DECL_NAME (decl);
2799 tmpl_spec_kind tsk;
2801 if (is_friend)
2803 if (!processing_specialization)
2804 tsk = tsk_none;
2805 else
2806 tsk = tsk_excessive_parms;
2808 else
2809 tsk = current_tmpl_spec_kind (template_count);
2811 switch (tsk)
2813 case tsk_none:
2814 if (processing_specialization && !VAR_P (decl))
2816 specialization = 1;
2817 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2819 else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR
2820 || (DECL_LANG_SPECIFIC (decl)
2821 && DECL_IMPLICIT_INSTANTIATION (decl)))
2823 if (is_friend)
2824 /* This could be something like:
2826 template <class T> void f(T);
2827 class S { friend void f<>(int); } */
2828 specialization = 1;
2829 else
2831 /* This case handles bogus declarations like template <>
2832 template <class T> void f<int>(); */
2834 error_at (cp_expr_loc_or_input_loc (declarator),
2835 "template-id %qE in declaration of primary template",
2836 declarator);
2837 return decl;
2840 break;
2842 case tsk_invalid_member_spec:
2843 /* The error has already been reported in
2844 check_specialization_scope. */
2845 return error_mark_node;
2847 case tsk_invalid_expl_inst:
2848 error ("template parameter list used in explicit instantiation");
2850 /* Fall through. */
2852 case tsk_expl_inst:
2853 if (have_def)
2854 error ("definition provided for explicit instantiation");
2856 explicit_instantiation = 1;
2857 break;
2859 case tsk_excessive_parms:
2860 case tsk_insufficient_parms:
2861 if (tsk == tsk_excessive_parms)
2862 error ("too many template parameter lists in declaration of %qD",
2863 decl);
2864 else if (template_header_count)
2865 error("too few template parameter lists in declaration of %qD", decl);
2866 else
2867 error("explicit specialization of %qD must be introduced by "
2868 "%<template <>%>", decl);
2870 /* Fall through. */
2871 case tsk_expl_spec:
2872 if (is_concept)
2873 error ("explicit specialization declared %<concept%>");
2875 if (VAR_P (decl) && TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2876 /* In cases like template<> constexpr bool v = true;
2877 We'll give an error in check_template_variable. */
2878 break;
2880 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2881 if (ctype)
2882 member_specialization = 1;
2883 else
2884 specialization = 1;
2885 break;
2887 case tsk_template:
2888 if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2890 /* This case handles bogus declarations like template <>
2891 template <class T> void f<int>(); */
2893 if (!uses_template_parms (TREE_OPERAND (declarator, 1)))
2894 error_at (cp_expr_loc_or_input_loc (declarator),
2895 "template-id %qE in declaration of primary template",
2896 declarator);
2897 else if (variable_template_p (TREE_OPERAND (declarator, 0)))
2899 /* Partial specialization of variable template. */
2900 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2901 specialization = 1;
2902 goto ok;
2904 else if (cxx_dialect < cxx14)
2905 error_at (cp_expr_loc_or_input_loc (declarator),
2906 "non-type partial specialization %qE "
2907 "is not allowed", declarator);
2908 else
2909 error_at (cp_expr_loc_or_input_loc (declarator),
2910 "non-class, non-variable partial specialization %qE "
2911 "is not allowed", declarator);
2912 return decl;
2913 ok:;
2916 if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2917 /* This is a specialization of a member template, without
2918 specialization the containing class. Something like:
2920 template <class T> struct S {
2921 template <class U> void f (U);
2923 template <> template <class U> void S<int>::f(U) {}
2925 That's a specialization -- but of the entire template. */
2926 specialization = 1;
2927 break;
2929 default:
2930 gcc_unreachable ();
2933 if ((specialization || member_specialization)
2934 /* This doesn't apply to variable templates. */
2935 && FUNC_OR_METHOD_TYPE_P (TREE_TYPE (decl)))
2937 tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2938 for (; t; t = TREE_CHAIN (t))
2939 if (TREE_PURPOSE (t))
2941 permerror (input_location,
2942 "default argument specified in explicit specialization");
2943 break;
2947 if (specialization || member_specialization || explicit_instantiation)
2949 tree tmpl = NULL_TREE;
2950 tree targs = NULL_TREE;
2951 bool was_template_id = (TREE_CODE (declarator) == TEMPLATE_ID_EXPR);
2952 bool found_hidden = false;
2954 /* Make sure that the declarator is a TEMPLATE_ID_EXPR. */
2955 if (!was_template_id)
2957 tree fns;
2959 gcc_assert (identifier_p (declarator));
2960 if (ctype)
2961 fns = dname;
2962 else
2964 /* If there is no class context, the explicit instantiation
2965 must be at namespace scope. */
2966 gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2968 /* Find the namespace binding, using the declaration
2969 context. */
2970 fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2971 LOOK_want::NORMAL, true);
2972 if (fns == error_mark_node)
2974 /* If lookup fails, look for a friend declaration so we can
2975 give a better diagnostic. */
2976 fns = (lookup_qualified_name
2977 (CP_DECL_CONTEXT (decl), dname,
2978 LOOK_want::NORMAL | LOOK_want::HIDDEN_FRIEND,
2979 /*complain*/true));
2980 found_hidden = true;
2983 if (fns == error_mark_node || !is_overloaded_fn (fns))
2985 error ("%qD is not a template function", dname);
2986 fns = error_mark_node;
2990 declarator = lookup_template_function (fns, NULL_TREE);
2993 if (declarator == error_mark_node)
2994 return error_mark_node;
2996 if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2998 if (!explicit_instantiation)
2999 /* A specialization in class scope. This is invalid,
3000 but the error will already have been flagged by
3001 check_specialization_scope. */
3002 return error_mark_node;
3003 else
3005 /* It's not valid to write an explicit instantiation in
3006 class scope, e.g.:
3008 class C { template void f(); }
3010 This case is caught by the parser. However, on
3011 something like:
3013 template class C { void f(); };
3015 (which is invalid) we can get here. The error will be
3016 issued later. */
3020 return decl;
3022 else if (ctype != NULL_TREE
3023 && (identifier_p (TREE_OPERAND (declarator, 0))))
3025 // We'll match variable templates in start_decl.
3026 if (VAR_P (decl))
3027 return decl;
3029 /* Find the list of functions in ctype that have the same
3030 name as the declared function. */
3031 tree name = TREE_OPERAND (declarator, 0);
3033 if (constructor_name_p (name, ctype))
3035 if (DECL_CONSTRUCTOR_P (decl)
3036 ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
3037 : !CLASSTYPE_DESTRUCTOR (ctype))
3039 /* From [temp.expl.spec]:
3041 If such an explicit specialization for the member
3042 of a class template names an implicitly-declared
3043 special member function (clause _special_), the
3044 program is ill-formed.
3046 Similar language is found in [temp.explicit]. */
3047 error ("specialization of implicitly-declared special member function");
3048 return error_mark_node;
3051 name = DECL_NAME (decl);
3054 /* For a type-conversion operator, We might be looking for
3055 `operator int' which will be a specialization of
3056 `operator T'. Grab all the conversion operators, and
3057 then select from them. */
3058 tree fns = get_class_binding (ctype, IDENTIFIER_CONV_OP_P (name)
3059 ? conv_op_identifier : name);
3061 if (fns == NULL_TREE)
3063 error ("no member function %qD declared in %qT", name, ctype);
3064 return error_mark_node;
3066 else
3067 TREE_OPERAND (declarator, 0) = fns;
3070 /* Figure out what exactly is being specialized at this point.
3071 Note that for an explicit instantiation, even one for a
3072 member function, we cannot tell a priori whether the
3073 instantiation is for a member template, or just a member
3074 function of a template class. Even if a member template is
3075 being instantiated, the member template arguments may be
3076 elided if they can be deduced from the rest of the
3077 declaration. */
3078 tmpl = determine_specialization (declarator, decl,
3079 &targs,
3080 member_specialization,
3081 template_count,
3082 tsk);
3084 if (!tmpl || tmpl == error_mark_node)
3085 /* We couldn't figure out what this declaration was
3086 specializing. */
3087 return error_mark_node;
3088 else
3090 if (found_hidden && TREE_CODE (decl) == FUNCTION_DECL)
3092 auto_diagnostic_group d;
3093 if (pedwarn (DECL_SOURCE_LOCATION (decl), 0,
3094 "friend declaration %qD is not visible to "
3095 "explicit specialization", tmpl))
3096 inform (DECL_SOURCE_LOCATION (tmpl),
3097 "friend declaration here");
3100 if (!ctype && !is_friend
3101 && CP_DECL_CONTEXT (decl) == current_namespace)
3102 check_unqualified_spec_or_inst (tmpl, DECL_SOURCE_LOCATION (decl));
3104 tree gen_tmpl = most_general_template (tmpl);
3106 if (explicit_instantiation)
3108 /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
3109 is done by do_decl_instantiation later. */
3111 int arg_depth = TMPL_ARGS_DEPTH (targs);
3112 int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
3114 if (arg_depth > parm_depth)
3116 /* If TMPL is not the most general template (for
3117 example, if TMPL is a friend template that is
3118 injected into namespace scope), then there will
3119 be too many levels of TARGS. Remove some of them
3120 here. */
3121 int i;
3122 tree new_targs;
3124 new_targs = make_tree_vec (parm_depth);
3125 for (i = arg_depth - parm_depth; i < arg_depth; ++i)
3126 TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
3127 = TREE_VEC_ELT (targs, i);
3128 targs = new_targs;
3131 return instantiate_template (tmpl, targs, tf_error);
3134 /* If we thought that the DECL was a member function, but it
3135 turns out to be specializing a static member function,
3136 make DECL a static member function as well. */
3137 if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3138 && DECL_STATIC_FUNCTION_P (tmpl)
3139 && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
3140 revert_static_member_fn (decl);
3142 /* If this is a specialization of a member template of a
3143 template class, we want to return the TEMPLATE_DECL, not
3144 the specialization of it. */
3145 if (tsk == tsk_template && !was_template_id)
3147 tree result = DECL_TEMPLATE_RESULT (tmpl);
3148 SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3149 DECL_INITIAL (result) = NULL_TREE;
3150 if (have_def)
3152 tree parm;
3153 DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
3154 DECL_SOURCE_LOCATION (result)
3155 = DECL_SOURCE_LOCATION (decl);
3156 /* We want to use the argument list specified in the
3157 definition, not in the original declaration. */
3158 DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
3159 for (parm = DECL_ARGUMENTS (result); parm;
3160 parm = DECL_CHAIN (parm))
3161 DECL_CONTEXT (parm) = result;
3163 decl = register_specialization (tmpl, gen_tmpl, targs,
3164 is_friend, 0);
3165 remove_contract_attributes (result);
3166 return decl;
3169 /* Set up the DECL_TEMPLATE_INFO for DECL. */
3170 DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
3172 if (was_template_id)
3173 TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl)) = true;
3175 /* Inherit default function arguments from the template
3176 DECL is specializing. */
3177 if (DECL_FUNCTION_TEMPLATE_P (tmpl))
3178 copy_default_args_to_explicit_spec (decl);
3180 /* This specialization has the same protection as the
3181 template it specializes. */
3182 TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
3183 TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
3185 /* 7.1.1-1 [dcl.stc]
3187 A storage-class-specifier shall not be specified in an
3188 explicit specialization...
3190 The parser rejects these, so unless action is taken here,
3191 explicit function specializations will always appear with
3192 global linkage.
3194 The action recommended by the C++ CWG in response to C++
3195 defect report 605 is to make the storage class and linkage
3196 of the explicit specialization match the templated function:
3198 http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
3200 if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
3202 tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
3203 gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
3205 /* A concept cannot be specialized. */
3206 if (DECL_DECLARED_CONCEPT_P (tmpl_func))
3208 error ("explicit specialization of function concept %qD",
3209 gen_tmpl);
3210 return error_mark_node;
3213 /* This specialization has the same linkage and visibility as
3214 the function template it specializes. */
3215 TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
3216 if (! TREE_PUBLIC (decl))
3218 DECL_INTERFACE_KNOWN (decl) = 1;
3219 DECL_NOT_REALLY_EXTERN (decl) = 1;
3221 DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
3222 if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
3224 DECL_VISIBILITY_SPECIFIED (decl) = 1;
3225 DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
3229 /* If DECL is a friend declaration, declared using an
3230 unqualified name, the namespace associated with DECL may
3231 have been set incorrectly. For example, in:
3233 template <typename T> void f(T);
3234 namespace N {
3235 struct S { friend void f<int>(int); }
3238 we will have set the DECL_CONTEXT for the friend
3239 declaration to N, rather than to the global namespace. */
3240 if (DECL_NAMESPACE_SCOPE_P (decl))
3241 DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
3243 if (is_friend && !have_def)
3244 /* This is not really a declaration of a specialization.
3245 It's just the name of an instantiation. But, it's not
3246 a request for an instantiation, either. */
3247 SET_DECL_IMPLICIT_INSTANTIATION (decl);
3248 else if (TREE_CODE (decl) == FUNCTION_DECL)
3249 /* A specialization is not necessarily COMDAT. */
3250 DECL_COMDAT (decl) = (TREE_PUBLIC (decl)
3251 && DECL_DECLARED_INLINE_P (decl));
3252 else if (VAR_P (decl))
3253 DECL_COMDAT (decl) = false;
3255 /* If this is a full specialization, register it so that we can find
3256 it again. Partial specializations will be registered in
3257 process_partial_specialization. */
3258 if (!processing_template_decl)
3260 warn_spec_missing_attributes (gen_tmpl, decl, attrlist);
3262 decl = register_specialization (decl, gen_tmpl, targs,
3263 is_friend, 0);
3266 /* If this is a specialization, splice any contracts that may have
3267 been inherited from the template, removing them. */
3268 if (decl != error_mark_node && DECL_TEMPLATE_SPECIALIZATION (decl))
3269 remove_contract_attributes (decl);
3271 /* A 'structor should already have clones. */
3272 gcc_assert (decl == error_mark_node
3273 || variable_template_p (tmpl)
3274 || !(DECL_CONSTRUCTOR_P (decl)
3275 || DECL_DESTRUCTOR_P (decl))
3276 || DECL_CLONED_FUNCTION_P (DECL_CHAIN (decl)));
3280 return decl;
3283 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
3284 parameters. These are represented in the same format used for
3285 DECL_TEMPLATE_PARMS. */
3288 comp_template_parms (const_tree parms1, const_tree parms2)
3290 const_tree p1;
3291 const_tree p2;
3293 if (parms1 == parms2)
3294 return 1;
3296 for (p1 = parms1, p2 = parms2;
3297 p1 != NULL_TREE && p2 != NULL_TREE;
3298 p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
3300 tree t1 = TREE_VALUE (p1);
3301 tree t2 = TREE_VALUE (p2);
3302 int i;
3304 gcc_assert (TREE_CODE (t1) == TREE_VEC);
3305 gcc_assert (TREE_CODE (t2) == TREE_VEC);
3307 if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
3308 return 0;
3310 for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
3312 tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
3313 tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
3315 /* If either of the template parameters are invalid, assume
3316 they match for the sake of error recovery. */
3317 if (error_operand_p (parm1) || error_operand_p (parm2))
3318 return 1;
3320 if (TREE_CODE (parm1) != TREE_CODE (parm2))
3321 return 0;
3323 if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
3324 && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
3325 == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
3326 continue;
3327 else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
3328 return 0;
3332 if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
3333 /* One set of parameters has more parameters lists than the
3334 other. */
3335 return 0;
3337 return 1;
3340 /* Returns true if two template parameters are declared with
3341 equivalent constraints. */
3343 static bool
3344 template_parameter_constraints_equivalent_p (const_tree parm1, const_tree parm2)
3346 tree req1 = TREE_TYPE (parm1);
3347 tree req2 = TREE_TYPE (parm2);
3348 if (!req1 != !req2)
3349 return false;
3350 if (req1)
3351 return cp_tree_equal (req1, req2);
3352 return true;
3355 /* Returns true when two template parameters are equivalent. */
3357 static bool
3358 template_parameters_equivalent_p (const_tree parm1, const_tree parm2)
3360 tree decl1 = TREE_VALUE (parm1);
3361 tree decl2 = TREE_VALUE (parm2);
3363 /* If either of the template parameters are invalid, assume
3364 they match for the sake of error recovery. */
3365 if (error_operand_p (decl1) || error_operand_p (decl2))
3366 return true;
3368 /* ... they declare parameters of the same kind. */
3369 if (TREE_CODE (decl1) != TREE_CODE (decl2))
3370 return false;
3372 /* ... one parameter was introduced by a parameter declaration, then
3373 both are. This case arises as a result of eagerly rewriting declarations
3374 during parsing. */
3375 if (DECL_VIRTUAL_P (decl1) != DECL_VIRTUAL_P (decl2))
3376 return false;
3378 /* ... if either declares a pack, they both do. */
3379 if (template_parameter_pack_p (decl1) != template_parameter_pack_p (decl2))
3380 return false;
3382 if (TREE_CODE (decl1) == PARM_DECL)
3384 /* ... if they declare non-type parameters, the types are equivalent. */
3385 if (!same_type_p (TREE_TYPE (decl1), TREE_TYPE (decl2)))
3386 return false;
3388 else if (TREE_CODE (decl2) == TEMPLATE_DECL)
3390 /* ... if they declare template template parameters, their template
3391 parameter lists are equivalent. */
3392 if (!template_heads_equivalent_p (decl1, decl2))
3393 return false;
3396 /* ... if they are declared with a qualified-concept name, they both
3397 are, and those names are equivalent. */
3398 return template_parameter_constraints_equivalent_p (parm1, parm2);
3401 /* Returns true if two template parameters lists are equivalent.
3402 Two template parameter lists are equivalent if they have the
3403 same length and their corresponding parameters are equivalent.
3405 PARMS1 and PARMS2 are TREE_LISTs containing TREE_VECs: the
3406 data structure returned by DECL_TEMPLATE_PARMS.
3408 This is generally the same implementation as comp_template_parms
3409 except that it also the concept names and arguments used to
3410 introduce parameters. */
3412 static bool
3413 template_parameter_lists_equivalent_p (const_tree parms1, const_tree parms2)
3415 if (parms1 == parms2)
3416 return true;
3418 const_tree p1 = parms1;
3419 const_tree p2 = parms2;
3420 while (p1 != NULL_TREE && p2 != NULL_TREE)
3422 tree list1 = TREE_VALUE (p1);
3423 tree list2 = TREE_VALUE (p2);
3425 if (TREE_VEC_LENGTH (list1) != TREE_VEC_LENGTH (list2))
3426 return 0;
3428 for (int i = 0; i < TREE_VEC_LENGTH (list2); ++i)
3430 tree parm1 = TREE_VEC_ELT (list1, i);
3431 tree parm2 = TREE_VEC_ELT (list2, i);
3432 if (!template_parameters_equivalent_p (parm1, parm2))
3433 return false;
3436 p1 = TREE_CHAIN (p1);
3437 p2 = TREE_CHAIN (p2);
3440 if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
3441 return false;
3443 return true;
3446 /* Return true if the requires-clause of the template parameter lists are
3447 equivalent and false otherwise. */
3448 static bool
3449 template_requirements_equivalent_p (const_tree parms1, const_tree parms2)
3451 tree req1 = TEMPLATE_PARMS_CONSTRAINTS (parms1);
3452 tree req2 = TEMPLATE_PARMS_CONSTRAINTS (parms2);
3453 if ((req1 != NULL_TREE) != (req2 != NULL_TREE))
3454 return false;
3455 if (!cp_tree_equal (req1, req2))
3456 return false;
3457 return true;
3460 /* Returns true if two template heads are equivalent. 17.6.6.1p6:
3461 Two template heads are equivalent if their template parameter
3462 lists are equivalent and their requires clauses are equivalent.
3464 In pre-C++20, this is equivalent to calling comp_template_parms
3465 for the template parameters of TMPL1 and TMPL2. */
3467 bool
3468 template_heads_equivalent_p (const_tree tmpl1, const_tree tmpl2)
3470 tree parms1 = DECL_TEMPLATE_PARMS (tmpl1);
3471 tree parms2 = DECL_TEMPLATE_PARMS (tmpl2);
3473 /* Don't change the matching rules for pre-C++20. */
3474 if (cxx_dialect < cxx20)
3475 return comp_template_parms (parms1, parms2);
3477 /* ... have the same number of template parameters, and their
3478 corresponding parameters are equivalent. */
3479 if (!template_parameter_lists_equivalent_p (parms1, parms2))
3480 return false;
3482 /* ... if either has a requires-clause, they both do and their
3483 corresponding constraint-expressions are equivalent. */
3484 return template_requirements_equivalent_p (parms1, parms2);
3487 /* Determine whether PARM is a parameter pack. */
3489 bool
3490 template_parameter_pack_p (const_tree parm)
3492 /* Determine if we have a non-type template parameter pack. */
3493 if (TREE_CODE (parm) == PARM_DECL)
3494 return (DECL_TEMPLATE_PARM_P (parm)
3495 && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
3496 if (TREE_CODE (parm) == TEMPLATE_PARM_INDEX)
3497 return TEMPLATE_PARM_PARAMETER_PACK (parm);
3499 /* If this is a list of template parameters, we could get a
3500 TYPE_DECL or a TEMPLATE_DECL. */
3501 if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
3502 parm = TREE_TYPE (parm);
3504 /* Otherwise it must be a type template parameter. */
3505 return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
3506 || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
3507 && TEMPLATE_TYPE_PARAMETER_PACK (parm));
3510 /* Determine if T is a function parameter pack. */
3512 bool
3513 function_parameter_pack_p (const_tree t)
3515 if (t && TREE_CODE (t) == PARM_DECL)
3516 return DECL_PACK_P (t);
3517 return false;
3520 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
3521 PRIMARY_FUNC_TMPL_INST is a primary function template instantiation. */
3523 tree
3524 get_function_template_decl (const_tree primary_func_tmpl_inst)
3526 if (! primary_func_tmpl_inst
3527 || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
3528 || ! primary_template_specialization_p (primary_func_tmpl_inst))
3529 return NULL;
3531 return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
3534 /* Return true iff the function parameter PARAM_DECL was expanded
3535 from the function parameter pack PACK. */
3537 bool
3538 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
3540 if (DECL_ARTIFICIAL (param_decl)
3541 || !function_parameter_pack_p (pack))
3542 return false;
3544 /* The parameter pack and its pack arguments have the same
3545 DECL_PARM_INDEX. */
3546 return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
3549 /* Determine whether ARGS describes a variadic template args list,
3550 i.e., one that is terminated by a template argument pack. */
3552 static bool
3553 template_args_variadic_p (tree args)
3555 int nargs;
3556 tree last_parm;
3558 if (args == NULL_TREE)
3559 return false;
3561 args = INNERMOST_TEMPLATE_ARGS (args);
3562 nargs = TREE_VEC_LENGTH (args);
3564 if (nargs == 0)
3565 return false;
3567 last_parm = TREE_VEC_ELT (args, nargs - 1);
3569 return ARGUMENT_PACK_P (last_parm);
3572 /* Generate a new name for the parameter pack name NAME (an
3573 IDENTIFIER_NODE) that incorporates its */
3575 static tree
3576 make_ith_pack_parameter_name (tree name, int i)
3578 /* Munge the name to include the parameter index. */
3579 #define NUMBUF_LEN 128
3580 char numbuf[NUMBUF_LEN];
3581 char* newname;
3582 int newname_len;
3584 if (name == NULL_TREE)
3585 return name;
3586 snprintf (numbuf, NUMBUF_LEN, "%i", i);
3587 newname_len = IDENTIFIER_LENGTH (name)
3588 + strlen (numbuf) + 2;
3589 newname = (char*)alloca (newname_len);
3590 snprintf (newname, newname_len,
3591 "%s#%i", IDENTIFIER_POINTER (name), i);
3592 return get_identifier (newname);
3595 /* Return true if T is a primary function, class or alias template
3596 specialization, not including the template pattern. */
3598 bool
3599 primary_template_specialization_p (const_tree t)
3601 if (!t)
3602 return false;
3604 if (VAR_OR_FUNCTION_DECL_P (t))
3605 return (DECL_LANG_SPECIFIC (t)
3606 && DECL_USE_TEMPLATE (t)
3607 && DECL_TEMPLATE_INFO (t)
3608 && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t)));
3609 else if (CLASS_TYPE_P (t) && !TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
3610 return (CLASSTYPE_TEMPLATE_INFO (t)
3611 && CLASSTYPE_USE_TEMPLATE (t)
3612 && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)));
3613 else if (alias_template_specialization_p (t, nt_transparent))
3614 return true;
3615 return false;
3618 /* Return true if PARM is a template template parameter. */
3620 bool
3621 template_template_parameter_p (const_tree parm)
3623 return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
3626 /* Return true iff PARM is a DECL representing a type template
3627 parameter. */
3629 bool
3630 template_type_parameter_p (const_tree parm)
3632 return (parm
3633 && (TREE_CODE (parm) == TYPE_DECL
3634 || TREE_CODE (parm) == TEMPLATE_DECL)
3635 && DECL_TEMPLATE_PARM_P (parm));
3638 /* Return the template parameters of T if T is a
3639 primary template instantiation, NULL otherwise. */
3641 tree
3642 get_primary_template_innermost_parameters (const_tree t)
3644 tree parms = NULL, template_info = NULL;
3646 if ((template_info = get_template_info (t))
3647 && primary_template_specialization_p (t))
3648 parms = INNERMOST_TEMPLATE_PARMS
3649 (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
3651 return parms;
3654 /* Returns the template arguments of T if T is a template instantiation,
3655 NULL otherwise. */
3657 tree
3658 get_template_innermost_arguments (const_tree t)
3660 tree args = NULL, template_info = NULL;
3662 if ((template_info = get_template_info (t))
3663 && TI_ARGS (template_info))
3664 args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
3666 return args;
3669 /* Return the argument pack elements of T if T is a template argument pack,
3670 NULL otherwise. */
3672 tree
3673 get_template_argument_pack_elems (const_tree t)
3675 if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
3676 && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
3677 return NULL;
3679 return ARGUMENT_PACK_ARGS (t);
3682 /* In an ARGUMENT_PACK_SELECT, the actual underlying argument that the
3683 ARGUMENT_PACK_SELECT represents. */
3685 static tree
3686 argument_pack_select_arg (tree t)
3688 tree args = ARGUMENT_PACK_ARGS (ARGUMENT_PACK_SELECT_FROM_PACK (t));
3689 tree arg = TREE_VEC_ELT (args, ARGUMENT_PACK_SELECT_INDEX (t));
3691 /* If the selected argument is an expansion E, that most likely means we were
3692 called from gen_elem_of_pack_expansion_instantiation during the
3693 substituting of an argument pack (of which the Ith element is a pack
3694 expansion, where I is ARGUMENT_PACK_SELECT_INDEX) into a pack expansion.
3695 In this case, the Ith element resulting from this substituting is going to
3696 be a pack expansion, which pattern is the pattern of E. Let's return the
3697 pattern of E, and gen_elem_of_pack_expansion_instantiation will build the
3698 resulting pack expansion from it. */
3699 if (PACK_EXPANSION_P (arg))
3701 /* Make sure we aren't throwing away arg info. */
3702 gcc_assert (!PACK_EXPANSION_EXTRA_ARGS (arg));
3703 arg = PACK_EXPANSION_PATTERN (arg);
3706 return arg;
3709 /* Return a modification of ARGS that's suitable for preserving inside a hash
3710 table. In particular, this replaces each ARGUMENT_PACK_SELECT with its
3711 underlying argument. ARGS is copied (upon modification) iff COW_P. */
3713 static tree
3714 preserve_args (tree args, bool cow_p = true)
3716 if (!args)
3717 return NULL_TREE;
3719 for (int i = 0, len = TREE_VEC_LENGTH (args); i < len; ++i)
3721 tree t = TREE_VEC_ELT (args, i);
3722 tree r;
3723 if (!t)
3724 r = NULL_TREE;
3725 else if (TREE_CODE (t) == ARGUMENT_PACK_SELECT)
3726 r = argument_pack_select_arg (t);
3727 else if (TREE_CODE (t) == TREE_VEC)
3728 r = preserve_args (t, cow_p);
3729 else
3730 r = t;
3731 if (r != t)
3733 if (cow_p)
3735 args = copy_template_args (args);
3736 cow_p = false;
3738 TREE_VEC_ELT (args, i) = r;
3742 return args;
3745 /* True iff FN is a function representing a built-in variadic parameter
3746 pack. */
3748 bool
3749 builtin_pack_fn_p (tree fn)
3751 if (!fn
3752 || TREE_CODE (fn) != FUNCTION_DECL
3753 || !DECL_IS_UNDECLARED_BUILTIN (fn))
3754 return false;
3756 if (id_equal (DECL_NAME (fn), "__integer_pack"))
3757 return true;
3759 return false;
3762 /* True iff CALL is a call to a function representing a built-in variadic
3763 parameter pack. */
3765 static bool
3766 builtin_pack_call_p (tree call)
3768 if (TREE_CODE (call) != CALL_EXPR)
3769 return false;
3770 return builtin_pack_fn_p (CALL_EXPR_FN (call));
3773 /* Return a TREE_VEC for the expansion of __integer_pack(HI). */
3775 static tree
3776 expand_integer_pack (tree call, tree args, tsubst_flags_t complain,
3777 tree in_decl)
3779 tree ohi = CALL_EXPR_ARG (call, 0);
3780 tree hi = tsubst_copy_and_build (ohi, args, complain, in_decl);
3782 if (instantiation_dependent_expression_p (hi))
3784 if (hi != ohi)
3786 call = copy_node (call);
3787 CALL_EXPR_ARG (call, 0) = hi;
3789 tree ex = make_pack_expansion (call, complain);
3790 tree vec = make_tree_vec (1);
3791 TREE_VEC_ELT (vec, 0) = ex;
3792 return vec;
3794 else
3796 hi = instantiate_non_dependent_expr (hi, complain);
3797 hi = cxx_constant_value (hi, complain);
3798 int len = valid_constant_size_p (hi) ? tree_to_shwi (hi) : -1;
3800 /* Calculate the largest value of len that won't make the size of the vec
3801 overflow an int. The compiler will exceed resource limits long before
3802 this, but it seems a decent place to diagnose. */
3803 int max = ((INT_MAX - sizeof (tree_vec)) / sizeof (tree)) + 1;
3805 if (len < 0 || len > max)
3807 if ((complain & tf_error)
3808 && hi != error_mark_node)
3809 error ("argument to %<__integer_pack%> must be between 0 and %d",
3810 max);
3811 return error_mark_node;
3814 tree vec = make_tree_vec (len);
3816 for (int i = 0; i < len; ++i)
3817 TREE_VEC_ELT (vec, i) = size_int (i);
3819 return vec;
3823 /* Return a TREE_VEC for the expansion of built-in template parameter pack
3824 CALL. */
3826 static tree
3827 expand_builtin_pack_call (tree call, tree args, tsubst_flags_t complain,
3828 tree in_decl)
3830 if (!builtin_pack_call_p (call))
3831 return NULL_TREE;
3833 tree fn = CALL_EXPR_FN (call);
3835 if (id_equal (DECL_NAME (fn), "__integer_pack"))
3836 return expand_integer_pack (call, args, complain, in_decl);
3838 return NULL_TREE;
3841 /* Return true if the tree T has the extra args mechanism for
3842 avoiding partial instantiation. */
3844 static bool
3845 has_extra_args_mechanism_p (const_tree t)
3847 return (PACK_EXPANSION_P (t) /* PACK_EXPANSION_EXTRA_ARGS */
3848 || TREE_CODE (t) == REQUIRES_EXPR /* REQUIRES_EXPR_EXTRA_ARGS */
3849 || (TREE_CODE (t) == IF_STMT
3850 && IF_STMT_CONSTEXPR_P (t))); /* IF_STMT_EXTRA_ARGS */
3853 /* Structure used to track the progress of find_parameter_packs_r. */
3854 struct find_parameter_pack_data
3856 /* TREE_LIST that will contain all of the parameter packs found by
3857 the traversal. */
3858 tree* parameter_packs;
3860 /* Set of AST nodes that have been visited by the traversal. */
3861 hash_set<tree> *visited;
3863 /* True iff we're making a type pack expansion. */
3864 bool type_pack_expansion_p;
3866 /* True iff we found a subtree that has the extra args mechanism. */
3867 bool found_extra_args_tree_p = false;
3870 /* Identifies all of the argument packs that occur in a template
3871 argument and appends them to the TREE_LIST inside DATA, which is a
3872 find_parameter_pack_data structure. This is a subroutine of
3873 make_pack_expansion and uses_parameter_packs. */
3874 static tree
3875 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
3877 tree t = *tp;
3878 struct find_parameter_pack_data* ppd =
3879 (struct find_parameter_pack_data*)data;
3880 bool parameter_pack_p = false;
3882 #define WALK_SUBTREE(NODE) \
3883 cp_walk_tree (&(NODE), &find_parameter_packs_r, \
3884 ppd, ppd->visited) \
3886 /* Don't look through typedefs; we are interested in whether a
3887 parameter pack is actually written in the expression/type we're
3888 looking at, not the target type. */
3889 if (TYPE_P (t) && typedef_variant_p (t))
3891 /* But do look at arguments for an alias template. */
3892 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
3893 cp_walk_tree (&TI_ARGS (tinfo),
3894 &find_parameter_packs_r,
3895 ppd, ppd->visited);
3896 *walk_subtrees = 0;
3897 return NULL_TREE;
3900 /* Identify whether this is a parameter pack or not. */
3901 switch (TREE_CODE (t))
3903 case TEMPLATE_PARM_INDEX:
3904 if (TEMPLATE_PARM_PARAMETER_PACK (t))
3905 parameter_pack_p = true;
3906 break;
3908 case TEMPLATE_TYPE_PARM:
3909 t = TYPE_MAIN_VARIANT (t);
3910 /* FALLTHRU */
3911 case TEMPLATE_TEMPLATE_PARM:
3912 /* If the placeholder appears in the decl-specifier-seq of a function
3913 parameter pack (14.6.3), or the type-specifier-seq of a type-id that
3914 is a pack expansion, the invented template parameter is a template
3915 parameter pack. */
3916 if (ppd->type_pack_expansion_p && is_auto (t))
3917 TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
3918 if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3919 parameter_pack_p = true;
3920 break;
3922 case FIELD_DECL:
3923 case PARM_DECL:
3924 if (DECL_PACK_P (t))
3926 /* We don't want to walk into the type of a PARM_DECL,
3927 because we don't want to see the type parameter pack. */
3928 *walk_subtrees = 0;
3929 parameter_pack_p = true;
3931 break;
3933 case VAR_DECL:
3934 if (DECL_PACK_P (t))
3936 /* We don't want to walk into the type of a variadic capture proxy,
3937 because we don't want to see the type parameter pack. */
3938 *walk_subtrees = 0;
3939 parameter_pack_p = true;
3941 else if (variable_template_specialization_p (t))
3943 cp_walk_tree (&DECL_TI_ARGS (t),
3944 find_parameter_packs_r,
3945 ppd, ppd->visited);
3946 *walk_subtrees = 0;
3948 break;
3950 case CALL_EXPR:
3951 if (builtin_pack_call_p (t))
3952 parameter_pack_p = true;
3953 break;
3955 case BASES:
3956 parameter_pack_p = true;
3957 break;
3958 default:
3959 /* Not a parameter pack. */
3960 break;
3963 if (parameter_pack_p)
3965 /* Add this parameter pack to the list. */
3966 *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
3969 if (has_extra_args_mechanism_p (t) && !PACK_EXPANSION_P (t))
3970 ppd->found_extra_args_tree_p = true;
3972 if (TYPE_P (t))
3973 cp_walk_tree (&TYPE_CONTEXT (t),
3974 &find_parameter_packs_r, ppd, ppd->visited);
3976 /* This switch statement will return immediately if we don't find a
3977 parameter pack. ??? Should some of these be in cp_walk_subtrees? */
3978 switch (TREE_CODE (t))
3980 case BOUND_TEMPLATE_TEMPLATE_PARM:
3981 /* Check the template itself. */
3982 cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)),
3983 &find_parameter_packs_r, ppd, ppd->visited);
3984 return NULL_TREE;
3986 case DECL_EXPR:
3988 tree decl = DECL_EXPR_DECL (t);
3989 /* Ignore the declaration of a capture proxy for a parameter pack. */
3990 if (is_capture_proxy (decl))
3991 *walk_subtrees = 0;
3992 if (is_typedef_decl (decl))
3993 /* Since we stop at typedefs above, we need to look through them at
3994 the point of the DECL_EXPR. */
3995 cp_walk_tree (&DECL_ORIGINAL_TYPE (decl),
3996 &find_parameter_packs_r, ppd, ppd->visited);
3997 return NULL_TREE;
4000 case TEMPLATE_DECL:
4001 if (!DECL_TEMPLATE_TEMPLATE_PARM_P (t))
4002 return NULL_TREE;
4003 cp_walk_tree (&TREE_TYPE (t),
4004 &find_parameter_packs_r, ppd, ppd->visited);
4005 return NULL_TREE;
4007 case TYPE_PACK_EXPANSION:
4008 case EXPR_PACK_EXPANSION:
4009 *walk_subtrees = 0;
4010 return NULL_TREE;
4012 case INTEGER_TYPE:
4013 cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r,
4014 ppd, ppd->visited);
4015 *walk_subtrees = 0;
4016 return NULL_TREE;
4018 case IDENTIFIER_NODE:
4019 cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd,
4020 ppd->visited);
4021 *walk_subtrees = 0;
4022 return NULL_TREE;
4024 case LAMBDA_EXPR:
4026 /* Since we defer implicit capture, look in the parms and body. */
4027 tree fn = lambda_function (t);
4028 cp_walk_tree (&TREE_TYPE (fn), &find_parameter_packs_r, ppd,
4029 ppd->visited);
4030 cp_walk_tree (&DECL_SAVED_TREE (fn), &find_parameter_packs_r, ppd,
4031 ppd->visited);
4032 return NULL_TREE;
4035 case DECLTYPE_TYPE:
4037 /* When traversing a DECLTYPE_TYPE_EXPR, we need to set
4038 type_pack_expansion_p to false so that any placeholders
4039 within the expression don't get marked as parameter packs. */
4040 bool type_pack_expansion_p = ppd->type_pack_expansion_p;
4041 ppd->type_pack_expansion_p = false;
4042 cp_walk_tree (&DECLTYPE_TYPE_EXPR (t), &find_parameter_packs_r,
4043 ppd, ppd->visited);
4044 ppd->type_pack_expansion_p = type_pack_expansion_p;
4045 *walk_subtrees = 0;
4046 return NULL_TREE;
4049 case IF_STMT:
4050 cp_walk_tree (&IF_COND (t), &find_parameter_packs_r,
4051 ppd, ppd->visited);
4052 cp_walk_tree (&THEN_CLAUSE (t), &find_parameter_packs_r,
4053 ppd, ppd->visited);
4054 cp_walk_tree (&ELSE_CLAUSE (t), &find_parameter_packs_r,
4055 ppd, ppd->visited);
4056 /* Don't walk into IF_STMT_EXTRA_ARGS. */
4057 *walk_subtrees = 0;
4058 return NULL_TREE;
4060 case TAG_DEFN:
4061 t = TREE_TYPE (t);
4062 if (CLASS_TYPE_P (t))
4064 /* Local class, need to look through the whole definition.
4065 TYPE_BINFO might be unset for a partial instantiation. */
4066 if (TYPE_BINFO (t))
4067 for (tree bb : BINFO_BASE_BINFOS (TYPE_BINFO (t)))
4068 cp_walk_tree (&BINFO_TYPE (bb), &find_parameter_packs_r,
4069 ppd, ppd->visited);
4071 else
4072 /* Enum, look at the values. */
4073 for (tree l = TYPE_VALUES (t); l; l = TREE_CHAIN (l))
4074 cp_walk_tree (&DECL_INITIAL (TREE_VALUE (l)),
4075 &find_parameter_packs_r,
4076 ppd, ppd->visited);
4077 return NULL_TREE;
4079 case FUNCTION_TYPE:
4080 case METHOD_TYPE:
4081 WALK_SUBTREE (TYPE_RAISES_EXCEPTIONS (t));
4082 break;
4084 default:
4085 return NULL_TREE;
4088 #undef WALK_SUBTREE
4090 return NULL_TREE;
4093 /* Determines if the expression or type T uses any parameter packs. */
4094 tree
4095 uses_parameter_packs (tree t)
4097 tree parameter_packs = NULL_TREE;
4098 struct find_parameter_pack_data ppd;
4099 ppd.parameter_packs = &parameter_packs;
4100 ppd.visited = new hash_set<tree>;
4101 ppd.type_pack_expansion_p = false;
4102 cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4103 delete ppd.visited;
4104 return parameter_packs;
4107 /* Turn ARG, which may be an expression, type, or a TREE_LIST
4108 representation a base-class initializer into a parameter pack
4109 expansion. If all goes well, the resulting node will be an
4110 EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
4111 respectively. */
4112 tree
4113 make_pack_expansion (tree arg, tsubst_flags_t complain)
4115 tree result;
4116 tree parameter_packs = NULL_TREE;
4117 bool for_types = false;
4118 struct find_parameter_pack_data ppd;
4120 if (!arg || arg == error_mark_node)
4121 return arg;
4123 if (TREE_CODE (arg) == TREE_LIST && TREE_PURPOSE (arg))
4125 /* A TREE_LIST with a non-null TREE_PURPOSE is for a base
4126 class initializer. In this case, the TREE_PURPOSE will be a
4127 _TYPE node (representing the base class expansion we're
4128 initializing) and the TREE_VALUE will be a TREE_LIST
4129 containing the initialization arguments.
4131 The resulting expansion looks somewhat different from most
4132 expansions. Rather than returning just one _EXPANSION, we
4133 return a TREE_LIST whose TREE_PURPOSE is a
4134 TYPE_PACK_EXPANSION containing the bases that will be
4135 initialized. The TREE_VALUE will be identical to the
4136 original TREE_VALUE, which is a list of arguments that will
4137 be passed to each base. We do not introduce any new pack
4138 expansion nodes into the TREE_VALUE (although it is possible
4139 that some already exist), because the TREE_PURPOSE and
4140 TREE_VALUE all need to be expanded together with the same
4141 _EXPANSION node. Note that the TYPE_PACK_EXPANSION in the
4142 resulting TREE_PURPOSE will mention the parameter packs in
4143 both the bases and the arguments to the bases. */
4144 tree purpose;
4145 tree value;
4146 tree parameter_packs = NULL_TREE;
4148 /* Determine which parameter packs will be used by the base
4149 class expansion. */
4150 ppd.visited = new hash_set<tree>;
4151 ppd.parameter_packs = &parameter_packs;
4152 ppd.type_pack_expansion_p = false;
4153 gcc_assert (TYPE_P (TREE_PURPOSE (arg)));
4154 cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r,
4155 &ppd, ppd.visited);
4157 if (parameter_packs == NULL_TREE)
4159 if (complain & tf_error)
4160 error ("base initializer expansion %qT contains no parameter packs",
4161 arg);
4162 delete ppd.visited;
4163 return error_mark_node;
4166 if (TREE_VALUE (arg) != void_type_node)
4168 /* Collect the sets of parameter packs used in each of the
4169 initialization arguments. */
4170 for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
4172 /* Determine which parameter packs will be expanded in this
4173 argument. */
4174 cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r,
4175 &ppd, ppd.visited);
4179 delete ppd.visited;
4181 /* Create the pack expansion type for the base type. */
4182 purpose = cxx_make_type (TYPE_PACK_EXPANSION);
4183 PACK_EXPANSION_PATTERN (purpose) = TREE_PURPOSE (arg);
4184 PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
4185 PACK_EXPANSION_LOCAL_P (purpose) = at_function_scope_p ();
4187 /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
4188 they will rarely be compared to anything. */
4189 SET_TYPE_STRUCTURAL_EQUALITY (purpose);
4191 return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
4194 if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
4195 for_types = true;
4197 /* Build the PACK_EXPANSION_* node. */
4198 result = for_types
4199 ? cxx_make_type (TYPE_PACK_EXPANSION)
4200 : make_node (EXPR_PACK_EXPANSION);
4201 PACK_EXPANSION_PATTERN (result) = arg;
4202 if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
4204 /* Propagate type and const-expression information. */
4205 TREE_TYPE (result) = TREE_TYPE (arg);
4206 TREE_CONSTANT (result) = TREE_CONSTANT (arg);
4207 /* Mark this read now, since the expansion might be length 0. */
4208 mark_exp_read (arg);
4210 else
4211 /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
4212 they will rarely be compared to anything. */
4213 SET_TYPE_STRUCTURAL_EQUALITY (result);
4215 /* Determine which parameter packs will be expanded. */
4216 ppd.parameter_packs = &parameter_packs;
4217 ppd.visited = new hash_set<tree>;
4218 ppd.type_pack_expansion_p = TYPE_P (arg);
4219 cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
4220 delete ppd.visited;
4222 /* Make sure we found some parameter packs. */
4223 if (parameter_packs == NULL_TREE)
4225 if (complain & tf_error)
4227 if (TYPE_P (arg))
4228 error ("expansion pattern %qT contains no parameter packs", arg);
4229 else
4230 error ("expansion pattern %qE contains no parameter packs", arg);
4232 return error_mark_node;
4234 PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
4236 PACK_EXPANSION_LOCAL_P (result) = at_function_scope_p ();
4237 if (ppd.found_extra_args_tree_p)
4238 /* If the pattern of this pack expansion contains a subtree that has
4239 the extra args mechanism for avoiding partial instantiation, then
4240 force this pack expansion to also use extra args. Otherwise
4241 partial instantiation of this pack expansion may not lower the
4242 level of some parameter packs within the pattern, which would
4243 confuse tsubst_pack_expansion later (PR101764). */
4244 PACK_EXPANSION_FORCE_EXTRA_ARGS_P (result) = true;
4246 return result;
4249 /* Checks T for any "bare" parameter packs, which have not yet been
4250 expanded, and issues an error if any are found. This operation can
4251 only be done on full expressions or types (e.g., an expression
4252 statement, "if" condition, etc.), because we could have expressions like:
4254 foo(f(g(h(args)))...)
4256 where "args" is a parameter pack. check_for_bare_parameter_packs
4257 should not be called for the subexpressions args, h(args),
4258 g(h(args)), or f(g(h(args))), because we would produce erroneous
4259 error messages.
4261 Returns TRUE and emits an error if there were bare parameter packs,
4262 returns FALSE otherwise. */
4263 bool
4264 check_for_bare_parameter_packs (tree t, location_t loc /* = UNKNOWN_LOCATION */)
4266 tree parameter_packs = NULL_TREE;
4267 struct find_parameter_pack_data ppd;
4269 if (!processing_template_decl || !t || t == error_mark_node)
4270 return false;
4272 if (TREE_CODE (t) == TYPE_DECL)
4273 t = TREE_TYPE (t);
4275 ppd.parameter_packs = &parameter_packs;
4276 ppd.visited = new hash_set<tree>;
4277 ppd.type_pack_expansion_p = false;
4278 cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4279 delete ppd.visited;
4281 if (!parameter_packs)
4282 return false;
4284 if (loc == UNKNOWN_LOCATION)
4285 loc = cp_expr_loc_or_input_loc (t);
4287 /* It's OK for a lambda to have an unexpanded parameter pack from the
4288 containing context, but do complain about unexpanded capture packs. */
4289 tree lam = current_lambda_expr ();
4290 if (lam)
4291 lam = TREE_TYPE (lam);
4293 if (lam && lam != current_class_type)
4295 /* We're in a lambda, but it isn't the innermost class.
4296 This should work, but currently doesn't. */
4297 sorry_at (loc, "unexpanded parameter pack in local class in lambda");
4298 return true;
4301 if (lam && CLASSTYPE_TEMPLATE_INFO (lam))
4302 for (; parameter_packs;
4303 parameter_packs = TREE_CHAIN (parameter_packs))
4305 tree pack = TREE_VALUE (parameter_packs);
4306 if (is_capture_proxy (pack)
4307 || (TREE_CODE (pack) == PARM_DECL
4308 && DECL_CONTEXT (DECL_CONTEXT (pack)) == lam))
4309 break;
4312 if (parameter_packs)
4314 error_at (loc, "parameter packs not expanded with %<...%>:");
4315 while (parameter_packs)
4317 tree pack = TREE_VALUE (parameter_packs);
4318 tree name = NULL_TREE;
4320 if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
4321 || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
4322 name = TYPE_NAME (pack);
4323 else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
4324 name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
4325 else if (TREE_CODE (pack) == CALL_EXPR)
4326 name = DECL_NAME (CALL_EXPR_FN (pack));
4327 else
4328 name = DECL_NAME (pack);
4330 if (name)
4331 inform (loc, " %qD", name);
4332 else
4333 inform (loc, " %s", "<anonymous>");
4335 parameter_packs = TREE_CHAIN (parameter_packs);
4338 return true;
4341 return false;
4344 /* Expand any parameter packs that occur in the template arguments in
4345 ARGS. */
4346 tree
4347 expand_template_argument_pack (tree args)
4349 if (args == error_mark_node)
4350 return error_mark_node;
4352 tree result_args = NULL_TREE;
4353 int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
4354 int num_result_args = -1;
4355 int non_default_args_count = -1;
4357 /* First, determine if we need to expand anything, and the number of
4358 slots we'll need. */
4359 for (in_arg = 0; in_arg < nargs; ++in_arg)
4361 tree arg = TREE_VEC_ELT (args, in_arg);
4362 if (arg == NULL_TREE)
4363 return args;
4364 if (ARGUMENT_PACK_P (arg))
4366 int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
4367 if (num_result_args < 0)
4368 num_result_args = in_arg + num_packed;
4369 else
4370 num_result_args += num_packed;
4372 else
4374 if (num_result_args >= 0)
4375 num_result_args++;
4379 /* If no expansion is necessary, we're done. */
4380 if (num_result_args < 0)
4381 return args;
4383 /* Expand arguments. */
4384 result_args = make_tree_vec (num_result_args);
4385 if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
4386 non_default_args_count =
4387 GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
4388 for (in_arg = 0; in_arg < nargs; ++in_arg)
4390 tree arg = TREE_VEC_ELT (args, in_arg);
4391 if (ARGUMENT_PACK_P (arg))
4393 tree packed = ARGUMENT_PACK_ARGS (arg);
4394 int i, num_packed = TREE_VEC_LENGTH (packed);
4395 for (i = 0; i < num_packed; ++i, ++out_arg)
4396 TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
4397 if (non_default_args_count > 0)
4398 non_default_args_count += num_packed - 1;
4400 else
4402 TREE_VEC_ELT (result_args, out_arg) = arg;
4403 ++out_arg;
4406 if (non_default_args_count >= 0)
4407 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
4408 return result_args;
4411 /* Checks if DECL shadows a template parameter.
4413 [temp.local]: A template-parameter shall not be redeclared within its
4414 scope (including nested scopes).
4416 Emits an error and returns TRUE if the DECL shadows a parameter,
4417 returns FALSE otherwise. */
4419 bool
4420 check_template_shadow (tree decl)
4422 tree olddecl;
4424 /* If we're not in a template, we can't possibly shadow a template
4425 parameter. */
4426 if (!current_template_parms)
4427 return true;
4429 /* Figure out what we're shadowing. */
4430 decl = OVL_FIRST (decl);
4431 olddecl = innermost_non_namespace_value (DECL_NAME (decl));
4433 /* If there's no previous binding for this name, we're not shadowing
4434 anything, let alone a template parameter. */
4435 if (!olddecl)
4436 return true;
4438 /* If we're not shadowing a template parameter, we're done. Note
4439 that OLDDECL might be an OVERLOAD (or perhaps even an
4440 ERROR_MARK), so we can't just blithely assume it to be a _DECL
4441 node. */
4442 if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
4443 return true;
4445 /* We check for decl != olddecl to avoid bogus errors for using a
4446 name inside a class. We check TPFI to avoid duplicate errors for
4447 inline member templates. */
4448 if (decl == olddecl
4449 || (DECL_TEMPLATE_PARM_P (decl)
4450 && TEMPLATE_PARMS_FOR_INLINE (current_template_parms)))
4451 return true;
4453 /* Don't complain about the injected class name, as we've already
4454 complained about the class itself. */
4455 if (DECL_SELF_REFERENCE_P (decl))
4456 return false;
4458 if (DECL_TEMPLATE_PARM_P (decl))
4459 error ("declaration of template parameter %q+D shadows "
4460 "template parameter", decl);
4461 else
4462 error ("declaration of %q+#D shadows template parameter", decl);
4463 inform (DECL_SOURCE_LOCATION (olddecl),
4464 "template parameter %qD declared here", olddecl);
4465 return false;
4468 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
4469 ORIG_LEVEL, DECL, and TYPE. */
4471 static tree
4472 build_template_parm_index (int index,
4473 int level,
4474 int orig_level,
4475 tree decl,
4476 tree type)
4478 tree t = make_node (TEMPLATE_PARM_INDEX);
4479 TEMPLATE_PARM_IDX (t) = index;
4480 TEMPLATE_PARM_LEVEL (t) = level;
4481 TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
4482 TEMPLATE_PARM_DECL (t) = decl;
4483 TREE_TYPE (t) = type;
4484 TREE_CONSTANT (t) = TREE_CONSTANT (decl);
4485 TREE_READONLY (t) = TREE_READONLY (decl);
4487 return t;
4490 struct ctp_hasher : ggc_ptr_hash<tree_node>
4492 static hashval_t hash (tree t)
4494 ++comparing_specializations;
4495 tree_code code = TREE_CODE (t);
4496 hashval_t val = iterative_hash_object (code, 0);
4497 val = iterative_hash_object (TEMPLATE_TYPE_LEVEL (t), val);
4498 val = iterative_hash_object (TEMPLATE_TYPE_IDX (t), val);
4499 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
4500 val = iterative_hash_template_arg (TYPE_TI_ARGS (t), val);
4501 --comparing_specializations;
4502 return val;
4505 static bool equal (tree t, tree u)
4507 ++comparing_specializations;
4508 bool eq = comptypes (t, u, COMPARE_STRUCTURAL);
4509 --comparing_specializations;
4510 return eq;
4514 static GTY (()) hash_table<ctp_hasher> *ctp_table;
4516 /* Find the canonical type parameter for the given template type
4517 parameter. Returns the canonical type parameter, which may be TYPE
4518 if no such parameter existed. */
4520 tree
4521 canonical_type_parameter (tree type)
4523 if (ctp_table == NULL)
4524 ctp_table = hash_table<ctp_hasher>::create_ggc (61);
4526 tree& slot = *ctp_table->find_slot (type, INSERT);
4527 if (slot == NULL_TREE)
4528 slot = type;
4529 return slot;
4532 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
4533 TEMPLATE_PARM_LEVEL has been decreased by LEVELS. If such a
4534 TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
4535 new one is created. */
4537 static tree
4538 reduce_template_parm_level (tree index, tree type, int levels, tree args,
4539 tsubst_flags_t complain)
4541 if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
4542 || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
4543 != TEMPLATE_PARM_LEVEL (index) - levels)
4544 || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
4546 tree orig_decl = TEMPLATE_PARM_DECL (index);
4548 tree decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
4549 TREE_CODE (orig_decl), DECL_NAME (orig_decl),
4550 type);
4551 TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
4552 TREE_READONLY (decl) = TREE_READONLY (orig_decl);
4553 DECL_VIRTUAL_P (decl) = DECL_VIRTUAL_P (orig_decl);
4554 DECL_ARTIFICIAL (decl) = 1;
4555 SET_DECL_TEMPLATE_PARM_P (decl);
4557 tree tpi = build_template_parm_index (TEMPLATE_PARM_IDX (index),
4558 TEMPLATE_PARM_LEVEL (index) - levels,
4559 TEMPLATE_PARM_ORIG_LEVEL (index),
4560 decl, type);
4561 TEMPLATE_PARM_DESCENDANTS (index) = tpi;
4562 TEMPLATE_PARM_PARAMETER_PACK (tpi)
4563 = TEMPLATE_PARM_PARAMETER_PACK (index);
4565 /* Template template parameters need this. */
4566 tree inner = decl;
4567 if (TREE_CODE (decl) == TEMPLATE_DECL)
4569 inner = build_decl (DECL_SOURCE_LOCATION (decl),
4570 TYPE_DECL, DECL_NAME (decl), type);
4571 DECL_TEMPLATE_RESULT (decl) = inner;
4572 DECL_ARTIFICIAL (inner) = true;
4573 DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
4574 (DECL_TEMPLATE_PARMS (orig_decl), args, complain);
4577 /* Attach the TPI to the decl. */
4578 if (TREE_CODE (inner) == TYPE_DECL)
4579 TEMPLATE_TYPE_PARM_INDEX (type) = tpi;
4580 else
4581 DECL_INITIAL (decl) = tpi;
4584 return TEMPLATE_PARM_DESCENDANTS (index);
4587 /* Process information from new template parameter PARM and append it
4588 to the LIST being built. This new parameter is a non-type
4589 parameter iff IS_NON_TYPE is true. This new parameter is a
4590 parameter pack iff IS_PARAMETER_PACK is true. The location of PARM
4591 is in PARM_LOC. */
4593 tree
4594 process_template_parm (tree list, location_t parm_loc, tree parm,
4595 bool is_non_type, bool is_parameter_pack)
4597 gcc_assert (TREE_CODE (parm) == TREE_LIST);
4598 tree prev = NULL_TREE;
4599 int idx = 0;
4601 if (list)
4603 prev = tree_last (list);
4605 tree p = TREE_VALUE (prev);
4606 if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
4607 idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
4608 else if (TREE_CODE (p) == PARM_DECL)
4609 idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
4611 ++idx;
4614 tree decl = NULL_TREE;
4615 tree defval = TREE_PURPOSE (parm);
4616 tree constr = TREE_TYPE (parm);
4618 if (is_non_type)
4620 parm = TREE_VALUE (parm);
4622 SET_DECL_TEMPLATE_PARM_P (parm);
4624 if (TREE_TYPE (parm) != error_mark_node)
4626 /* [temp.param]
4628 The top-level cv-qualifiers on the template-parameter are
4629 ignored when determining its type. */
4630 TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
4631 if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
4632 TREE_TYPE (parm) = error_mark_node;
4633 else if (uses_parameter_packs (TREE_TYPE (parm))
4634 && !is_parameter_pack
4635 /* If we're in a nested template parameter list, the template
4636 template parameter could be a parameter pack. */
4637 && processing_template_parmlist == 1)
4639 /* This template parameter is not a parameter pack, but it
4640 should be. Complain about "bare" parameter packs. */
4641 check_for_bare_parameter_packs (TREE_TYPE (parm));
4643 /* Recover by calling this a parameter pack. */
4644 is_parameter_pack = true;
4648 /* A template parameter is not modifiable. */
4649 TREE_CONSTANT (parm) = 1;
4650 TREE_READONLY (parm) = 1;
4651 decl = build_decl (parm_loc,
4652 CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
4653 TREE_CONSTANT (decl) = 1;
4654 TREE_READONLY (decl) = 1;
4655 DECL_INITIAL (parm) = DECL_INITIAL (decl)
4656 = build_template_parm_index (idx, current_template_depth,
4657 current_template_depth,
4658 decl, TREE_TYPE (parm));
4660 TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))
4661 = is_parameter_pack;
4663 else
4665 tree t;
4666 parm = TREE_VALUE (TREE_VALUE (parm));
4668 if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
4670 t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
4671 /* This is for distinguishing between real templates and template
4672 template parameters */
4673 TREE_TYPE (parm) = t;
4675 /* any_template_parm_r expects to be able to get the targs of a
4676 DECL_TEMPLATE_RESULT. */
4677 tree result = DECL_TEMPLATE_RESULT (parm);
4678 TREE_TYPE (result) = t;
4679 tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (parm));
4680 tree tinfo = build_template_info (parm, args);
4681 retrofit_lang_decl (result);
4682 DECL_TEMPLATE_INFO (result) = tinfo;
4684 decl = parm;
4686 else
4688 t = cxx_make_type (TEMPLATE_TYPE_PARM);
4689 /* parm is either IDENTIFIER_NODE or NULL_TREE. */
4690 decl = build_decl (parm_loc,
4691 TYPE_DECL, parm, t);
4694 TYPE_NAME (t) = decl;
4695 TYPE_STUB_DECL (t) = decl;
4696 parm = decl;
4697 TEMPLATE_TYPE_PARM_INDEX (t)
4698 = build_template_parm_index (idx, current_template_depth,
4699 current_template_depth,
4700 decl, TREE_TYPE (parm));
4701 TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
4702 TYPE_CANONICAL (t) = canonical_type_parameter (t);
4704 DECL_ARTIFICIAL (decl) = 1;
4705 SET_DECL_TEMPLATE_PARM_P (decl);
4707 if (TREE_CODE (parm) == TEMPLATE_DECL
4708 && !uses_outer_template_parms (parm))
4709 TEMPLATE_TEMPLATE_PARM_SIMPLE_P (TREE_TYPE (parm)) = true;
4711 /* Build requirements for the type/template parameter.
4712 This must be done after SET_DECL_TEMPLATE_PARM_P or
4713 process_template_parm could fail. */
4714 tree reqs = finish_shorthand_constraint (parm, constr);
4716 decl = pushdecl (decl);
4717 if (!is_non_type)
4718 parm = decl;
4720 /* Build the parameter node linking the parameter declaration,
4721 its default argument (if any), and its constraints (if any). */
4722 parm = build_tree_list (defval, parm);
4723 TEMPLATE_PARM_CONSTRAINTS (parm) = reqs;
4725 if (prev)
4726 TREE_CHAIN (prev) = parm;
4727 else
4728 list = parm;
4730 return list;
4733 /* The end of a template parameter list has been reached. Process the
4734 tree list into a parameter vector, converting each parameter into a more
4735 useful form. Type parameters are saved as IDENTIFIER_NODEs, and others
4736 as PARM_DECLs. */
4738 tree
4739 end_template_parm_list (tree parms)
4741 tree saved_parmlist = make_tree_vec (list_length (parms));
4743 /* Pop the dummy parameter level and add the real one. We do not
4744 morph the dummy parameter in place, as it might have been
4745 captured by a (nested) template-template-parm. */
4746 current_template_parms = TREE_CHAIN (current_template_parms);
4748 current_template_parms
4749 = tree_cons (size_int (current_template_depth + 1),
4750 saved_parmlist, current_template_parms);
4752 for (unsigned ix = 0; parms; ix++)
4754 tree parm = parms;
4755 parms = TREE_CHAIN (parms);
4756 TREE_CHAIN (parm) = NULL_TREE;
4758 TREE_VEC_ELT (saved_parmlist, ix) = parm;
4761 --processing_template_parmlist;
4763 return saved_parmlist;
4766 // Explicitly indicate the end of the template parameter list. We assume
4767 // that the current template parameters have been constructed and/or
4768 // managed explicitly, as when creating new template template parameters
4769 // from a shorthand constraint.
4770 void
4771 end_template_parm_list ()
4773 --processing_template_parmlist;
4776 /* end_template_decl is called after a template declaration is seen. */
4778 void
4779 end_template_decl (void)
4781 reset_specialization ();
4783 if (! processing_template_decl)
4784 return;
4786 /* This matches the pushlevel in begin_template_parm_list. */
4787 finish_scope ();
4789 --processing_template_decl;
4790 current_template_parms = TREE_CHAIN (current_template_parms);
4793 /* Takes a TEMPLATE_PARM_P or DECL_TEMPLATE_PARM_P node or a TREE_LIST
4794 thereof, and converts it into an argument suitable to be passed to
4795 the type substitution functions. Note that if the TREE_LIST contains
4796 an error_mark node, the returned argument is error_mark_node. */
4798 tree
4799 template_parm_to_arg (tree t)
4801 if (!t)
4802 return NULL_TREE;
4804 if (TREE_CODE (t) == TREE_LIST)
4805 t = TREE_VALUE (t);
4807 if (error_operand_p (t))
4808 return error_mark_node;
4810 if (DECL_P (t) && DECL_TEMPLATE_PARM_P (t))
4812 if (TREE_CODE (t) == TYPE_DECL
4813 || TREE_CODE (t) == TEMPLATE_DECL)
4814 t = TREE_TYPE (t);
4815 else
4816 t = DECL_INITIAL (t);
4819 gcc_assert (TEMPLATE_PARM_P (t));
4821 if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
4822 || TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
4824 if (TEMPLATE_TYPE_PARAMETER_PACK (t))
4826 /* Turn this argument into a TYPE_ARGUMENT_PACK
4827 with a single element, which expands T. */
4828 tree vec = make_tree_vec (1);
4829 if (CHECKING_P)
4830 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4832 TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4834 t = cxx_make_type (TYPE_ARGUMENT_PACK);
4835 ARGUMENT_PACK_ARGS (t) = vec;
4838 else
4840 if (TEMPLATE_PARM_PARAMETER_PACK (t))
4842 /* Turn this argument into a NONTYPE_ARGUMENT_PACK
4843 with a single element, which expands T. */
4844 tree vec = make_tree_vec (1);
4845 if (CHECKING_P)
4846 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4848 t = convert_from_reference (t);
4849 TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4851 t = make_node (NONTYPE_ARGUMENT_PACK);
4852 ARGUMENT_PACK_ARGS (t) = vec;
4854 else
4855 t = convert_from_reference (t);
4857 return t;
4860 /* If T looks like a generic template argument produced by template_parm_to_arg,
4861 return the corresponding template parameter, otherwise return NULL_TREE. */
4863 static tree
4864 template_arg_to_parm (tree t)
4866 if (t == NULL_TREE)
4867 return NULL_TREE;
4869 if (ARGUMENT_PACK_P (t))
4871 tree args = ARGUMENT_PACK_ARGS (t);
4872 if (TREE_VEC_LENGTH (args) == 1
4873 && PACK_EXPANSION_P (TREE_VEC_ELT (args, 0)))
4874 t = PACK_EXPANSION_PATTERN (TREE_VEC_ELT (args, 0));
4877 if (REFERENCE_REF_P (t))
4878 t = TREE_OPERAND (t, 0);
4880 if (TEMPLATE_PARM_P (t))
4881 return t;
4882 else
4883 return NULL_TREE;
4886 /* Given a single level of template parameters (a TREE_VEC), return it
4887 as a set of template arguments. */
4889 tree
4890 template_parms_level_to_args (tree parms)
4892 parms = copy_node (parms);
4893 TREE_TYPE (parms) = NULL_TREE;
4894 for (tree& parm : tree_vec_range (parms))
4895 parm = template_parm_to_arg (parm);
4897 if (CHECKING_P)
4898 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (parms, TREE_VEC_LENGTH (parms));
4900 return parms;
4903 /* Given a set of template parameters, return them as a set of template
4904 arguments. The template parameters are represented as a TREE_VEC, in
4905 the form documented in cp-tree.h for template arguments. */
4907 tree
4908 template_parms_to_args (tree parms)
4910 tree header;
4911 tree args = NULL_TREE;
4912 int length = TMPL_PARMS_DEPTH (parms);
4913 int l = length;
4915 /* If there is only one level of template parameters, we do not
4916 create a TREE_VEC of TREE_VECs. Instead, we return a single
4917 TREE_VEC containing the arguments. */
4918 if (length > 1)
4919 args = make_tree_vec (length);
4921 for (header = parms; header; header = TREE_CHAIN (header))
4923 tree a = template_parms_level_to_args (TREE_VALUE (header));
4925 if (length > 1)
4926 TREE_VEC_ELT (args, --l) = a;
4927 else
4928 args = a;
4931 return args;
4934 /* Within the declaration of a template, return the currently active
4935 template parameters as an argument TREE_VEC. */
4937 static tree
4938 current_template_args (void)
4940 return template_parms_to_args (current_template_parms);
4943 /* Return the fully generic arguments for of TMPL, i.e. what
4944 current_template_args would be while parsing it. */
4946 tree
4947 generic_targs_for (tree tmpl)
4949 if (tmpl == NULL_TREE)
4950 return NULL_TREE;
4951 if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
4952 || DECL_TEMPLATE_SPECIALIZATION (tmpl))
4953 /* DECL_TEMPLATE_RESULT doesn't have the arguments we want. For a template
4954 template parameter, it has no TEMPLATE_INFO; for a partial
4955 specialization, it has the arguments for the primary template, and we
4956 want the arguments for the partial specialization. */;
4957 else if (tree result = DECL_TEMPLATE_RESULT (tmpl))
4958 if (tree ti = get_template_info (result))
4959 return TI_ARGS (ti);
4960 return template_parms_to_args (DECL_TEMPLATE_PARMS (tmpl));
4963 /* Return the template arguments corresponding to the template parameters of
4964 TMPL's enclosing scope. When TMPL is a member of a partial specialization,
4965 this returns the arguments for the partial specialization as opposed to those
4966 for the primary template, which is the main difference between this function
4967 and simply using e.g. the TYPE_TI_ARGS of TMPL's DECL_CONTEXT. */
4969 tree
4970 outer_template_args (tree tmpl)
4972 tree ti = get_template_info (DECL_TEMPLATE_RESULT (tmpl));
4973 if (!ti)
4974 return NULL_TREE;
4975 tree args = TI_ARGS (ti);
4976 if (!PRIMARY_TEMPLATE_P (tmpl))
4977 return args;
4978 if (TMPL_ARGS_DEPTH (args) == 1)
4979 return NULL_TREE;
4980 return strip_innermost_template_args (args, 1);
4983 /* Update the declared TYPE by doing any lookups which were thought to be
4984 dependent, but are not now that we know the SCOPE of the declarator. */
4986 tree
4987 maybe_update_decl_type (tree orig_type, tree scope)
4989 tree type = orig_type;
4991 if (type == NULL_TREE)
4992 return type;
4994 if (TREE_CODE (orig_type) == TYPE_DECL)
4995 type = TREE_TYPE (type);
4997 if (scope && TYPE_P (scope) && dependent_type_p (scope)
4998 && dependent_type_p (type)
4999 /* Don't bother building up the args in this case. */
5000 && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
5002 /* tsubst in the args corresponding to the template parameters,
5003 including auto if present. Most things will be unchanged, but
5004 make_typename_type and tsubst_qualified_id will resolve
5005 TYPENAME_TYPEs and SCOPE_REFs that were previously dependent. */
5006 tree args = current_template_args ();
5007 tree auto_node = type_uses_auto (type);
5008 tree pushed;
5009 if (auto_node)
5011 tree auto_vec = make_tree_vec (1);
5012 TREE_VEC_ELT (auto_vec, 0) = auto_node;
5013 args = add_to_template_args (args, auto_vec);
5015 pushed = push_scope (scope);
5016 type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
5017 if (pushed)
5018 pop_scope (scope);
5021 if (type == error_mark_node)
5022 return orig_type;
5024 if (TREE_CODE (orig_type) == TYPE_DECL)
5026 if (same_type_p (type, TREE_TYPE (orig_type)))
5027 type = orig_type;
5028 else
5029 type = TYPE_NAME (type);
5031 return type;
5034 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
5035 template PARMS and constraints, CONSTR. If MEMBER_TEMPLATE_P is true,
5036 the new template is a member template. */
5038 static tree
5039 build_template_decl (tree decl, tree parms, bool member_template_p)
5041 gcc_checking_assert (TREE_CODE (decl) != TEMPLATE_DECL);
5043 tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
5044 SET_DECL_LANGUAGE (tmpl, DECL_LANGUAGE (decl));
5045 DECL_TEMPLATE_PARMS (tmpl) = parms;
5046 DECL_TEMPLATE_RESULT (tmpl) = decl;
5047 DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
5048 TREE_TYPE (tmpl) = TREE_TYPE (decl);
5049 DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
5050 DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
5052 /* Propagate module information from the decl. */
5053 DECL_MODULE_EXPORT_P (tmpl) = DECL_MODULE_EXPORT_P (decl);
5055 return tmpl;
5058 struct template_parm_data
5060 /* The level of the template parameters we are currently
5061 processing. */
5062 int level;
5064 /* The index of the specialization argument we are currently
5065 processing. */
5066 int current_arg;
5068 /* An array whose size is the number of template parameters. The
5069 elements are nonzero if the parameter has been used in any one
5070 of the arguments processed so far. */
5071 int* parms;
5073 /* An array whose size is the number of template arguments. The
5074 elements are nonzero if the argument makes use of template
5075 parameters of this level. */
5076 int* arg_uses_template_parms;
5079 /* Subroutine of push_template_decl used to see if each template
5080 parameter in a partial specialization is used in the explicit
5081 argument list. If T is of the LEVEL given in DATA (which is
5082 treated as a template_parm_data*), then DATA->PARMS is marked
5083 appropriately. */
5085 static int
5086 mark_template_parm (tree t, void* data)
5088 int level;
5089 int idx;
5090 struct template_parm_data* tpd = (struct template_parm_data*) data;
5092 template_parm_level_and_index (t, &level, &idx);
5094 if (level == tpd->level)
5096 tpd->parms[idx] = 1;
5097 tpd->arg_uses_template_parms[tpd->current_arg] = 1;
5100 /* In C++17 the type of a non-type argument is a deduced context. */
5101 if (cxx_dialect >= cxx17
5102 && TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5103 for_each_template_parm (TREE_TYPE (t),
5104 &mark_template_parm,
5105 data,
5106 NULL,
5107 /*include_nondeduced_p=*/false);
5109 /* Return zero so that for_each_template_parm will continue the
5110 traversal of the tree; we want to mark *every* template parm. */
5111 return 0;
5114 /* Process the partial specialization DECL. */
5116 static tree
5117 process_partial_specialization (tree decl)
5119 tree type = TREE_TYPE (decl);
5120 tree tinfo = get_template_info (decl);
5121 tree maintmpl = TI_TEMPLATE (tinfo);
5122 tree specargs = TI_ARGS (tinfo);
5123 tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
5124 tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
5125 tree inner_parms;
5126 tree inst;
5127 int nargs = TREE_VEC_LENGTH (inner_args);
5128 int ntparms;
5129 int i;
5130 bool did_error_intro = false;
5131 struct template_parm_data tpd;
5132 struct template_parm_data tpd2;
5134 gcc_assert (current_template_parms);
5136 /* A concept cannot be specialized. */
5137 if (flag_concepts && variable_concept_p (maintmpl))
5139 error ("specialization of variable concept %q#D", maintmpl);
5140 return error_mark_node;
5143 inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
5144 ntparms = TREE_VEC_LENGTH (inner_parms);
5146 /* We check that each of the template parameters given in the
5147 partial specialization is used in the argument list to the
5148 specialization. For example:
5150 template <class T> struct S;
5151 template <class T> struct S<T*>;
5153 The second declaration is OK because `T*' uses the template
5154 parameter T, whereas
5156 template <class T> struct S<int>;
5158 is no good. Even trickier is:
5160 template <class T>
5161 struct S1
5163 template <class U>
5164 struct S2;
5165 template <class U>
5166 struct S2<T>;
5169 The S2<T> declaration is actually invalid; it is a
5170 full-specialization. Of course,
5172 template <class U>
5173 struct S2<T (*)(U)>;
5175 or some such would have been OK. */
5176 tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
5177 tpd.parms = XALLOCAVEC (int, ntparms);
5178 memset (tpd.parms, 0, sizeof (int) * ntparms);
5180 tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
5181 memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
5182 for (i = 0; i < nargs; ++i)
5184 tpd.current_arg = i;
5185 for_each_template_parm (TREE_VEC_ELT (inner_args, i),
5186 &mark_template_parm,
5187 &tpd,
5188 NULL,
5189 /*include_nondeduced_p=*/false);
5191 for (i = 0; i < ntparms; ++i)
5192 if (tpd.parms[i] == 0)
5194 /* One of the template parms was not used in a deduced context in the
5195 specialization. */
5196 if (!did_error_intro)
5198 error ("template parameters not deducible in "
5199 "partial specialization:");
5200 did_error_intro = true;
5203 inform (input_location, " %qD",
5204 TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
5207 if (did_error_intro)
5208 return error_mark_node;
5210 /* [temp.class.spec]
5212 The argument list of the specialization shall not be identical to
5213 the implicit argument list of the primary template. */
5214 tree main_args
5215 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (maintmpl)));
5216 if (comp_template_args (inner_args, INNERMOST_TEMPLATE_ARGS (main_args))
5217 && (!flag_concepts
5218 || !strictly_subsumes (current_template_constraints (), maintmpl)))
5220 if (!flag_concepts)
5221 error ("partial specialization %q+D does not specialize "
5222 "any template arguments; to define the primary template, "
5223 "remove the template argument list", decl);
5224 else
5225 error ("partial specialization %q+D does not specialize any "
5226 "template arguments and is not more constrained than "
5227 "the primary template; to define the primary template, "
5228 "remove the template argument list", decl);
5229 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5232 /* A partial specialization that replaces multiple parameters of the
5233 primary template with a pack expansion is less specialized for those
5234 parameters. */
5235 if (nargs < DECL_NTPARMS (maintmpl))
5237 error ("partial specialization is not more specialized than the "
5238 "primary template because it replaces multiple parameters "
5239 "with a pack expansion");
5240 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5241 /* Avoid crash in process_partial_specialization. */
5242 return decl;
5245 else if (nargs > DECL_NTPARMS (maintmpl))
5247 error ("too many arguments for partial specialization %qT", type);
5248 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5249 /* Avoid crash below. */
5250 return decl;
5253 /* If we aren't in a dependent class, we can actually try deduction. */
5254 else if (tpd.level == 1
5255 /* FIXME we should be able to handle a partial specialization of a
5256 partial instantiation, but currently we can't (c++/41727). */
5257 && TMPL_ARGS_DEPTH (specargs) == 1
5258 && !get_partial_spec_bindings (maintmpl, maintmpl, specargs))
5260 auto_diagnostic_group d;
5261 if (pedwarn (input_location, 0,
5262 "partial specialization %qD is not more specialized than",
5263 decl))
5264 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template %qD",
5265 maintmpl);
5268 /* [temp.spec.partial]
5270 The type of a template parameter corresponding to a specialized
5271 non-type argument shall not be dependent on a parameter of the
5272 specialization.
5274 Also, we verify that pack expansions only occur at the
5275 end of the argument list. */
5276 tpd2.parms = 0;
5277 for (i = 0; i < nargs; ++i)
5279 tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
5280 tree arg = TREE_VEC_ELT (inner_args, i);
5281 tree packed_args = NULL_TREE;
5282 int j, len = 1;
5284 if (ARGUMENT_PACK_P (arg))
5286 /* Extract the arguments from the argument pack. We'll be
5287 iterating over these in the following loop. */
5288 packed_args = ARGUMENT_PACK_ARGS (arg);
5289 len = TREE_VEC_LENGTH (packed_args);
5292 for (j = 0; j < len; j++)
5294 if (packed_args)
5295 /* Get the Jth argument in the parameter pack. */
5296 arg = TREE_VEC_ELT (packed_args, j);
5298 if (PACK_EXPANSION_P (arg))
5300 /* Pack expansions must come at the end of the
5301 argument list. */
5302 if ((packed_args && j < len - 1)
5303 || (!packed_args && i < nargs - 1))
5305 if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5306 error ("parameter pack argument %qE must be at the "
5307 "end of the template argument list", arg);
5308 else
5309 error ("parameter pack argument %qT must be at the "
5310 "end of the template argument list", arg);
5314 if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5315 /* We only care about the pattern. */
5316 arg = PACK_EXPANSION_PATTERN (arg);
5318 if (/* These first two lines are the `non-type' bit. */
5319 !TYPE_P (arg)
5320 && TREE_CODE (arg) != TEMPLATE_DECL
5321 /* This next two lines are the `argument expression is not just a
5322 simple identifier' condition and also the `specialized
5323 non-type argument' bit. */
5324 && TREE_CODE (arg) != TEMPLATE_PARM_INDEX
5325 && !((REFERENCE_REF_P (arg)
5326 || TREE_CODE (arg) == VIEW_CONVERT_EXPR)
5327 && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_PARM_INDEX))
5329 /* Look at the corresponding template parameter,
5330 marking which template parameters its type depends
5331 upon. */
5332 tree type = TREE_TYPE (parm);
5334 if (!tpd2.parms)
5336 /* We haven't yet initialized TPD2. Do so now. */
5337 tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
5338 /* The number of parameters here is the number in the
5339 main template, which, as checked in the assertion
5340 above, is NARGS. */
5341 tpd2.parms = XALLOCAVEC (int, nargs);
5342 tpd2.level =
5343 TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
5346 /* Mark the template parameters. But this time, we're
5347 looking for the template parameters of the main
5348 template, not in the specialization. */
5349 tpd2.current_arg = i;
5350 tpd2.arg_uses_template_parms[i] = 0;
5351 memset (tpd2.parms, 0, sizeof (int) * nargs);
5352 for_each_template_parm (type,
5353 &mark_template_parm,
5354 &tpd2,
5355 NULL,
5356 /*include_nondeduced_p=*/false);
5358 if (tpd2.arg_uses_template_parms [i])
5360 /* The type depended on some template parameters.
5361 If they are fully specialized in the
5362 specialization, that's OK. */
5363 int j;
5364 int count = 0;
5365 for (j = 0; j < nargs; ++j)
5366 if (tpd2.parms[j] != 0
5367 && tpd.arg_uses_template_parms [j])
5368 ++count;
5369 if (count != 0)
5370 error_n (input_location, count,
5371 "type %qT of template argument %qE depends "
5372 "on a template parameter",
5373 "type %qT of template argument %qE depends "
5374 "on template parameters",
5375 type,
5376 arg);
5382 /* We should only get here once. */
5383 if (TREE_CODE (decl) == TYPE_DECL)
5384 gcc_assert (!COMPLETE_TYPE_P (type));
5386 // Build the template decl.
5387 tree tmpl = build_template_decl (decl, current_template_parms,
5388 DECL_MEMBER_TEMPLATE_P (maintmpl));
5389 SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5390 DECL_TEMPLATE_INFO (tmpl) = build_template_info (maintmpl, specargs);
5391 DECL_PRIMARY_TEMPLATE (tmpl) = maintmpl;
5393 /* Give template template parms a DECL_CONTEXT of the template
5394 for which they are a parameter. */
5395 for (i = 0; i < ntparms; ++i)
5397 tree parm = TREE_VALUE (TREE_VEC_ELT (inner_parms, i));
5398 if (TREE_CODE (parm) == TEMPLATE_DECL)
5399 DECL_CONTEXT (parm) = tmpl;
5402 if (VAR_P (decl))
5403 /* We didn't register this in check_explicit_specialization so we could
5404 wait until the constraints were set. */
5405 decl = register_specialization (decl, maintmpl, specargs, false, 0);
5406 else
5407 associate_classtype_constraints (type);
5409 DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
5410 = tree_cons (specargs, tmpl,
5411 DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
5412 TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
5413 /* Link the DECL_TEMPLATE_RESULT back to the partial TEMPLATE_DECL. */
5414 gcc_checking_assert (!TI_PARTIAL_INFO (tinfo));
5415 TI_PARTIAL_INFO (tinfo) = build_template_info (tmpl, NULL_TREE);
5417 for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
5418 inst = TREE_CHAIN (inst))
5420 tree instance = TREE_VALUE (inst);
5421 if (TYPE_P (instance)
5422 ? (COMPLETE_TYPE_P (instance)
5423 && CLASSTYPE_IMPLICIT_INSTANTIATION (instance))
5424 : DECL_TEMPLATE_INSTANTIATION (instance))
5426 tree partial_ti = most_specialized_partial_spec (instance, tf_none,
5427 /*rechecking=*/true);
5428 tree inst_decl = (DECL_P (instance)
5429 ? instance : TYPE_NAME (instance));
5430 if (!partial_ti)
5431 /* OK */;
5432 else if (partial_ti == error_mark_node)
5433 permerror (input_location,
5434 "declaration of %qD ambiguates earlier template "
5435 "instantiation for %qD", decl, inst_decl);
5436 else if (TI_TEMPLATE (partial_ti) == tmpl)
5437 permerror (input_location,
5438 "partial specialization of %qD after instantiation "
5439 "of %qD", decl, inst_decl);
5443 return decl;
5446 /* PARM is a template parameter of some form; return the corresponding
5447 TEMPLATE_PARM_INDEX. */
5449 static tree
5450 get_template_parm_index (tree parm)
5452 if (TREE_CODE (parm) == PARM_DECL
5453 || TREE_CODE (parm) == CONST_DECL)
5454 parm = DECL_INITIAL (parm);
5455 else if (TREE_CODE (parm) == TYPE_DECL
5456 || TREE_CODE (parm) == TEMPLATE_DECL)
5457 parm = TREE_TYPE (parm);
5458 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
5459 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM
5460 || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
5461 parm = TEMPLATE_TYPE_PARM_INDEX (parm);
5462 gcc_assert (TREE_CODE (parm) == TEMPLATE_PARM_INDEX);
5463 return parm;
5466 /* Subroutine of fixed_parameter_pack_p below. Look for any template
5467 parameter packs used by the template parameter PARM. */
5469 static void
5470 fixed_parameter_pack_p_1 (tree parm, struct find_parameter_pack_data *ppd)
5472 /* A type parm can't refer to another parm. */
5473 if (TREE_CODE (parm) == TYPE_DECL || parm == error_mark_node)
5474 return;
5475 else if (TREE_CODE (parm) == PARM_DECL)
5477 cp_walk_tree (&TREE_TYPE (parm), &find_parameter_packs_r,
5478 ppd, ppd->visited);
5479 return;
5482 gcc_assert (TREE_CODE (parm) == TEMPLATE_DECL);
5484 tree vec = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
5485 for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
5487 tree p = TREE_VALUE (TREE_VEC_ELT (vec, i));
5488 if (template_parameter_pack_p (p))
5489 /* Any packs in the type are expanded by this parameter. */;
5490 else
5491 fixed_parameter_pack_p_1 (p, ppd);
5495 /* PARM is a template parameter pack. Return any parameter packs used in
5496 its type or the type of any of its template parameters. If there are
5497 any such packs, it will be instantiated into a fixed template parameter
5498 list by partial instantiation rather than be fully deduced. */
5500 tree
5501 fixed_parameter_pack_p (tree parm)
5503 /* This can only be true in a member template. */
5504 if (TEMPLATE_PARM_ORIG_LEVEL (get_template_parm_index (parm)) < 2)
5505 return NULL_TREE;
5506 /* This can only be true for a parameter pack. */
5507 if (!template_parameter_pack_p (parm))
5508 return NULL_TREE;
5509 /* A type parm can't refer to another parm. */
5510 if (TREE_CODE (parm) == TYPE_DECL)
5511 return NULL_TREE;
5513 tree parameter_packs = NULL_TREE;
5514 struct find_parameter_pack_data ppd;
5515 ppd.parameter_packs = &parameter_packs;
5516 ppd.visited = new hash_set<tree>;
5517 ppd.type_pack_expansion_p = false;
5519 fixed_parameter_pack_p_1 (parm, &ppd);
5521 delete ppd.visited;
5522 return parameter_packs;
5525 /* Check that a template declaration's use of default arguments and
5526 parameter packs is not invalid. Here, PARMS are the template
5527 parameters. IS_PRIMARY is true if DECL is the thing declared by
5528 a primary template. IS_PARTIAL is true if DECL is a partial
5529 specialization.
5531 IS_FRIEND_DECL is nonzero if DECL is either a non-defining friend
5532 function template declaration or a friend class template
5533 declaration. In the function case, 1 indicates a declaration, 2
5534 indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
5535 emitted for extraneous default arguments.
5537 Returns TRUE if there were no errors found, FALSE otherwise. */
5539 bool
5540 check_default_tmpl_args (tree decl, tree parms, bool is_primary,
5541 bool is_partial, int is_friend_decl)
5543 const char *msg;
5544 int last_level_to_check;
5545 tree parm_level;
5546 bool no_errors = true;
5548 /* [temp.param]
5550 A default template-argument shall not be specified in a
5551 function template declaration or a function template definition, nor
5552 in the template-parameter-list of the definition of a member of a
5553 class template. */
5555 if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL
5556 || (TREE_CODE (decl) == FUNCTION_DECL && DECL_LOCAL_DECL_P (decl)))
5557 /* You can't have a function template declaration in a local
5558 scope, nor you can you define a member of a class template in a
5559 local scope. */
5560 return true;
5562 if ((TREE_CODE (decl) == TYPE_DECL
5563 && TREE_TYPE (decl)
5564 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5565 || (TREE_CODE (decl) == FUNCTION_DECL
5566 && LAMBDA_FUNCTION_P (decl)))
5567 /* A lambda doesn't have an explicit declaration; don't complain
5568 about the parms of the enclosing class. */
5569 return true;
5571 if (current_class_type
5572 && !TYPE_BEING_DEFINED (current_class_type)
5573 && DECL_LANG_SPECIFIC (decl)
5574 && DECL_DECLARES_FUNCTION_P (decl)
5575 /* If this is either a friend defined in the scope of the class
5576 or a member function. */
5577 && (DECL_FUNCTION_MEMBER_P (decl)
5578 ? same_type_p (DECL_CONTEXT (decl), current_class_type)
5579 : DECL_FRIEND_CONTEXT (decl)
5580 ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
5581 : false)
5582 /* And, if it was a member function, it really was defined in
5583 the scope of the class. */
5584 && (!DECL_FUNCTION_MEMBER_P (decl)
5585 || DECL_INITIALIZED_IN_CLASS_P (decl)))
5586 /* We already checked these parameters when the template was
5587 declared, so there's no need to do it again now. This function
5588 was defined in class scope, but we're processing its body now
5589 that the class is complete. */
5590 return true;
5592 /* Core issue 226 (C++0x only): the following only applies to class
5593 templates. */
5594 if (is_primary
5595 && ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL))
5597 /* [temp.param]
5599 If a template-parameter has a default template-argument, all
5600 subsequent template-parameters shall have a default
5601 template-argument supplied. */
5602 for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
5604 tree inner_parms = TREE_VALUE (parm_level);
5605 int ntparms = TREE_VEC_LENGTH (inner_parms);
5606 int seen_def_arg_p = 0;
5607 int i;
5609 for (i = 0; i < ntparms; ++i)
5611 tree parm = TREE_VEC_ELT (inner_parms, i);
5613 if (parm == error_mark_node)
5614 continue;
5616 if (TREE_PURPOSE (parm))
5617 seen_def_arg_p = 1;
5618 else if (seen_def_arg_p
5619 && !template_parameter_pack_p (TREE_VALUE (parm)))
5621 error ("no default argument for %qD", TREE_VALUE (parm));
5622 /* For better subsequent error-recovery, we indicate that
5623 there should have been a default argument. */
5624 TREE_PURPOSE (parm) = error_mark_node;
5625 no_errors = false;
5627 else if (!is_partial
5628 && !is_friend_decl
5629 /* Don't complain about an enclosing partial
5630 specialization. */
5631 && parm_level == parms
5632 && (TREE_CODE (decl) == TYPE_DECL || VAR_P (decl))
5633 && i < ntparms - 1
5634 && template_parameter_pack_p (TREE_VALUE (parm))
5635 /* A fixed parameter pack will be partially
5636 instantiated into a fixed length list. */
5637 && !fixed_parameter_pack_p (TREE_VALUE (parm)))
5639 /* A primary class template, primary variable template
5640 (DR 2032), or alias template can only have one
5641 parameter pack, at the end of the template
5642 parameter list. */
5644 error ("parameter pack %q+D must be at the end of the"
5645 " template parameter list", TREE_VALUE (parm));
5647 TREE_VALUE (TREE_VEC_ELT (inner_parms, i))
5648 = error_mark_node;
5649 no_errors = false;
5655 if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
5656 || is_partial
5657 || !is_primary
5658 || is_friend_decl)
5659 /* For an ordinary class template, default template arguments are
5660 allowed at the innermost level, e.g.:
5661 template <class T = int>
5662 struct S {};
5663 but, in a partial specialization, they're not allowed even
5664 there, as we have in [temp.class.spec]:
5666 The template parameter list of a specialization shall not
5667 contain default template argument values.
5669 So, for a partial specialization, or for a function template
5670 (in C++98/C++03), we look at all of them. */
5672 else
5673 /* But, for a primary class template that is not a partial
5674 specialization we look at all template parameters except the
5675 innermost ones. */
5676 parms = TREE_CHAIN (parms);
5678 /* Figure out what error message to issue. */
5679 if (is_friend_decl == 2)
5680 msg = G_("default template arguments may not be used in function template "
5681 "friend re-declaration");
5682 else if (is_friend_decl)
5683 msg = G_("default template arguments may not be used in template "
5684 "friend declarations");
5685 else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
5686 msg = G_("default template arguments may not be used in function templates "
5687 "without %<-std=c++11%> or %<-std=gnu++11%>");
5688 else if (is_partial)
5689 msg = G_("default template arguments may not be used in "
5690 "partial specializations");
5691 else if (current_class_type && CLASSTYPE_IS_TEMPLATE (current_class_type))
5692 msg = G_("default argument for template parameter for class enclosing %qD");
5693 else
5694 /* Per [temp.param]/9, "A default template-argument shall not be
5695 specified in the template-parameter-lists of the definition of
5696 a member of a class template that appears outside of the member's
5697 class.", thus if we aren't handling a member of a class template
5698 there is no need to examine the parameters. */
5699 return true;
5701 if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
5702 /* If we're inside a class definition, there's no need to
5703 examine the parameters to the class itself. On the one
5704 hand, they will be checked when the class is defined, and,
5705 on the other, default arguments are valid in things like:
5706 template <class T = double>
5707 struct S { template <class U> void f(U); };
5708 Here the default argument for `S' has no bearing on the
5709 declaration of `f'. */
5710 last_level_to_check = template_class_depth (current_class_type) + 1;
5711 else
5712 /* Check everything. */
5713 last_level_to_check = 0;
5715 for (parm_level = parms;
5716 parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
5717 parm_level = TREE_CHAIN (parm_level))
5719 tree inner_parms = TREE_VALUE (parm_level);
5720 int i;
5721 int ntparms;
5723 ntparms = TREE_VEC_LENGTH (inner_parms);
5724 for (i = 0; i < ntparms; ++i)
5726 if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
5727 continue;
5729 if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
5731 if (msg)
5733 no_errors = false;
5734 if (is_friend_decl == 2)
5735 return no_errors;
5737 error (msg, decl);
5738 msg = 0;
5741 /* Clear out the default argument so that we are not
5742 confused later. */
5743 TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
5747 /* At this point, if we're still interested in issuing messages,
5748 they must apply to classes surrounding the object declared. */
5749 if (msg)
5750 msg = G_("default argument for template parameter for class "
5751 "enclosing %qD");
5754 return no_errors;
5757 /* Worker for push_template_decl_real, called via
5758 for_each_template_parm. DATA is really an int, indicating the
5759 level of the parameters we are interested in. If T is a template
5760 parameter of that level, return nonzero. */
5762 static int
5763 template_parm_this_level_p (tree t, void* data)
5765 int this_level = *(int *)data;
5766 int level;
5768 if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5769 level = TEMPLATE_PARM_LEVEL (t);
5770 else
5771 level = TEMPLATE_TYPE_LEVEL (t);
5772 return level == this_level;
5775 /* Worker for uses_outer_template_parms, called via for_each_template_parm.
5776 DATA is really an int, indicating the innermost outer level of parameters.
5777 If T is a template parameter of that level or further out, return
5778 nonzero. */
5780 static int
5781 template_parm_outer_level (tree t, void *data)
5783 int this_level = *(int *)data;
5784 int level;
5786 if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5787 level = TEMPLATE_PARM_LEVEL (t);
5788 else
5789 level = TEMPLATE_TYPE_LEVEL (t);
5790 return level <= this_level;
5793 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
5794 parameters given by current_template_args, or reuses a
5795 previously existing one, if appropriate. Returns the DECL, or an
5796 equivalent one, if it is replaced via a call to duplicate_decls.
5798 If IS_FRIEND is true, DECL is a friend declaration. */
5800 tree
5801 push_template_decl (tree decl, bool is_friend)
5803 if (decl == error_mark_node || !current_template_parms)
5804 return error_mark_node;
5806 /* See if this is a partial specialization. */
5807 bool is_partial = ((DECL_IMPLICIT_TYPEDEF_P (decl)
5808 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
5809 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
5810 || (VAR_P (decl)
5811 && DECL_LANG_SPECIFIC (decl)
5812 && DECL_TEMPLATE_SPECIALIZATION (decl)
5813 && TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl))));
5815 /* No surprising friend functions. */
5816 gcc_checking_assert (is_friend
5817 || !(TREE_CODE (decl) == FUNCTION_DECL
5818 && DECL_UNIQUE_FRIEND_P (decl)));
5820 tree ctx;
5821 if (is_friend)
5822 /* For a friend, we want the context of the friend, not
5823 the type of which it is a friend. */
5824 ctx = CP_DECL_CONTEXT (decl);
5825 else if (CP_DECL_CONTEXT (decl)
5826 && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
5827 /* In the case of a virtual function, we want the class in which
5828 it is defined. */
5829 ctx = CP_DECL_CONTEXT (decl);
5830 else
5831 /* Otherwise, if we're currently defining some class, the DECL
5832 is assumed to be a member of the class. */
5833 ctx = current_scope ();
5835 if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
5836 ctx = NULL_TREE;
5838 if (!DECL_CONTEXT (decl))
5839 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5841 /* See if this is a primary template. */
5842 bool is_primary = false;
5843 if (is_friend && ctx
5844 && uses_template_parms_level (ctx, current_template_depth))
5845 /* A friend template that specifies a class context, i.e.
5846 template <typename T> friend void A<T>::f();
5847 is not primary. */
5849 else if (TREE_CODE (decl) == TYPE_DECL && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5850 /* Lambdas are not primary. */
5852 else
5853 is_primary = template_parm_scope_p ();
5855 /* True if the template is a member template, in the sense of
5856 [temp.mem]. */
5857 bool member_template_p = false;
5859 if (is_primary)
5861 warning (OPT_Wtemplates, "template %qD declared", decl);
5863 if (DECL_CLASS_SCOPE_P (decl))
5864 member_template_p = true;
5866 if (TREE_CODE (decl) == TYPE_DECL
5867 && IDENTIFIER_ANON_P (DECL_NAME (decl)))
5869 error ("template class without a name");
5870 return error_mark_node;
5872 else if (TREE_CODE (decl) == FUNCTION_DECL)
5874 if (member_template_p)
5876 if (DECL_OVERRIDE_P (decl) || DECL_FINAL_P (decl))
5877 error ("member template %qD may not have virt-specifiers", decl);
5879 if (DECL_DESTRUCTOR_P (decl))
5881 /* [temp.mem]
5883 A destructor shall not be a member template. */
5884 error_at (DECL_SOURCE_LOCATION (decl),
5885 "destructor %qD declared as member template", decl);
5886 return error_mark_node;
5888 if (IDENTIFIER_NEWDEL_OP_P (DECL_NAME (decl))
5889 && (!prototype_p (TREE_TYPE (decl))
5890 || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
5891 || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5892 || (TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5893 == void_list_node)))
5895 /* [basic.stc.dynamic.allocation]
5897 An allocation function can be a function
5898 template. ... Template allocation functions shall
5899 have two or more parameters. */
5900 error ("invalid template declaration of %qD", decl);
5901 return error_mark_node;
5904 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5905 && CLASS_TYPE_P (TREE_TYPE (decl)))
5906 /* Class template. */;
5907 else if (TREE_CODE (decl) == TYPE_DECL
5908 && TYPE_DECL_ALIAS_P (decl))
5909 /* alias-declaration */
5910 gcc_assert (!DECL_ARTIFICIAL (decl));
5911 else if (VAR_P (decl))
5912 /* C++14 variable template. */;
5913 else if (TREE_CODE (decl) == CONCEPT_DECL)
5914 /* C++20 concept definitions. */;
5915 else
5917 error ("template declaration of %q#D", decl);
5918 return error_mark_node;
5922 bool local_p = (!DECL_IMPLICIT_TYPEDEF_P (decl)
5923 && ((ctx && TREE_CODE (ctx) == FUNCTION_DECL)
5924 || (VAR_OR_FUNCTION_DECL_P (decl)
5925 && DECL_LOCAL_DECL_P (decl))));
5927 /* Check to see that the rules regarding the use of default
5928 arguments are not being violated. We check args for a friend
5929 functions when we know whether it's a definition, introducing
5930 declaration or re-declaration. */
5931 if (!local_p && (!is_friend || TREE_CODE (decl) != FUNCTION_DECL))
5932 check_default_tmpl_args (decl, current_template_parms,
5933 is_primary, is_partial, is_friend);
5935 /* Ensure that there are no parameter packs in the type of this
5936 declaration that have not been expanded. */
5937 if (TREE_CODE (decl) == FUNCTION_DECL)
5939 /* Check each of the arguments individually to see if there are
5940 any bare parameter packs. */
5941 tree type = TREE_TYPE (decl);
5942 tree arg = DECL_ARGUMENTS (decl);
5943 tree argtype = TYPE_ARG_TYPES (type);
5945 while (arg && argtype)
5947 if (!DECL_PACK_P (arg)
5948 && check_for_bare_parameter_packs (TREE_TYPE (arg)))
5950 /* This is a PARM_DECL that contains unexpanded parameter
5951 packs. We have already complained about this in the
5952 check_for_bare_parameter_packs call, so just replace
5953 these types with ERROR_MARK_NODE. */
5954 TREE_TYPE (arg) = error_mark_node;
5955 TREE_VALUE (argtype) = error_mark_node;
5958 arg = DECL_CHAIN (arg);
5959 argtype = TREE_CHAIN (argtype);
5962 /* Check for bare parameter packs in the return type and the
5963 exception specifiers. */
5964 if (check_for_bare_parameter_packs (TREE_TYPE (type)))
5965 /* Errors were already issued, set return type to int
5966 as the frontend doesn't expect error_mark_node as
5967 the return type. */
5968 TREE_TYPE (type) = integer_type_node;
5969 if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
5970 TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
5972 else
5974 if (check_for_bare_parameter_packs (is_typedef_decl (decl)
5975 ? DECL_ORIGINAL_TYPE (decl)
5976 : TREE_TYPE (decl)))
5978 TREE_TYPE (decl) = error_mark_node;
5979 return error_mark_node;
5982 if (is_partial && VAR_P (decl)
5983 && check_for_bare_parameter_packs (DECL_TI_ARGS (decl)))
5984 return error_mark_node;
5987 if (is_partial)
5988 return process_partial_specialization (decl);
5990 tree args = current_template_args ();
5991 tree tmpl = NULL_TREE;
5992 bool new_template_p = false;
5993 if (local_p)
5995 /* Does not get a template head. */
5996 tmpl = NULL_TREE;
5997 gcc_checking_assert (!is_primary);
5999 else if (!ctx
6000 || TREE_CODE (ctx) == FUNCTION_DECL
6001 || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
6002 || (TREE_CODE (decl) == TYPE_DECL && LAMBDA_TYPE_P (TREE_TYPE (decl)))
6003 || (is_friend && !(DECL_LANG_SPECIFIC (decl)
6004 && DECL_TEMPLATE_INFO (decl))))
6006 if (DECL_LANG_SPECIFIC (decl)
6007 && DECL_TEMPLATE_INFO (decl)
6008 && DECL_TI_TEMPLATE (decl))
6009 tmpl = DECL_TI_TEMPLATE (decl);
6010 /* If DECL is a TYPE_DECL for a class-template, then there won't
6011 be DECL_LANG_SPECIFIC. The information equivalent to
6012 DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead. */
6013 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
6014 && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
6015 && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
6017 /* Since a template declaration already existed for this
6018 class-type, we must be redeclaring it here. Make sure
6019 that the redeclaration is valid. */
6020 redeclare_class_template (TREE_TYPE (decl),
6021 current_template_parms,
6022 current_template_constraints ());
6023 /* We don't need to create a new TEMPLATE_DECL; just use the
6024 one we already had. */
6025 tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
6027 else
6029 tmpl = build_template_decl (decl, current_template_parms,
6030 member_template_p);
6031 new_template_p = true;
6033 if (DECL_LANG_SPECIFIC (decl)
6034 && DECL_TEMPLATE_SPECIALIZATION (decl))
6036 /* A specialization of a member template of a template
6037 class. */
6038 SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
6039 DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
6040 DECL_TEMPLATE_INFO (decl) = NULL_TREE;
6044 else
6046 tree a, t, current, parms;
6047 int i;
6048 tree tinfo = get_template_info (decl);
6050 if (!tinfo)
6052 error ("template definition of non-template %q#D", decl);
6053 return error_mark_node;
6056 tmpl = TI_TEMPLATE (tinfo);
6058 if (DECL_FUNCTION_TEMPLATE_P (tmpl)
6059 && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
6060 && DECL_TEMPLATE_SPECIALIZATION (decl)
6061 && DECL_MEMBER_TEMPLATE_P (tmpl))
6063 /* The declaration is a specialization of a member
6064 template, declared outside the class. Therefore, the
6065 innermost template arguments will be NULL, so we
6066 replace them with the arguments determined by the
6067 earlier call to check_explicit_specialization. */
6068 args = DECL_TI_ARGS (decl);
6070 tree new_tmpl
6071 = build_template_decl (decl, current_template_parms,
6072 member_template_p);
6073 DECL_TI_TEMPLATE (decl) = new_tmpl;
6074 SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
6075 DECL_TEMPLATE_INFO (new_tmpl)
6076 = build_template_info (tmpl, args);
6078 register_specialization (new_tmpl,
6079 most_general_template (tmpl),
6080 args,
6081 is_friend, 0);
6082 return decl;
6085 /* Make sure the template headers we got make sense. */
6087 parms = DECL_TEMPLATE_PARMS (tmpl);
6088 i = TMPL_PARMS_DEPTH (parms);
6089 if (TMPL_ARGS_DEPTH (args) != i)
6091 error ("expected %d levels of template parms for %q#D, got %d",
6092 i, decl, TMPL_ARGS_DEPTH (args));
6093 DECL_INTERFACE_KNOWN (decl) = 1;
6094 return error_mark_node;
6096 else
6097 for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
6099 a = TMPL_ARGS_LEVEL (args, i);
6100 t = INNERMOST_TEMPLATE_PARMS (parms);
6102 if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
6104 if (current == decl)
6105 error ("got %d template parameters for %q#D",
6106 TREE_VEC_LENGTH (a), decl);
6107 else
6108 error ("got %d template parameters for %q#T",
6109 TREE_VEC_LENGTH (a), current);
6110 error (" but %d required", TREE_VEC_LENGTH (t));
6111 /* Avoid crash in import_export_decl. */
6112 DECL_INTERFACE_KNOWN (decl) = 1;
6113 return error_mark_node;
6116 if (current == decl)
6117 current = ctx;
6118 else if (current == NULL_TREE)
6119 /* Can happen in erroneous input. */
6120 break;
6121 else
6122 current = get_containing_scope (current);
6125 /* Check that the parms are used in the appropriate qualifying scopes
6126 in the declarator. */
6127 if (!comp_template_args
6128 (TI_ARGS (tinfo),
6129 TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
6131 error ("template arguments to %qD do not match original "
6132 "template %qD", decl, DECL_TEMPLATE_RESULT (tmpl));
6133 if (!uses_template_parms (TI_ARGS (tinfo)))
6134 inform (input_location, "use %<template<>%> for"
6135 " an explicit specialization");
6136 /* Avoid crash in import_export_decl. */
6137 DECL_INTERFACE_KNOWN (decl) = 1;
6138 return error_mark_node;
6141 /* Check that the constraints for each enclosing template scope are
6142 consistent with the original declarations. */
6143 if (flag_concepts)
6145 tree decl_parms = DECL_TEMPLATE_PARMS (tmpl);
6146 tree scope_parms = current_template_parms;
6147 if (PRIMARY_TEMPLATE_P (tmpl))
6149 decl_parms = TREE_CHAIN (decl_parms);
6150 scope_parms = TREE_CHAIN (scope_parms);
6152 while (decl_parms)
6154 if (!template_requirements_equivalent_p (decl_parms, scope_parms))
6156 error ("redeclaration of %qD with different constraints",
6157 TPARMS_PRIMARY_TEMPLATE (TREE_VALUE (decl_parms)));
6158 break;
6160 decl_parms = TREE_CHAIN (decl_parms);
6161 scope_parms = TREE_CHAIN (scope_parms);
6166 gcc_checking_assert (!tmpl || DECL_TEMPLATE_RESULT (tmpl) == decl);
6168 if (new_template_p)
6170 /* Push template declarations for global functions and types.
6171 Note that we do not try to push a global template friend
6172 declared in a template class; such a thing may well depend on
6173 the template parameters of the class and we'll push it when
6174 instantiating the befriending class. */
6175 if (!ctx
6176 && !(is_friend && template_class_depth (current_class_type) > 0))
6178 tree pushed = pushdecl_namespace_level (tmpl, /*hiding=*/is_friend);
6179 if (pushed == error_mark_node)
6180 return error_mark_node;
6182 /* pushdecl may have found an existing template. */
6183 if (pushed != tmpl)
6185 decl = DECL_TEMPLATE_RESULT (pushed);
6186 tmpl = NULL_TREE;
6189 else if (is_friend)
6191 /* Record this decl as belonging to the current class. It's
6192 not chained onto anything else. */
6193 DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (tmpl) = true;
6194 gcc_checking_assert (!DECL_CHAIN (tmpl));
6195 DECL_CHAIN (tmpl) = current_scope ();
6198 else if (tmpl)
6199 /* The type may have been completed, or (erroneously) changed. */
6200 TREE_TYPE (tmpl) = TREE_TYPE (decl);
6202 if (tmpl)
6204 if (is_primary)
6206 tree parms = DECL_TEMPLATE_PARMS (tmpl);
6208 DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
6210 /* Give template template parms a DECL_CONTEXT of the template
6211 for which they are a parameter. */
6212 parms = INNERMOST_TEMPLATE_PARMS (parms);
6213 for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
6215 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
6216 if (TREE_CODE (parm) == TEMPLATE_DECL)
6217 DECL_CONTEXT (parm) = tmpl;
6220 if (TREE_CODE (decl) == TYPE_DECL
6221 && TYPE_DECL_ALIAS_P (decl))
6223 if (tree constr
6224 = TEMPLATE_PARMS_CONSTRAINTS (DECL_TEMPLATE_PARMS (tmpl)))
6226 /* ??? Why don't we do this here for all templates? */
6227 constr = build_constraints (constr, NULL_TREE);
6228 set_constraints (decl, constr);
6230 if (complex_alias_template_p (tmpl))
6231 TEMPLATE_DECL_COMPLEX_ALIAS_P (tmpl) = true;
6235 /* The DECL_TI_ARGS of DECL contains full set of arguments
6236 referring wback to its most general template. If TMPL is a
6237 specialization, ARGS may only have the innermost set of
6238 arguments. Add the missing argument levels if necessary. */
6239 if (DECL_TEMPLATE_INFO (tmpl))
6240 args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
6242 tree info = build_template_info (tmpl, args);
6244 if (DECL_IMPLICIT_TYPEDEF_P (decl))
6245 SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
6246 else
6248 retrofit_lang_decl (decl);
6249 DECL_TEMPLATE_INFO (decl) = info;
6253 if (flag_implicit_templates
6254 && !is_friend
6255 && TREE_PUBLIC (decl)
6256 && VAR_OR_FUNCTION_DECL_P (decl))
6257 /* Set DECL_COMDAT on template instantiations; if we force
6258 them to be emitted by explicit instantiation,
6259 mark_needed will tell cgraph to do the right thing. */
6260 DECL_COMDAT (decl) = true;
6262 gcc_checking_assert (!tmpl || DECL_TEMPLATE_RESULT (tmpl) == decl);
6264 return decl;
6267 /* FN is an inheriting constructor that inherits from the constructor
6268 template INHERITED; turn FN into a constructor template with a matching
6269 template header. */
6271 tree
6272 add_inherited_template_parms (tree fn, tree inherited)
6274 tree inner_parms
6275 = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (inherited));
6276 inner_parms = copy_node (inner_parms);
6277 tree parms
6278 = tree_cons (size_int (current_template_depth + 1),
6279 inner_parms, current_template_parms);
6280 tree tmpl = build_template_decl (fn, parms, /*member*/true);
6281 tree args = template_parms_to_args (parms);
6282 DECL_TEMPLATE_INFO (fn) = build_template_info (tmpl, args);
6283 DECL_ARTIFICIAL (tmpl) = true;
6284 DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
6285 return tmpl;
6288 /* Called when a class template TYPE is redeclared with the indicated
6289 template PARMS, e.g.:
6291 template <class T> struct S;
6292 template <class T> struct S {}; */
6294 bool
6295 redeclare_class_template (tree type, tree parms, tree cons)
6297 tree tmpl;
6298 tree tmpl_parms;
6299 int i;
6301 if (!TYPE_TEMPLATE_INFO (type))
6303 error ("%qT is not a template type", type);
6304 return false;
6307 tmpl = TYPE_TI_TEMPLATE (type);
6308 if (!PRIMARY_TEMPLATE_P (tmpl))
6309 /* The type is nested in some template class. Nothing to worry
6310 about here; there are no new template parameters for the nested
6311 type. */
6312 return true;
6314 if (!parms)
6316 error ("template specifiers not specified in declaration of %qD",
6317 tmpl);
6318 return false;
6321 parms = INNERMOST_TEMPLATE_PARMS (parms);
6322 tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
6324 if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
6326 error_n (input_location, TREE_VEC_LENGTH (parms),
6327 "redeclared with %d template parameter",
6328 "redeclared with %d template parameters",
6329 TREE_VEC_LENGTH (parms));
6330 inform_n (DECL_SOURCE_LOCATION (tmpl), TREE_VEC_LENGTH (tmpl_parms),
6331 "previous declaration %qD used %d template parameter",
6332 "previous declaration %qD used %d template parameters",
6333 tmpl, TREE_VEC_LENGTH (tmpl_parms));
6334 return false;
6337 for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
6339 tree tmpl_parm;
6340 tree parm;
6342 if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
6343 || TREE_VEC_ELT (parms, i) == error_mark_node)
6344 continue;
6346 tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
6347 if (error_operand_p (tmpl_parm))
6348 return false;
6350 parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
6352 /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
6353 TEMPLATE_DECL. */
6354 if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
6355 || (TREE_CODE (tmpl_parm) != TYPE_DECL
6356 && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
6357 || (TREE_CODE (tmpl_parm) != PARM_DECL
6358 && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
6359 != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
6360 || (TREE_CODE (tmpl_parm) == PARM_DECL
6361 && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
6362 != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
6364 auto_diagnostic_group d;
6365 error ("template parameter %q+#D", tmpl_parm);
6366 if (DECL_P (parm))
6367 inform (DECL_SOURCE_LOCATION (parm), "redeclared here as %q#D", parm);
6368 else
6369 inform (input_location, "redeclared here");
6370 return false;
6373 /* The parameters can be declared to introduce different
6374 constraints. */
6375 tree p1 = TREE_VEC_ELT (tmpl_parms, i);
6376 tree p2 = TREE_VEC_ELT (parms, i);
6377 if (!template_parameter_constraints_equivalent_p (p1, p2))
6379 auto_diagnostic_group d;
6380 error ("declaration of template parameter %q+#D with different "
6381 "constraints", parm);
6382 inform (DECL_SOURCE_LOCATION (tmpl_parm),
6383 "original declaration appeared here");
6384 return false;
6387 /* Give each template template parm in this redeclaration a
6388 DECL_CONTEXT of the template for which they are a parameter. */
6389 if (TREE_CODE (parm) == TEMPLATE_DECL)
6391 gcc_checking_assert (DECL_CONTEXT (parm) == NULL_TREE
6392 || DECL_CONTEXT (parm) == tmpl);
6393 DECL_CONTEXT (parm) = tmpl;
6397 if (!merge_default_template_args (parms, tmpl_parms, /*class_p=*/true))
6398 return false;
6400 tree ci = get_constraints (tmpl);
6401 tree req1 = ci ? CI_TEMPLATE_REQS (ci) : NULL_TREE;
6402 tree req2 = cons ? CI_TEMPLATE_REQS (cons) : NULL_TREE;
6404 /* Two classes with different constraints declare different entities. */
6405 if (!cp_tree_equal (req1, req2))
6407 auto_diagnostic_group d;
6408 error_at (input_location, "redeclaration of %q#D with different "
6409 "constraints", tmpl);
6410 inform (DECL_SOURCE_LOCATION (tmpl),
6411 "original declaration appeared here");
6412 return false;
6415 return true;
6418 /* The actual substitution part of instantiate_non_dependent_expr,
6419 to be used when the caller has already checked
6420 !instantiation_dependent_uneval_expression_p (expr)
6421 and cleared processing_template_decl. */
6423 tree
6424 instantiate_non_dependent_expr_internal (tree expr, tsubst_flags_t complain)
6426 return tsubst_copy_and_build (expr,
6427 /*args=*/NULL_TREE,
6428 complain,
6429 /*in_decl=*/NULL_TREE);
6432 /* Instantiate the non-dependent expression EXPR. */
6434 tree
6435 instantiate_non_dependent_expr (tree expr,
6436 tsubst_flags_t complain /* = tf_error */)
6438 if (expr == NULL_TREE)
6439 return NULL_TREE;
6441 if (processing_template_decl)
6443 /* The caller should have checked this already. */
6444 gcc_checking_assert (!instantiation_dependent_uneval_expression_p (expr));
6445 processing_template_decl_sentinel s;
6446 expr = instantiate_non_dependent_expr_internal (expr, complain);
6448 return expr;
6451 /* Like instantiate_non_dependent_expr, but return NULL_TREE if the
6452 expression is dependent or non-constant. */
6454 tree
6455 instantiate_non_dependent_or_null (tree expr)
6457 if (expr == NULL_TREE)
6458 return NULL_TREE;
6459 if (processing_template_decl)
6461 if (!is_nondependent_constant_expression (expr))
6462 expr = NULL_TREE;
6463 else
6465 processing_template_decl_sentinel s;
6466 expr = instantiate_non_dependent_expr_internal (expr, tf_error);
6469 return expr;
6472 /* True iff T is a specialization of a variable template. */
6474 bool
6475 variable_template_specialization_p (tree t)
6477 if (!VAR_P (t) || !DECL_LANG_SPECIFIC (t) || !DECL_TEMPLATE_INFO (t))
6478 return false;
6479 tree tmpl = DECL_TI_TEMPLATE (t);
6480 return variable_template_p (tmpl);
6483 /* Return TRUE iff T is a type alias, a TEMPLATE_DECL for an alias
6484 template declaration, or a TYPE_DECL for an alias declaration. */
6486 bool
6487 alias_type_or_template_p (tree t)
6489 if (t == NULL_TREE)
6490 return false;
6491 return ((TREE_CODE (t) == TYPE_DECL && TYPE_DECL_ALIAS_P (t))
6492 || (TYPE_P (t)
6493 && TYPE_NAME (t)
6494 && TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
6495 || DECL_ALIAS_TEMPLATE_P (t));
6498 /* If T is a specialization of an alias template, return it; otherwise return
6499 NULL_TREE. If TRANSPARENT_TYPEDEFS is true, look through other aliases. */
6501 tree
6502 alias_template_specialization_p (const_tree t,
6503 bool transparent_typedefs)
6505 if (!TYPE_P (t))
6506 return NULL_TREE;
6508 /* It's an alias template specialization if it's an alias and its
6509 TYPE_NAME is a specialization of a primary template. */
6510 if (typedef_variant_p (t))
6512 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
6513 if (PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo)))
6514 return CONST_CAST_TREE (t);
6515 if (transparent_typedefs)
6516 return alias_template_specialization_p (DECL_ORIGINAL_TYPE
6517 (TYPE_NAME (t)),
6518 transparent_typedefs);
6521 return NULL_TREE;
6524 /* Data structure for complex_alias_template_*. */
6526 struct uses_all_template_parms_data
6528 int level;
6529 bool *seen;
6532 /* walk_tree callback for complex_alias_template_p. */
6534 static tree
6535 complex_alias_template_r (tree *tp, int *walk_subtrees, void *data_)
6537 tree t = *tp;
6538 auto &data = *(struct uses_all_template_parms_data*)data_;
6540 switch (TREE_CODE (t))
6542 case TEMPLATE_TYPE_PARM:
6543 case TEMPLATE_PARM_INDEX:
6544 case TEMPLATE_TEMPLATE_PARM:
6545 case BOUND_TEMPLATE_TEMPLATE_PARM:
6547 tree idx = get_template_parm_index (t);
6548 if (TEMPLATE_PARM_LEVEL (idx) == data.level)
6549 data.seen[TEMPLATE_PARM_IDX (idx)] = true;
6552 default:;
6555 if (!PACK_EXPANSION_P (t))
6556 return 0;
6558 /* An alias template with a pack expansion that expands a pack from the
6559 enclosing class needs to be considered complex, to avoid confusion with
6560 the same pack being used as an argument to the alias's own template
6561 parameter (91966). */
6562 for (tree pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
6563 pack = TREE_CHAIN (pack))
6565 tree parm_pack = TREE_VALUE (pack);
6566 if (!TEMPLATE_PARM_P (parm_pack))
6567 continue;
6568 int idx, level;
6569 template_parm_level_and_index (parm_pack, &level, &idx);
6570 if (level < data.level)
6571 return t;
6573 /* Consider the expanded packs to be used outside the expansion... */
6574 data.seen[idx] = true;
6577 /* ...but don't walk into the pattern. Consider PR104008:
6579 template <typename T, typename... Ts>
6580 using IsOneOf = disjunction<is_same<T, Ts>...>;
6582 where IsOneOf seemingly uses all of its template parameters in its
6583 expansion (and does not expand a pack from the enclosing class), so the
6584 alias was not marked as complex. However, if it is used like
6585 "IsOneOf<T>", the empty pack for Ts means that T no longer appears in the
6586 expansion. So only Ts is considered used by the pack expansion. */
6587 *walk_subtrees = false;
6589 return 0;
6592 /* An alias template is complex from a SFINAE perspective if a template-id
6593 using that alias can be ill-formed when the expansion is not, as with
6594 the void_t template.
6596 Returns 1 if always complex, 0 if not complex, -1 if complex iff any of the
6597 template arguments are empty packs. */
6599 static bool
6600 complex_alias_template_p (const_tree tmpl)
6602 /* A renaming alias isn't complex. */
6603 if (get_underlying_template (CONST_CAST_TREE (tmpl)) != tmpl)
6604 return false;
6606 /* Any other constrained alias is complex. */
6607 if (get_constraints (tmpl))
6608 return true;
6610 struct uses_all_template_parms_data data;
6611 tree pat = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6612 tree parms = DECL_TEMPLATE_PARMS (tmpl);
6613 data.level = TMPL_PARMS_DEPTH (parms);
6614 int len = TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS (parms));
6615 data.seen = XALLOCAVEC (bool, len);
6616 for (int i = 0; i < len; ++i)
6617 data.seen[i] = false;
6619 if (cp_walk_tree_without_duplicates (&pat, complex_alias_template_r, &data))
6620 return true;
6621 for (int i = 0; i < len; ++i)
6622 if (!data.seen[i])
6623 return true;
6624 return false;
6627 /* If T is a specialization of a complex alias template with dependent
6628 template-arguments, return it; otherwise return NULL_TREE. If T is a
6629 typedef to such a specialization, return the specialization. */
6631 tree
6632 dependent_alias_template_spec_p (const_tree t, bool transparent_typedefs)
6634 if (t == error_mark_node)
6635 return NULL_TREE;
6636 gcc_assert (TYPE_P (t));
6638 if (!typedef_variant_p (t))
6639 return NULL_TREE;
6641 tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t);
6642 if (tinfo
6643 && TEMPLATE_DECL_COMPLEX_ALIAS_P (TI_TEMPLATE (tinfo))
6644 && (any_dependent_template_arguments_p
6645 (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)))))
6646 return CONST_CAST_TREE (t);
6648 if (transparent_typedefs)
6650 tree utype = DECL_ORIGINAL_TYPE (TYPE_NAME (t));
6651 return dependent_alias_template_spec_p (utype, transparent_typedefs);
6654 return NULL_TREE;
6657 /* Return the number of innermost template parameters in TMPL. */
6659 static int
6660 num_innermost_template_parms (const_tree tmpl)
6662 tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
6663 return TREE_VEC_LENGTH (parms);
6666 /* Return either TMPL or another template that it is equivalent to under DR
6667 1286: An alias that just changes the name of a template is equivalent to
6668 the other template. */
6670 static tree
6671 get_underlying_template (tree tmpl)
6673 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
6674 while (DECL_ALIAS_TEMPLATE_P (tmpl))
6676 /* Determine if the alias is equivalent to an underlying template. */
6677 tree orig_type = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6678 /* The underlying type may have been ill-formed. Don't proceed. */
6679 if (!orig_type)
6680 break;
6681 tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (orig_type);
6682 if (!tinfo)
6683 break;
6685 tree underlying = TI_TEMPLATE (tinfo);
6686 if (!PRIMARY_TEMPLATE_P (underlying)
6687 || (num_innermost_template_parms (tmpl)
6688 != num_innermost_template_parms (underlying)))
6689 break;
6691 /* Does the alias add cv-quals? */
6692 if (TYPE_QUALS (TREE_TYPE (underlying)) != TYPE_QUALS (TREE_TYPE (tmpl)))
6693 break;
6695 tree alias_args = INNERMOST_TEMPLATE_ARGS (generic_targs_for (tmpl));
6696 if (!comp_template_args (TI_ARGS (tinfo), alias_args))
6697 break;
6699 /* Are any default template arguments equivalent? */
6700 tree aparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
6701 tree uparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (underlying));
6702 const int nparms = TREE_VEC_LENGTH (aparms);
6703 for (int i = 0; i < nparms; ++i)
6705 tree adefarg = TREE_PURPOSE (TREE_VEC_ELT (aparms, i));
6706 tree udefarg = TREE_PURPOSE (TREE_VEC_ELT (uparms, i));
6707 if (!template_args_equal (adefarg, udefarg))
6708 goto top_break;
6711 /* If TMPL adds or changes any constraints, it isn't equivalent. I think
6712 it's appropriate to treat a less-constrained alias as equivalent. */
6713 if (!at_least_as_constrained (underlying, tmpl))
6714 break;
6716 /* Alias is equivalent. Strip it and repeat. */
6717 tmpl = underlying;
6719 top_break:;
6721 return tmpl;
6724 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
6725 must be a reference-to-function or a pointer-to-function type, as specified
6726 in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
6727 and check that the resulting function has external linkage. */
6729 static tree
6730 convert_nontype_argument_function (tree type, tree expr,
6731 tsubst_flags_t complain)
6733 tree fns = expr;
6734 tree fn, fn_no_ptr;
6735 linkage_kind linkage;
6737 fn = instantiate_type (type, fns, tf_none);
6738 if (fn == error_mark_node)
6739 return error_mark_node;
6741 if (value_dependent_expression_p (fn))
6742 goto accept;
6744 fn_no_ptr = fn;
6745 if (REFERENCE_REF_P (fn_no_ptr))
6746 fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
6747 fn_no_ptr = strip_fnptr_conv (fn_no_ptr);
6748 if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
6749 fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
6750 if (BASELINK_P (fn_no_ptr))
6751 fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
6753 /* [temp.arg.nontype]/1
6755 A template-argument for a non-type, non-template template-parameter
6756 shall be one of:
6757 [...]
6758 -- the address of an object or function with external [C++11: or
6759 internal] linkage. */
6761 STRIP_ANY_LOCATION_WRAPPER (fn_no_ptr);
6762 if (TREE_CODE (fn_no_ptr) != FUNCTION_DECL)
6764 if (complain & tf_error)
6766 location_t loc = cp_expr_loc_or_input_loc (expr);
6767 error_at (loc, "%qE is not a valid template argument for type %qT",
6768 expr, type);
6769 if (TYPE_PTR_P (type))
6770 inform (loc, "it must be the address of a function "
6771 "with external linkage");
6772 else
6773 inform (loc, "it must be the name of a function with "
6774 "external linkage");
6776 return NULL_TREE;
6779 linkage = decl_linkage (fn_no_ptr);
6780 if ((cxx_dialect < cxx11 && linkage != lk_external)
6781 || (cxx_dialect < cxx17 && linkage == lk_none))
6783 if (complain & tf_error)
6785 location_t loc = cp_expr_loc_or_input_loc (expr);
6786 if (cxx_dialect >= cxx11)
6787 error_at (loc, "%qE is not a valid template argument for type "
6788 "%qT because %qD has no linkage",
6789 expr, type, fn_no_ptr);
6790 else
6791 error_at (loc, "%qE is not a valid template argument for type "
6792 "%qT because %qD does not have external linkage",
6793 expr, type, fn_no_ptr);
6795 return NULL_TREE;
6798 accept:
6799 if (TYPE_REF_P (type))
6801 if (REFERENCE_REF_P (fn))
6802 fn = TREE_OPERAND (fn, 0);
6803 else
6804 fn = build_address (fn);
6806 if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (fn)))
6807 fn = build_nop (type, fn);
6809 return fn;
6812 /* Subroutine of convert_nontype_argument.
6813 Check if EXPR of type TYPE is a valid pointer-to-member constant.
6814 Emit an error otherwise. */
6816 static bool
6817 check_valid_ptrmem_cst_expr (tree type, tree expr,
6818 tsubst_flags_t complain)
6820 tree orig_expr = expr;
6821 STRIP_NOPS (expr);
6822 if (null_ptr_cst_p (expr))
6823 return true;
6824 if (TREE_CODE (expr) == PTRMEM_CST
6825 && same_type_p (TYPE_PTRMEM_CLASS_TYPE (type),
6826 PTRMEM_CST_CLASS (expr)))
6827 return true;
6828 if (cxx_dialect >= cxx11 && null_member_pointer_value_p (expr))
6829 return true;
6830 if (processing_template_decl
6831 && TREE_CODE (expr) == ADDR_EXPR
6832 && TREE_CODE (TREE_OPERAND (expr, 0)) == OFFSET_REF)
6833 return true;
6834 if (complain & tf_error)
6836 location_t loc = cp_expr_loc_or_input_loc (orig_expr);
6837 error_at (loc, "%qE is not a valid template argument for type %qT",
6838 orig_expr, type);
6839 if (TREE_CODE (expr) != PTRMEM_CST)
6840 inform (loc, "it must be a pointer-to-member of the form %<&X::Y%>");
6841 else
6842 inform (loc, "because it is a member of %qT", PTRMEM_CST_CLASS (expr));
6844 return false;
6847 /* Returns TRUE iff the address of OP is value-dependent.
6849 14.6.2.4 [temp.dep.temp]:
6850 A non-integral non-type template-argument is dependent if its type is
6851 dependent or it has either of the following forms
6852 qualified-id
6853 & qualified-id
6854 and contains a nested-name-specifier which specifies a class-name that
6855 names a dependent type.
6857 We generalize this to just say that the address of a member of a
6858 dependent class is value-dependent; the above doesn't cover the
6859 address of a static data member named with an unqualified-id. */
6861 static bool
6862 has_value_dependent_address (tree op)
6864 STRIP_ANY_LOCATION_WRAPPER (op);
6866 /* We could use get_inner_reference here, but there's no need;
6867 this is only relevant for template non-type arguments, which
6868 can only be expressed as &id-expression. */
6869 if (DECL_P (op))
6871 tree ctx = CP_DECL_CONTEXT (op);
6873 if (TYPE_P (ctx) && dependent_type_p (ctx))
6874 return true;
6876 if (VAR_P (op)
6877 && TREE_STATIC (op)
6878 && TREE_CODE (ctx) == FUNCTION_DECL
6879 && type_dependent_expression_p (ctx))
6880 return true;
6883 return false;
6886 /* The next set of functions are used for providing helpful explanatory
6887 diagnostics for failed overload resolution. Their messages should be
6888 indented by two spaces for consistency with the messages in
6889 call.cc */
6891 static int
6892 unify_success (bool /*explain_p*/)
6894 return 0;
6897 /* Other failure functions should call this one, to provide a single function
6898 for setting a breakpoint on. */
6900 static int
6901 unify_invalid (bool /*explain_p*/)
6903 return 1;
6906 static int
6907 unify_parameter_deduction_failure (bool explain_p, tree parm)
6909 if (explain_p)
6910 inform (input_location,
6911 " couldn%'t deduce template parameter %qD", parm);
6912 return unify_invalid (explain_p);
6915 static int
6916 unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
6918 if (explain_p)
6919 inform (input_location,
6920 " types %qT and %qT have incompatible cv-qualifiers",
6921 parm, arg);
6922 return unify_invalid (explain_p);
6925 static int
6926 unify_type_mismatch (bool explain_p, tree parm, tree arg)
6928 if (explain_p)
6929 inform (input_location, " mismatched types %qT and %qT", parm, arg);
6930 return unify_invalid (explain_p);
6933 static int
6934 unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
6936 if (explain_p)
6937 inform (input_location,
6938 " template parameter %qD is not a parameter pack, but "
6939 "argument %qD is",
6940 parm, arg);
6941 return unify_invalid (explain_p);
6944 static int
6945 unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
6947 if (explain_p)
6948 inform (input_location,
6949 " template argument %qE does not match "
6950 "pointer-to-member constant %qE",
6951 arg, parm);
6952 return unify_invalid (explain_p);
6955 static int
6956 unify_expression_unequal (bool explain_p, tree parm, tree arg)
6958 if (explain_p)
6959 inform (input_location, " %qE is not equivalent to %qE", parm, arg);
6960 return unify_invalid (explain_p);
6963 static int
6964 unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
6966 if (explain_p)
6967 inform (input_location,
6968 " inconsistent parameter pack deduction with %qT and %qT",
6969 old_arg, new_arg);
6970 return unify_invalid (explain_p);
6973 static int
6974 unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
6976 if (explain_p)
6978 if (TYPE_P (parm))
6979 inform (input_location,
6980 " deduced conflicting types for parameter %qT (%qT and %qT)",
6981 parm, first, second);
6982 else
6983 inform (input_location,
6984 " deduced conflicting values for non-type parameter "
6985 "%qE (%qE and %qE)", parm, first, second);
6987 return unify_invalid (explain_p);
6990 static int
6991 unify_vla_arg (bool explain_p, tree arg)
6993 if (explain_p)
6994 inform (input_location,
6995 " variable-sized array type %qT is not "
6996 "a valid template argument",
6997 arg);
6998 return unify_invalid (explain_p);
7001 static int
7002 unify_method_type_error (bool explain_p, tree arg)
7004 if (explain_p)
7005 inform (input_location,
7006 " member function type %qT is not a valid template argument",
7007 arg);
7008 return unify_invalid (explain_p);
7011 static int
7012 unify_arity (bool explain_p, int have, int wanted, bool least_p = false)
7014 if (explain_p)
7016 if (least_p)
7017 inform_n (input_location, wanted,
7018 " candidate expects at least %d argument, %d provided",
7019 " candidate expects at least %d arguments, %d provided",
7020 wanted, have);
7021 else
7022 inform_n (input_location, wanted,
7023 " candidate expects %d argument, %d provided",
7024 " candidate expects %d arguments, %d provided",
7025 wanted, have);
7027 return unify_invalid (explain_p);
7030 static int
7031 unify_too_many_arguments (bool explain_p, int have, int wanted)
7033 return unify_arity (explain_p, have, wanted);
7036 static int
7037 unify_too_few_arguments (bool explain_p, int have, int wanted,
7038 bool least_p = false)
7040 return unify_arity (explain_p, have, wanted, least_p);
7043 static int
7044 unify_arg_conversion (bool explain_p, tree to_type,
7045 tree from_type, tree arg)
7047 if (explain_p)
7048 inform (cp_expr_loc_or_input_loc (arg),
7049 " cannot convert %qE (type %qT) to type %qT",
7050 arg, from_type, to_type);
7051 return unify_invalid (explain_p);
7054 static int
7055 unify_no_common_base (bool explain_p, enum template_base_result r,
7056 tree parm, tree arg)
7058 if (explain_p)
7059 switch (r)
7061 case tbr_ambiguous_baseclass:
7062 inform (input_location, " %qT is an ambiguous base class of %qT",
7063 parm, arg);
7064 break;
7065 default:
7066 inform (input_location, " %qT is not derived from %qT", arg, parm);
7067 break;
7069 return unify_invalid (explain_p);
7072 static int
7073 unify_inconsistent_template_template_parameters (bool explain_p)
7075 if (explain_p)
7076 inform (input_location,
7077 " template parameters of a template template argument are "
7078 "inconsistent with other deduced template arguments");
7079 return unify_invalid (explain_p);
7082 static int
7083 unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
7085 if (explain_p)
7086 inform (input_location,
7087 " cannot deduce a template for %qT from non-template type %qT",
7088 parm, arg);
7089 return unify_invalid (explain_p);
7092 static int
7093 unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
7095 if (explain_p)
7096 inform (input_location,
7097 " template argument %qE does not match %qE", arg, parm);
7098 return unify_invalid (explain_p);
7101 /* Subroutine of convert_nontype_argument, to check whether EXPR, as an
7102 argument for TYPE, points to an unsuitable object.
7104 Also adjust the type of the index in C++20 array subobject references. */
7106 static bool
7107 invalid_tparm_referent_p (tree type, tree expr, tsubst_flags_t complain)
7109 switch (TREE_CODE (expr))
7111 CASE_CONVERT:
7112 return invalid_tparm_referent_p (type, TREE_OPERAND (expr, 0),
7113 complain);
7115 case TARGET_EXPR:
7116 return invalid_tparm_referent_p (type, TARGET_EXPR_INITIAL (expr),
7117 complain);
7119 case CONSTRUCTOR:
7121 for (auto &e: CONSTRUCTOR_ELTS (expr))
7122 if (invalid_tparm_referent_p (TREE_TYPE (e.value), e.value, complain))
7123 return true;
7125 break;
7127 case ADDR_EXPR:
7129 tree decl = TREE_OPERAND (expr, 0);
7131 if (cxx_dialect >= cxx20)
7132 while (TREE_CODE (decl) == COMPONENT_REF
7133 || TREE_CODE (decl) == ARRAY_REF)
7135 tree &op = TREE_OPERAND (decl, 1);
7136 if (TREE_CODE (decl) == ARRAY_REF
7137 && TREE_CODE (op) == INTEGER_CST)
7138 /* Canonicalize array offsets to ptrdiff_t; how they were
7139 written doesn't matter for subobject identity. */
7140 op = fold_convert (ptrdiff_type_node, op);
7141 decl = TREE_OPERAND (decl, 0);
7144 if (!VAR_OR_FUNCTION_DECL_P (decl))
7146 if (complain & tf_error)
7147 error_at (cp_expr_loc_or_input_loc (expr),
7148 "%qE is not a valid template argument of type %qT "
7149 "because %qE is not a variable or function",
7150 expr, type, decl);
7151 return true;
7153 else if (cxx_dialect < cxx11 && !DECL_EXTERNAL_LINKAGE_P (decl))
7155 if (complain & tf_error)
7156 error_at (cp_expr_loc_or_input_loc (expr),
7157 "%qE is not a valid template argument of type %qT "
7158 "in C++98 because %qD does not have external linkage",
7159 expr, type, decl);
7160 return true;
7162 else if ((cxx_dialect >= cxx11 && cxx_dialect < cxx17)
7163 && decl_linkage (decl) == lk_none)
7165 if (complain & tf_error)
7166 error_at (cp_expr_loc_or_input_loc (expr),
7167 "%qE is not a valid template argument of type %qT "
7168 "because %qD has no linkage", expr, type, decl);
7169 return true;
7171 /* C++17: For a non-type template-parameter of reference or pointer
7172 type, the value of the constant expression shall not refer to (or
7173 for a pointer type, shall not be the address of):
7174 * a subobject (4.5),
7175 * a temporary object (15.2),
7176 * a string literal (5.13.5),
7177 * the result of a typeid expression (8.2.8), or
7178 * a predefined __func__ variable (11.4.1). */
7179 else if (VAR_P (decl) && DECL_ARTIFICIAL (decl))
7181 if (complain & tf_error)
7182 error ("the address of %qD is not a valid template argument",
7183 decl);
7184 return true;
7186 else if (cxx_dialect < cxx20
7187 && !(same_type_ignoring_top_level_qualifiers_p
7188 (strip_array_types (TREE_TYPE (type)),
7189 strip_array_types (TREE_TYPE (decl)))))
7191 if (complain & tf_error)
7192 error ("the address of the %qT subobject of %qD is not a "
7193 "valid template argument", TREE_TYPE (type), decl);
7194 return true;
7196 else if (!TREE_STATIC (decl) && !DECL_EXTERNAL (decl))
7198 if (complain & tf_error)
7199 error ("the address of %qD is not a valid template argument "
7200 "because it does not have static storage duration",
7201 decl);
7202 return true;
7205 break;
7207 default:
7208 if (!INDIRECT_TYPE_P (type))
7209 /* We're only concerned about pointers and references here. */;
7210 else if (cxx_dialect >= cxx11 && integer_zerop (expr))
7211 /* Null pointer values are OK in C++11. */;
7212 else
7214 if (VAR_P (expr))
7216 if (complain & tf_error)
7217 error ("%qD is not a valid template argument "
7218 "because %qD is a variable, not the address of "
7219 "a variable", expr, expr);
7220 return true;
7222 else
7224 if (complain & tf_error)
7225 error ("%qE is not a valid template argument for %qT "
7226 "because it is not the address of a variable",
7227 expr, type);
7228 return true;
7232 return false;
7236 /* Return a VAR_DECL for the C++20 template parameter object corresponding to
7237 template argument EXPR. */
7239 static tree
7240 create_template_parm_object (tree expr, tsubst_flags_t complain)
7242 if (TREE_CODE (expr) == TARGET_EXPR)
7243 expr = TARGET_EXPR_INITIAL (expr);
7245 if (!TREE_CONSTANT (expr))
7247 if ((complain & tf_error)
7248 && require_rvalue_constant_expression (expr))
7249 cxx_constant_value (expr);
7250 return error_mark_node;
7252 if (invalid_tparm_referent_p (TREE_TYPE (expr), expr, complain))
7253 return error_mark_node;
7255 /* This is no longer a compound literal. */
7256 gcc_assert (!TREE_HAS_CONSTRUCTOR (expr));
7258 return get_template_parm_object (expr, mangle_template_parm_object (expr));
7261 /* The template arguments corresponding to template parameter objects of types
7262 that contain pointers to members. */
7264 static GTY(()) hash_map<tree, tree> *tparm_obj_values;
7266 /* Find or build an nttp object for (already-validated) EXPR with name
7267 NAME. */
7269 tree
7270 get_template_parm_object (tree expr, tree name)
7272 tree decl = get_global_binding (name);
7273 if (decl)
7274 return decl;
7276 tree type = cp_build_qualified_type (TREE_TYPE (expr), TYPE_QUAL_CONST);
7277 decl = create_temporary_var (type);
7278 DECL_NTTP_OBJECT_P (decl) = true;
7279 DECL_CONTEXT (decl) = NULL_TREE;
7280 TREE_STATIC (decl) = true;
7281 DECL_DECLARED_CONSTEXPR_P (decl) = true;
7282 TREE_READONLY (decl) = true;
7283 DECL_NAME (decl) = name;
7284 SET_DECL_ASSEMBLER_NAME (decl, name);
7285 comdat_linkage (decl);
7287 if (!zero_init_p (type))
7289 /* If EXPR contains any PTRMEM_CST, they will get clobbered by
7290 lower_var_init before we're done mangling. So store the original
7291 value elsewhere. */
7292 tree copy = unshare_constructor (expr);
7293 hash_map_safe_put<hm_ggc> (tparm_obj_values, decl, copy);
7296 pushdecl_top_level_and_finish (decl, expr);
7298 return decl;
7301 /* Return the actual template argument corresponding to template parameter
7302 object VAR. */
7304 tree
7305 tparm_object_argument (tree var)
7307 if (zero_init_p (TREE_TYPE (var)))
7308 return DECL_INITIAL (var);
7309 return *(tparm_obj_values->get (var));
7312 /* Attempt to convert the non-type template parameter EXPR to the
7313 indicated TYPE. If the conversion is successful, return the
7314 converted value. If the conversion is unsuccessful, return
7315 NULL_TREE if we issued an error message, or error_mark_node if we
7316 did not. We issue error messages for out-and-out bad template
7317 parameters, but not simply because the conversion failed, since we
7318 might be just trying to do argument deduction. Both TYPE and EXPR
7319 must be non-dependent.
7321 The conversion follows the special rules described in
7322 [temp.arg.nontype], and it is much more strict than an implicit
7323 conversion.
7325 This function is called twice for each template argument (see
7326 lookup_template_class for a more accurate description of this
7327 problem). This means that we need to handle expressions which
7328 are not valid in a C++ source, but can be created from the
7329 first call (for instance, casts to perform conversions). These
7330 hacks can go away after we fix the double coercion problem. */
7332 static tree
7333 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
7335 tree expr_type;
7336 location_t loc = cp_expr_loc_or_input_loc (expr);
7338 /* Detect immediately string literals as invalid non-type argument.
7339 This special-case is not needed for correctness (we would easily
7340 catch this later), but only to provide better diagnostic for this
7341 common user mistake. As suggested by DR 100, we do not mention
7342 linkage issues in the diagnostic as this is not the point. */
7343 if (TREE_CODE (expr) == STRING_CST && !CLASS_TYPE_P (type))
7345 if (complain & tf_error)
7346 error ("%qE is not a valid template argument for type %qT "
7347 "because string literals can never be used in this context",
7348 expr, type);
7349 return NULL_TREE;
7352 /* Add the ADDR_EXPR now for the benefit of
7353 value_dependent_expression_p. */
7354 if (TYPE_PTROBV_P (type)
7355 && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
7357 expr = decay_conversion (expr, complain);
7358 if (expr == error_mark_node)
7359 return error_mark_node;
7362 /* If we are in a template, EXPR may be non-dependent, but still
7363 have a syntactic, rather than semantic, form. For example, EXPR
7364 might be a SCOPE_REF, rather than the VAR_DECL to which the
7365 SCOPE_REF refers. Preserving the qualifying scope is necessary
7366 so that access checking can be performed when the template is
7367 instantiated -- but here we need the resolved form so that we can
7368 convert the argument. */
7369 bool non_dep = false;
7370 if (TYPE_REF_OBJ_P (type)
7371 && has_value_dependent_address (expr))
7372 /* If we want the address and it's value-dependent, don't fold. */;
7373 else if (processing_template_decl
7374 && !instantiation_dependent_expression_p (expr))
7375 non_dep = true;
7376 if (error_operand_p (expr))
7377 return error_mark_node;
7378 expr_type = TREE_TYPE (expr);
7380 /* If the argument is non-dependent, perform any conversions in
7381 non-dependent context as well. */
7382 processing_template_decl_sentinel s (non_dep);
7383 if (non_dep)
7384 expr = instantiate_non_dependent_expr_internal (expr, complain);
7386 bool val_dep_p = value_dependent_expression_p (expr);
7387 if (val_dep_p)
7388 expr = canonicalize_expr_argument (expr, complain);
7389 else
7390 STRIP_ANY_LOCATION_WRAPPER (expr);
7392 /* 14.3.2/5: The null pointer{,-to-member} conversion is applied
7393 to a non-type argument of "nullptr". */
7394 if (NULLPTR_TYPE_P (expr_type) && TYPE_PTR_OR_PTRMEM_P (type))
7395 expr = fold_simple (convert (type, expr));
7397 /* In C++11, integral or enumeration non-type template arguments can be
7398 arbitrary constant expressions. Pointer and pointer to
7399 member arguments can be general constant expressions that evaluate
7400 to a null value, but otherwise still need to be of a specific form. */
7401 if (cxx_dialect >= cxx11)
7403 if (TREE_CODE (expr) == PTRMEM_CST && TYPE_PTRMEM_P (type))
7404 /* A PTRMEM_CST is already constant, and a valid template
7405 argument for a parameter of pointer to member type, we just want
7406 to leave it in that form rather than lower it to a
7407 CONSTRUCTOR. */;
7408 else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
7409 || cxx_dialect >= cxx17)
7411 /* C++17: A template-argument for a non-type template-parameter shall
7412 be a converted constant expression (8.20) of the type of the
7413 template-parameter. */
7414 expr = build_converted_constant_expr (type, expr, complain);
7415 if (expr == error_mark_node)
7416 /* Make sure we return NULL_TREE only if we have really issued
7417 an error, as described above. */
7418 return (complain & tf_error) ? NULL_TREE : error_mark_node;
7419 else if (TREE_CODE (expr) == IMPLICIT_CONV_EXPR)
7421 IMPLICIT_CONV_EXPR_NONTYPE_ARG (expr) = true;
7422 return expr;
7424 expr = maybe_constant_value (expr, NULL_TREE, mce_true);
7425 expr = convert_from_reference (expr);
7426 /* EXPR may have become value-dependent. */
7427 val_dep_p = value_dependent_expression_p (expr);
7429 else if (TYPE_PTR_OR_PTRMEM_P (type))
7431 tree folded = maybe_constant_value (expr, NULL_TREE, mce_true);
7432 if (TYPE_PTR_P (type) ? integer_zerop (folded)
7433 : null_member_pointer_value_p (folded))
7434 expr = folded;
7438 if (TYPE_REF_P (type))
7439 expr = mark_lvalue_use (expr);
7440 else
7441 expr = mark_rvalue_use (expr);
7443 /* HACK: Due to double coercion, we can get a
7444 NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
7445 which is the tree that we built on the first call (see
7446 below when coercing to reference to object or to reference to
7447 function). We just strip everything and get to the arg.
7448 See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
7449 for examples. */
7450 if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
7452 /* Check this before we strip *& to avoid redundancy. */
7453 if (!mark_single_function (expr, complain))
7454 return error_mark_node;
7456 tree probe_type, probe = expr;
7457 if (REFERENCE_REF_P (probe))
7458 probe = TREE_OPERAND (probe, 0);
7459 probe_type = TREE_TYPE (probe);
7460 if (TREE_CODE (probe) == NOP_EXPR)
7462 /* ??? Maybe we could use convert_from_reference here, but we
7463 would need to relax its constraints because the NOP_EXPR
7464 could actually change the type to something more cv-qualified,
7465 and this is not folded by convert_from_reference. */
7466 tree addr = TREE_OPERAND (probe, 0);
7467 if (TYPE_REF_P (probe_type)
7468 && TREE_CODE (addr) == ADDR_EXPR
7469 && TYPE_PTR_P (TREE_TYPE (addr))
7470 && (same_type_ignoring_top_level_qualifiers_p
7471 (TREE_TYPE (probe_type),
7472 TREE_TYPE (TREE_TYPE (addr)))))
7474 expr = TREE_OPERAND (addr, 0);
7475 expr_type = TREE_TYPE (probe_type);
7480 /* [temp.arg.nontype]/5, bullet 1
7482 For a non-type template-parameter of integral or enumeration type,
7483 integral promotions (_conv.prom_) and integral conversions
7484 (_conv.integral_) are applied. */
7485 if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
7486 || SCALAR_FLOAT_TYPE_P (type))
7488 if (cxx_dialect < cxx11)
7490 tree t = build_converted_constant_expr (type, expr, complain);
7491 t = maybe_constant_value (t);
7492 if (t != error_mark_node)
7493 expr = t;
7496 if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
7497 return error_mark_node;
7499 /* Notice that there are constant expressions like '4 % 0' which
7500 do not fold into integer constants. */
7501 if (!CONSTANT_CLASS_P (expr) && !val_dep_p)
7503 if (complain & tf_error)
7505 int errs = errorcount, warns = warningcount + werrorcount;
7506 if (!require_potential_constant_expression (expr))
7507 expr = error_mark_node;
7508 else
7509 expr = cxx_constant_value (expr);
7510 if (errorcount > errs || warningcount + werrorcount > warns)
7511 inform (loc, "in template argument for type %qT", type);
7512 if (expr == error_mark_node)
7513 return NULL_TREE;
7514 /* else cxx_constant_value complained but gave us
7515 a real constant, so go ahead. */
7516 if (!CONSTANT_CLASS_P (expr))
7518 /* Some assemble time constant expressions like
7519 (intptr_t)&&lab1 - (intptr_t)&&lab2 or
7520 4 + (intptr_t)&&var satisfy reduced_constant_expression_p
7521 as we can emit them into .rodata initializers of
7522 variables, yet they can't fold into an INTEGER_CST at
7523 compile time. Refuse them here. */
7524 gcc_checking_assert (reduced_constant_expression_p (expr));
7525 error_at (loc, "template argument %qE for type %qT not "
7526 "a compile-time constant", expr, type);
7527 return NULL_TREE;
7530 else
7531 return NULL_TREE;
7534 /* Avoid typedef problems. */
7535 if (TREE_TYPE (expr) != type)
7536 expr = fold_convert (type, expr);
7538 /* [temp.arg.nontype]/5, bullet 2
7540 For a non-type template-parameter of type pointer to object,
7541 qualification conversions (_conv.qual_) and the array-to-pointer
7542 conversion (_conv.array_) are applied. */
7543 else if (TYPE_PTROBV_P (type))
7545 tree decayed = expr;
7547 /* Look through any NOP_EXPRs around an ADDR_EXPR, whether they come from
7548 decay_conversion or an explicit cast. If it's a problematic cast,
7549 we'll complain about it below. */
7550 if (TREE_CODE (expr) == NOP_EXPR)
7552 tree probe = expr;
7553 STRIP_NOPS (probe);
7554 if (TREE_CODE (probe) == ADDR_EXPR
7555 && TYPE_PTR_P (TREE_TYPE (probe)))
7557 expr = probe;
7558 expr_type = TREE_TYPE (expr);
7562 /* [temp.arg.nontype]/1 (TC1 version, DR 49):
7564 A template-argument for a non-type, non-template template-parameter
7565 shall be one of: [...]
7567 -- the name of a non-type template-parameter;
7568 -- the address of an object or function with external linkage, [...]
7569 expressed as "& id-expression" where the & is optional if the name
7570 refers to a function or array, or if the corresponding
7571 template-parameter is a reference.
7573 Here, we do not care about functions, as they are invalid anyway
7574 for a parameter of type pointer-to-object. */
7576 if (val_dep_p)
7577 /* Non-type template parameters are OK. */
7579 else if (cxx_dialect >= cxx11 && integer_zerop (expr))
7580 /* Null pointer values are OK in C++11. */;
7581 else if (TREE_CODE (expr) != ADDR_EXPR
7582 && !INDIRECT_TYPE_P (expr_type))
7583 /* Other values, like integer constants, might be valid
7584 non-type arguments of some other type. */
7585 return error_mark_node;
7586 else if (invalid_tparm_referent_p (type, expr, complain))
7587 return NULL_TREE;
7589 expr = decayed;
7591 expr = perform_qualification_conversions (type, expr);
7592 if (expr == error_mark_node)
7593 return error_mark_node;
7595 /* [temp.arg.nontype]/5, bullet 3
7597 For a non-type template-parameter of type reference to object, no
7598 conversions apply. The type referred to by the reference may be more
7599 cv-qualified than the (otherwise identical) type of the
7600 template-argument. The template-parameter is bound directly to the
7601 template-argument, which must be an lvalue. */
7602 else if (TYPE_REF_OBJ_P (type))
7604 if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
7605 expr_type))
7606 return error_mark_node;
7608 if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
7610 if (complain & tf_error)
7611 error ("%qE is not a valid template argument for type %qT "
7612 "because of conflicts in cv-qualification", expr, type);
7613 return NULL_TREE;
7616 if (!lvalue_p (expr))
7618 if (complain & tf_error)
7619 error ("%qE is not a valid template argument for type %qT "
7620 "because it is not an lvalue", expr, type);
7621 return NULL_TREE;
7624 /* [temp.arg.nontype]/1
7626 A template-argument for a non-type, non-template template-parameter
7627 shall be one of: [...]
7629 -- the address of an object or function with external linkage. */
7630 if (INDIRECT_REF_P (expr)
7631 && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
7633 expr = TREE_OPERAND (expr, 0);
7634 if (DECL_P (expr))
7636 if (complain & tf_error)
7637 error ("%q#D is not a valid template argument for type %qT "
7638 "because a reference variable does not have a constant "
7639 "address", expr, type);
7640 return NULL_TREE;
7644 if (TYPE_REF_OBJ_P (TREE_TYPE (expr)) && val_dep_p)
7645 /* OK, dependent reference. We don't want to ask whether a DECL is
7646 itself value-dependent, since what we want here is its address. */;
7647 else
7649 expr = build_address (expr);
7651 if (invalid_tparm_referent_p (type, expr, complain))
7652 return NULL_TREE;
7655 if (!same_type_p (type, TREE_TYPE (expr)))
7656 expr = build_nop (type, expr);
7658 /* [temp.arg.nontype]/5, bullet 4
7660 For a non-type template-parameter of type pointer to function, only
7661 the function-to-pointer conversion (_conv.func_) is applied. If the
7662 template-argument represents a set of overloaded functions (or a
7663 pointer to such), the matching function is selected from the set
7664 (_over.over_). */
7665 else if (TYPE_PTRFN_P (type))
7667 /* If the argument is a template-id, we might not have enough
7668 context information to decay the pointer. */
7669 if (!type_unknown_p (expr_type))
7671 expr = decay_conversion (expr, complain);
7672 if (expr == error_mark_node)
7673 return error_mark_node;
7676 if (cxx_dialect >= cxx11 && integer_zerop (expr))
7677 /* Null pointer values are OK in C++11. */
7678 return perform_qualification_conversions (type, expr);
7680 expr = convert_nontype_argument_function (type, expr, complain);
7681 if (!expr || expr == error_mark_node)
7682 return expr;
7684 /* [temp.arg.nontype]/5, bullet 5
7686 For a non-type template-parameter of type reference to function, no
7687 conversions apply. If the template-argument represents a set of
7688 overloaded functions, the matching function is selected from the set
7689 (_over.over_). */
7690 else if (TYPE_REFFN_P (type))
7692 if (TREE_CODE (expr) == ADDR_EXPR)
7694 if (complain & tf_error)
7696 error ("%qE is not a valid template argument for type %qT "
7697 "because it is a pointer", expr, type);
7698 inform (input_location, "try using %qE instead",
7699 TREE_OPERAND (expr, 0));
7701 return NULL_TREE;
7704 expr = convert_nontype_argument_function (type, expr, complain);
7705 if (!expr || expr == error_mark_node)
7706 return expr;
7708 /* [temp.arg.nontype]/5, bullet 6
7710 For a non-type template-parameter of type pointer to member function,
7711 no conversions apply. If the template-argument represents a set of
7712 overloaded member functions, the matching member function is selected
7713 from the set (_over.over_). */
7714 else if (TYPE_PTRMEMFUNC_P (type))
7716 expr = instantiate_type (type, expr, tf_none);
7717 if (expr == error_mark_node)
7718 return error_mark_node;
7720 /* [temp.arg.nontype] bullet 1 says the pointer to member
7721 expression must be a pointer-to-member constant. */
7722 if (!val_dep_p
7723 && !check_valid_ptrmem_cst_expr (type, expr, complain))
7724 return NULL_TREE;
7726 /* Repeated conversion can't deal with a conversion that turns PTRMEM_CST
7727 into a CONSTRUCTOR, so build up a new PTRMEM_CST instead. */
7728 if (fnptr_conv_p (type, TREE_TYPE (expr)))
7729 expr = make_ptrmem_cst (type, PTRMEM_CST_MEMBER (expr));
7731 /* [temp.arg.nontype]/5, bullet 7
7733 For a non-type template-parameter of type pointer to data member,
7734 qualification conversions (_conv.qual_) are applied. */
7735 else if (TYPE_PTRDATAMEM_P (type))
7737 /* [temp.arg.nontype] bullet 1 says the pointer to member
7738 expression must be a pointer-to-member constant. */
7739 if (!val_dep_p
7740 && !check_valid_ptrmem_cst_expr (type, expr, complain))
7741 return NULL_TREE;
7743 expr = perform_qualification_conversions (type, expr);
7744 if (expr == error_mark_node)
7745 return expr;
7747 else if (NULLPTR_TYPE_P (type))
7749 if (!NULLPTR_TYPE_P (TREE_TYPE (expr)))
7751 if (complain & tf_error)
7752 error ("%qE is not a valid template argument for type %qT "
7753 "because it is of type %qT", expr, type, TREE_TYPE (expr));
7754 return NULL_TREE;
7756 return expr;
7758 else if (CLASS_TYPE_P (type))
7760 /* Replace the argument with a reference to the corresponding template
7761 parameter object. */
7762 if (!val_dep_p)
7763 expr = create_template_parm_object (expr, complain);
7764 if (expr == error_mark_node)
7765 return NULL_TREE;
7767 /* A template non-type parameter must be one of the above. */
7768 else
7769 gcc_unreachable ();
7771 /* Sanity check: did we actually convert the argument to the
7772 right type? */
7773 gcc_assert (same_type_ignoring_top_level_qualifiers_p
7774 (type, TREE_TYPE (expr)));
7775 return convert_from_reference (expr);
7778 /* Subroutine of coerce_template_template_parms, which returns 1 if
7779 PARM_PARM and ARG_PARM match using the rule for the template
7780 parameters of template template parameters. Both PARM and ARG are
7781 template parameters; the rest of the arguments are the same as for
7782 coerce_template_template_parms.
7784 static int
7785 coerce_template_template_parm (tree parm,
7786 tree arg,
7787 tsubst_flags_t complain,
7788 tree in_decl,
7789 tree outer_args)
7791 if (arg == NULL_TREE || error_operand_p (arg)
7792 || parm == NULL_TREE || error_operand_p (parm))
7793 return 0;
7795 if (TREE_CODE (arg) != TREE_CODE (parm))
7796 return 0;
7798 switch (TREE_CODE (parm))
7800 case TEMPLATE_DECL:
7801 /* We encounter instantiations of templates like
7802 template <template <template <class> class> class TT>
7803 class C; */
7805 if (!coerce_template_template_parms
7806 (parm, arg, complain, in_decl, outer_args))
7807 return 0;
7809 /* Fall through. */
7811 case TYPE_DECL:
7812 if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
7813 && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
7814 /* Argument is a parameter pack but parameter is not. */
7815 return 0;
7816 break;
7818 case PARM_DECL:
7819 /* The tsubst call is used to handle cases such as
7821 template <int> class C {};
7822 template <class T, template <T> class TT> class D {};
7823 D<int, C> d;
7825 i.e. the parameter list of TT depends on earlier parameters. */
7826 if (!uses_template_parms (TREE_TYPE (arg)))
7828 tree t = tsubst (TREE_TYPE (parm), outer_args, complain, in_decl);
7829 if (!uses_template_parms (t)
7830 && !same_type_p (t, TREE_TYPE (arg)))
7831 return 0;
7834 if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
7835 && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
7836 /* Argument is a parameter pack but parameter is not. */
7837 return 0;
7839 break;
7841 default:
7842 gcc_unreachable ();
7845 return 1;
7848 /* Coerce template argument list ARGLIST for use with template
7849 template-parameter TEMPL. */
7851 static tree
7852 coerce_template_args_for_ttp (tree templ, tree arglist,
7853 tsubst_flags_t complain)
7855 /* Consider an example where a template template parameter declared as
7857 template <class T, class U = std::allocator<T> > class TT
7859 The template parameter level of T and U are one level larger than
7860 of TT. To proper process the default argument of U, say when an
7861 instantiation `TT<int>' is seen, we need to build the full
7862 arguments containing {int} as the innermost level. Outer levels,
7863 available when not appearing as default template argument, can be
7864 obtained from the arguments of the enclosing template.
7866 Suppose that TT is later substituted with std::vector. The above
7867 instantiation is `TT<int, std::allocator<T> >' with TT at
7868 level 1, and T at level 2, while the template arguments at level 1
7869 becomes {std::vector} and the inner level 2 is {int}. */
7871 tree outer = DECL_CONTEXT (templ);
7872 if (outer)
7873 outer = generic_targs_for (outer);
7874 else if (current_template_parms)
7876 /* This is an argument of the current template, so we haven't set
7877 DECL_CONTEXT yet. We can also get here when level-lowering a
7878 bound ttp. */
7879 tree relevant_template_parms;
7881 /* Parameter levels that are greater than the level of the given
7882 template template parm are irrelevant. */
7883 relevant_template_parms = current_template_parms;
7884 while (TMPL_PARMS_DEPTH (relevant_template_parms)
7885 != TEMPLATE_TYPE_LEVEL (TREE_TYPE (templ)))
7886 relevant_template_parms = TREE_CHAIN (relevant_template_parms);
7888 outer = template_parms_to_args (relevant_template_parms);
7891 if (outer)
7892 arglist = add_to_template_args (outer, arglist);
7894 tree parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
7895 return coerce_template_parms (parmlist, arglist, templ, complain);
7898 /* A cache of template template parameters with match-all default
7899 arguments. */
7900 static GTY((deletable)) hash_map<tree,tree> *defaulted_ttp_cache;
7902 /* T is a bound template template-parameter. Copy its arguments into default
7903 arguments of the template template-parameter's template parameters. */
7905 static tree
7906 add_defaults_to_ttp (tree otmpl)
7908 if (tree *c = hash_map_safe_get (defaulted_ttp_cache, otmpl))
7909 return *c;
7911 tree ntmpl = copy_node (otmpl);
7913 tree ntype = copy_node (TREE_TYPE (otmpl));
7914 TYPE_STUB_DECL (ntype) = TYPE_NAME (ntype) = ntmpl;
7915 TYPE_MAIN_VARIANT (ntype) = ntype;
7916 TYPE_POINTER_TO (ntype) = TYPE_REFERENCE_TO (ntype) = NULL_TREE;
7917 TYPE_NAME (ntype) = ntmpl;
7918 SET_TYPE_STRUCTURAL_EQUALITY (ntype);
7920 tree idx = TEMPLATE_TYPE_PARM_INDEX (ntype)
7921 = copy_node (TEMPLATE_TYPE_PARM_INDEX (ntype));
7922 TEMPLATE_PARM_DECL (idx) = ntmpl;
7923 TREE_TYPE (ntmpl) = TREE_TYPE (idx) = ntype;
7925 tree oparms = DECL_TEMPLATE_PARMS (otmpl);
7926 tree parms = DECL_TEMPLATE_PARMS (ntmpl) = copy_node (oparms);
7927 TREE_CHAIN (parms) = TREE_CHAIN (oparms);
7928 tree vec = TREE_VALUE (parms) = copy_node (TREE_VALUE (parms));
7929 for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
7931 tree o = TREE_VEC_ELT (vec, i);
7932 if (!template_parameter_pack_p (TREE_VALUE (o)))
7934 tree n = TREE_VEC_ELT (vec, i) = copy_node (o);
7935 TREE_PURPOSE (n) = any_targ_node;
7939 hash_map_safe_put<hm_ggc> (defaulted_ttp_cache, otmpl, ntmpl);
7940 return ntmpl;
7943 /* ARG is a bound potential template template-argument, and PARGS is a list
7944 of arguments for the corresponding template template-parameter. Adjust
7945 PARGS as appropriate for application to ARG's template, and if ARG is a
7946 BOUND_TEMPLATE_TEMPLATE_PARM, possibly adjust it to add default template
7947 arguments to the template template parameter. */
7949 static tree
7950 coerce_ttp_args_for_tta (tree& arg, tree pargs, tsubst_flags_t complain)
7952 ++processing_template_decl;
7953 tree arg_tmpl = TYPE_TI_TEMPLATE (arg);
7954 if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
7956 /* When comparing two template template-parameters in partial ordering,
7957 rewrite the one currently being used as an argument to have default
7958 arguments for all parameters. */
7959 arg_tmpl = add_defaults_to_ttp (arg_tmpl);
7960 pargs = coerce_template_args_for_ttp (arg_tmpl, pargs, complain);
7961 if (pargs != error_mark_node)
7962 arg = bind_template_template_parm (TREE_TYPE (arg_tmpl),
7963 TYPE_TI_ARGS (arg));
7965 else
7967 tree aparms
7968 = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (arg_tmpl));
7969 pargs = coerce_template_parms (aparms, pargs, arg_tmpl, complain);
7971 --processing_template_decl;
7972 return pargs;
7975 /* Subroutine of unify for the case when PARM is a
7976 BOUND_TEMPLATE_TEMPLATE_PARM. */
7978 static int
7979 unify_bound_ttp_args (tree tparms, tree targs, tree parm, tree& arg,
7980 bool explain_p)
7982 tree parmvec = TYPE_TI_ARGS (parm);
7983 tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
7985 /* The template template parm might be variadic and the argument
7986 not, so flatten both argument lists. */
7987 parmvec = expand_template_argument_pack (parmvec);
7988 argvec = expand_template_argument_pack (argvec);
7990 if (flag_new_ttp)
7992 /* In keeping with P0522R0, adjust P's template arguments
7993 to apply to A's template; then flatten it again. */
7994 tree nparmvec = coerce_ttp_args_for_tta (arg, parmvec, tf_none);
7995 nparmvec = expand_template_argument_pack (nparmvec);
7997 if (unify (tparms, targs, nparmvec, argvec,
7998 UNIFY_ALLOW_NONE, explain_p))
7999 return 1;
8001 /* If the P0522 adjustment eliminated a pack expansion, deduce
8002 empty packs. */
8003 if (flag_new_ttp
8004 && TREE_VEC_LENGTH (nparmvec) < TREE_VEC_LENGTH (parmvec)
8005 && unify_pack_expansion (tparms, targs, parmvec, argvec,
8006 DEDUCE_EXACT, /*sub*/true, explain_p))
8007 return 1;
8009 else
8011 /* Deduce arguments T, i from TT<T> or TT<i>.
8012 We check each element of PARMVEC and ARGVEC individually
8013 rather than the whole TREE_VEC since they can have
8014 different number of elements, which is allowed under N2555. */
8016 int len = TREE_VEC_LENGTH (parmvec);
8018 /* Check if the parameters end in a pack, making them
8019 variadic. */
8020 int parm_variadic_p = 0;
8021 if (len > 0
8022 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
8023 parm_variadic_p = 1;
8025 for (int i = 0; i < len - parm_variadic_p; ++i)
8026 /* If the template argument list of P contains a pack
8027 expansion that is not the last template argument, the
8028 entire template argument list is a non-deduced
8029 context. */
8030 if (PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, i)))
8031 return unify_success (explain_p);
8033 if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
8034 return unify_too_few_arguments (explain_p,
8035 TREE_VEC_LENGTH (argvec), len);
8037 for (int i = 0; i < len - parm_variadic_p; ++i)
8038 if (unify (tparms, targs,
8039 TREE_VEC_ELT (parmvec, i),
8040 TREE_VEC_ELT (argvec, i),
8041 UNIFY_ALLOW_NONE, explain_p))
8042 return 1;
8044 if (parm_variadic_p
8045 && unify_pack_expansion (tparms, targs,
8046 parmvec, argvec,
8047 DEDUCE_EXACT,
8048 /*subr=*/true, explain_p))
8049 return 1;
8052 return 0;
8055 /* Return 1 if PARM_TMPL and ARG_TMPL match using rule for
8056 template template parameters.
8058 Consider the example:
8059 template <class T> class A;
8060 template<template <class U> class TT> class B;
8062 For B<A>, PARM_TMPL is TT, while ARG_TMPL is A,
8063 and OUTER_ARGS contains A. */
8065 static int
8066 coerce_template_template_parms (tree parm_tmpl,
8067 tree arg_tmpl,
8068 tsubst_flags_t complain,
8069 tree in_decl,
8070 tree outer_args)
8072 int nparms, nargs, i;
8073 tree parm, arg;
8074 int variadic_p = 0;
8076 tree parm_parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm_tmpl));
8077 tree arg_parms_full = DECL_TEMPLATE_PARMS (arg_tmpl);
8078 tree arg_parms = INNERMOST_TEMPLATE_PARMS (arg_parms_full);
8080 gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
8081 gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
8083 nparms = TREE_VEC_LENGTH (parm_parms);
8084 nargs = TREE_VEC_LENGTH (arg_parms);
8086 if (flag_new_ttp)
8088 /* P0522R0: A template template-parameter P is at least as specialized as
8089 a template template-argument A if, given the following rewrite to two
8090 function templates, the function template corresponding to P is at
8091 least as specialized as the function template corresponding to A
8092 according to the partial ordering rules for function templates
8093 ([temp.func.order]). Given an invented class template X with the
8094 template parameter list of A (including default arguments):
8096 * Each of the two function templates has the same template parameters,
8097 respectively, as P or A.
8099 * Each function template has a single function parameter whose type is
8100 a specialization of X with template arguments corresponding to the
8101 template parameters from the respective function template where, for
8102 each template parameter PP in the template parameter list of the
8103 function template, a corresponding template argument AA is formed. If
8104 PP declares a parameter pack, then AA is the pack expansion
8105 PP... ([temp.variadic]); otherwise, AA is the id-expression PP.
8107 If the rewrite produces an invalid type, then P is not at least as
8108 specialized as A. */
8110 /* So coerce P's args to apply to A's parms, and then deduce between A's
8111 args and the converted args. If that succeeds, A is at least as
8112 specialized as P, so they match.*/
8113 processing_template_decl_sentinel ptds (/*reset*/false);
8114 ++processing_template_decl;
8116 tree pargs = template_parms_level_to_args (parm_parms);
8118 /* PARM and ARG might be at different template depths, and we want to
8119 pass the right additional levels of args when coercing PARGS to
8120 ARG_PARMS in case we need to do any substitution into non-type
8121 template parameter types.
8123 OUTER_ARGS are not the right outer levels in this case, as they are
8124 the args we're building up for PARM, and for the coercion we want the
8125 args for ARG. If DECL_CONTEXT isn't set for a template template
8126 parameter, we can assume that it's in the current scope. In that case
8127 we might end up adding more levels than needed, but that shouldn't be
8128 a problem; any args we need to refer to are at the right level. */
8129 tree ctx = DECL_CONTEXT (arg_tmpl);
8130 if (!ctx && DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
8131 ctx = current_scope ();
8132 tree scope_args = NULL_TREE;
8133 if (tree tinfo = get_template_info (ctx))
8134 scope_args = TI_ARGS (tinfo);
8135 pargs = add_to_template_args (scope_args, pargs);
8137 pargs = coerce_template_parms (arg_parms, pargs, NULL_TREE, tf_none);
8138 if (pargs != error_mark_node)
8140 tree targs = make_tree_vec (nargs);
8141 tree aargs = template_parms_level_to_args (arg_parms);
8142 if (!unify (arg_parms, targs, aargs, pargs, UNIFY_ALLOW_NONE,
8143 /*explain*/false))
8144 return 1;
8148 /* Determine whether we have a parameter pack at the end of the
8149 template template parameter's template parameter list. */
8150 if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
8152 parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
8154 if (error_operand_p (parm))
8155 return 0;
8157 switch (TREE_CODE (parm))
8159 case TEMPLATE_DECL:
8160 case TYPE_DECL:
8161 if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
8162 variadic_p = 1;
8163 break;
8165 case PARM_DECL:
8166 if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
8167 variadic_p = 1;
8168 break;
8170 default:
8171 gcc_unreachable ();
8175 if (nargs != nparms
8176 && !(variadic_p && nargs >= nparms - 1))
8177 return 0;
8179 /* Check all of the template parameters except the parameter pack at
8180 the end (if any). */
8181 for (i = 0; i < nparms - variadic_p; ++i)
8183 if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
8184 || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
8185 continue;
8187 parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
8188 arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
8190 if (!coerce_template_template_parm (parm, arg, complain, in_decl,
8191 outer_args))
8192 return 0;
8196 if (variadic_p)
8198 /* Check each of the template parameters in the template
8199 argument against the template parameter pack at the end of
8200 the template template parameter. */
8201 if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
8202 return 0;
8204 parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
8206 for (; i < nargs; ++i)
8208 if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
8209 continue;
8211 arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
8213 if (!coerce_template_template_parm (parm, arg, complain, in_decl,
8214 outer_args))
8215 return 0;
8219 return 1;
8222 /* Verifies that the deduced template arguments (in TARGS) for the
8223 template template parameters (in TPARMS) represent valid bindings,
8224 by comparing the template parameter list of each template argument
8225 to the template parameter list of its corresponding template
8226 template parameter, in accordance with DR150. This
8227 routine can only be called after all template arguments have been
8228 deduced. It will return TRUE if all of the template template
8229 parameter bindings are okay, FALSE otherwise. */
8230 bool
8231 template_template_parm_bindings_ok_p (tree tparms, tree targs)
8233 int i, ntparms = TREE_VEC_LENGTH (tparms);
8234 bool ret = true;
8236 /* We're dealing with template parms in this process. */
8237 ++processing_template_decl;
8239 targs = INNERMOST_TEMPLATE_ARGS (targs);
8241 for (i = 0; i < ntparms; ++i)
8243 tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
8244 tree targ = TREE_VEC_ELT (targs, i);
8246 if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
8248 tree packed_args = NULL_TREE;
8249 int idx, len = 1;
8251 if (ARGUMENT_PACK_P (targ))
8253 /* Look inside the argument pack. */
8254 packed_args = ARGUMENT_PACK_ARGS (targ);
8255 len = TREE_VEC_LENGTH (packed_args);
8258 for (idx = 0; idx < len; ++idx)
8260 if (packed_args)
8261 /* Extract the next argument from the argument
8262 pack. */
8263 targ = TREE_VEC_ELT (packed_args, idx);
8265 if (PACK_EXPANSION_P (targ))
8266 /* Look at the pattern of the pack expansion. */
8267 targ = PACK_EXPANSION_PATTERN (targ);
8269 /* Extract the template parameters from the template
8270 argument. */
8271 if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
8272 targ = TYPE_NAME (targ);
8274 /* Verify that we can coerce the template template
8275 parameters from the template argument to the template
8276 parameter. This requires an exact match. */
8277 if (TREE_CODE (targ) == TEMPLATE_DECL
8278 && !coerce_template_template_parms
8279 (tparm,
8280 targ,
8281 tf_none,
8282 tparm,
8283 targs))
8285 ret = false;
8286 goto out;
8292 out:
8294 --processing_template_decl;
8295 return ret;
8298 /* Since type attributes aren't mangled, we need to strip them from
8299 template type arguments. */
8301 tree
8302 canonicalize_type_argument (tree arg, tsubst_flags_t complain)
8304 if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
8305 return arg;
8306 bool removed_attributes = false;
8307 tree canon = strip_typedefs (arg, &removed_attributes);
8308 if (removed_attributes
8309 && (complain & tf_warning))
8310 warning (OPT_Wignored_attributes,
8311 "ignoring attributes on template argument %qT", arg);
8312 return canon;
8315 /* And from inside dependent non-type arguments like sizeof(Type). */
8317 static tree
8318 canonicalize_expr_argument (tree arg, tsubst_flags_t complain)
8320 if (!arg || arg == error_mark_node)
8321 return arg;
8322 bool removed_attributes = false;
8323 tree canon = strip_typedefs_expr (arg, &removed_attributes);
8324 if (removed_attributes
8325 && (complain & tf_warning))
8326 warning (OPT_Wignored_attributes,
8327 "ignoring attributes in template argument %qE", arg);
8328 return canon;
8331 /* A template declaration can be substituted for a constrained
8332 template template parameter only when the argument is no more
8333 constrained than the parameter. */
8335 static bool
8336 is_compatible_template_arg (tree parm, tree arg)
8338 tree parm_cons = get_constraints (parm);
8340 /* For now, allow constrained template template arguments
8341 and unconstrained template template parameters. */
8342 if (parm_cons == NULL_TREE)
8343 return true;
8345 /* If the template parameter is constrained, we need to rewrite its
8346 constraints in terms of the ARG's template parameters. This ensures
8347 that all of the template parameter types will have the same depth.
8349 Note that this is only valid when coerce_template_template_parm is
8350 true for the innermost template parameters of PARM and ARG. In other
8351 words, because coercion is successful, this conversion will be valid. */
8352 tree new_args = NULL_TREE;
8353 if (parm_cons)
8355 tree aparms = DECL_INNERMOST_TEMPLATE_PARMS (arg);
8356 new_args = template_parms_level_to_args (aparms);
8357 ++processing_template_decl;
8358 parm_cons = tsubst_constraint_info (parm_cons, new_args,
8359 tf_none, NULL_TREE);
8360 --processing_template_decl;
8361 if (parm_cons == error_mark_node)
8362 return false;
8365 return weakly_subsumes (parm_cons, arg);
8368 // Convert a placeholder argument into a binding to the original
8369 // parameter. The original parameter is saved as the TREE_TYPE of
8370 // ARG.
8371 static inline tree
8372 convert_wildcard_argument (tree parm, tree arg)
8374 TREE_TYPE (arg) = parm;
8375 return arg;
8378 /* We can't fully resolve ARG given as a non-type template argument to TYPE,
8379 because one of them is dependent. But we need to represent the
8380 conversion for the benefit of cp_tree_equal. */
8382 static tree
8383 maybe_convert_nontype_argument (tree type, tree arg)
8385 /* Auto parms get no conversion. */
8386 if (type_uses_auto (type))
8387 return arg;
8388 /* We don't need or want to add this conversion now if we're going to use the
8389 argument for deduction. */
8390 if (value_dependent_expression_p (arg))
8391 return arg;
8393 type = cv_unqualified (type);
8394 tree argtype = TREE_TYPE (arg);
8395 if (same_type_p (type, argtype))
8396 return arg;
8398 arg = build1 (IMPLICIT_CONV_EXPR, type, arg);
8399 IMPLICIT_CONV_EXPR_NONTYPE_ARG (arg) = true;
8400 return arg;
8403 /* Convert the indicated template ARG as necessary to match the
8404 indicated template PARM. Returns the converted ARG, or
8405 error_mark_node if the conversion was unsuccessful. Error and
8406 warning messages are issued under control of COMPLAIN. This
8407 conversion is for the Ith parameter in the parameter list. ARGS is
8408 the full set of template arguments deduced so far. */
8410 static tree
8411 convert_template_argument (tree parm,
8412 tree arg,
8413 tree args,
8414 tsubst_flags_t complain,
8415 int i,
8416 tree in_decl)
8418 tree orig_arg;
8419 tree val;
8420 int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
8422 if (parm == error_mark_node || error_operand_p (arg))
8423 return error_mark_node;
8425 /* Trivially convert placeholders. */
8426 if (TREE_CODE (arg) == WILDCARD_DECL)
8427 return convert_wildcard_argument (parm, arg);
8429 if (arg == any_targ_node)
8430 return arg;
8432 if (TREE_CODE (arg) == TREE_LIST
8433 && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
8435 /* The template argument was the name of some
8436 member function. That's usually
8437 invalid, but static members are OK. In any
8438 case, grab the underlying fields/functions
8439 and issue an error later if required. */
8440 TREE_TYPE (arg) = unknown_type_node;
8443 orig_arg = arg;
8445 requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
8446 requires_type = (TREE_CODE (parm) == TYPE_DECL
8447 || requires_tmpl_type);
8449 /* When determining whether an argument pack expansion is a template,
8450 look at the pattern. */
8451 if (PACK_EXPANSION_P (arg))
8452 arg = PACK_EXPANSION_PATTERN (arg);
8454 /* Deal with an injected-class-name used as a template template arg. */
8455 if (requires_tmpl_type && CLASS_TYPE_P (arg))
8457 tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
8458 if (TREE_CODE (t) == TEMPLATE_DECL)
8460 if (cxx_dialect >= cxx11)
8461 /* OK under DR 1004. */;
8462 else if (complain & tf_warning_or_error)
8463 pedwarn (input_location, OPT_Wpedantic, "injected-class-name %qD"
8464 " used as template template argument", TYPE_NAME (arg));
8465 else if (flag_pedantic_errors)
8466 t = arg;
8468 arg = t;
8472 is_tmpl_type =
8473 ((TREE_CODE (arg) == TEMPLATE_DECL
8474 && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
8475 || (requires_tmpl_type && TREE_CODE (arg) == TYPE_ARGUMENT_PACK)
8476 || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
8477 || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
8479 if (is_tmpl_type
8480 && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
8481 || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
8482 arg = TYPE_STUB_DECL (arg);
8484 is_type = TYPE_P (arg) || is_tmpl_type;
8486 if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
8487 && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
8489 if (TREE_CODE (TREE_OPERAND (arg, 1)) == BIT_NOT_EXPR)
8491 if (complain & tf_error)
8492 error ("invalid use of destructor %qE as a type", orig_arg);
8493 return error_mark_node;
8496 permerror (input_location,
8497 "to refer to a type member of a template parameter, "
8498 "use %<typename %E%>", orig_arg);
8500 orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
8501 TREE_OPERAND (arg, 1),
8502 typename_type,
8503 complain);
8504 arg = orig_arg;
8505 is_type = 1;
8507 if (is_type != requires_type)
8509 if (in_decl)
8511 if (complain & tf_error)
8513 error ("type/value mismatch at argument %d in template "
8514 "parameter list for %qD",
8515 i + 1, in_decl);
8516 if (is_type)
8518 /* The template argument is a type, but we're expecting
8519 an expression. */
8520 inform (input_location,
8521 " expected a constant of type %qT, got %qT",
8522 TREE_TYPE (parm),
8523 (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
8524 /* [temp.arg]/2: "In a template-argument, an ambiguity
8525 between a type-id and an expression is resolved to a
8526 type-id, regardless of the form of the corresponding
8527 template-parameter." So give the user a clue. */
8528 if (TREE_CODE (arg) == FUNCTION_TYPE)
8529 inform (input_location, " ambiguous template argument "
8530 "for non-type template parameter is treated as "
8531 "function type");
8533 else if (requires_tmpl_type)
8534 inform (input_location,
8535 " expected a class template, got %qE", orig_arg);
8536 else
8537 inform (input_location,
8538 " expected a type, got %qE", orig_arg);
8541 return error_mark_node;
8543 if (is_tmpl_type ^ requires_tmpl_type)
8545 if (in_decl && (complain & tf_error))
8547 error ("type/value mismatch at argument %d in template "
8548 "parameter list for %qD",
8549 i + 1, in_decl);
8550 if (is_tmpl_type)
8551 inform (input_location,
8552 " expected a type, got %qT", DECL_NAME (arg));
8553 else
8554 inform (input_location,
8555 " expected a class template, got %qT", orig_arg);
8557 return error_mark_node;
8560 if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
8561 /* We already did the appropriate conversion when packing args. */
8562 val = orig_arg;
8563 else if (is_type)
8565 if (requires_tmpl_type)
8567 if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
8568 /* The number of argument required is not known yet.
8569 Just accept it for now. */
8570 val = orig_arg;
8571 else
8573 /* Strip alias templates that are equivalent to another
8574 template. */
8575 arg = get_underlying_template (arg);
8577 if (coerce_template_template_parms (parm, arg,
8578 complain, in_decl,
8579 args))
8581 val = arg;
8583 /* TEMPLATE_TEMPLATE_PARM node is preferred over
8584 TEMPLATE_DECL. */
8585 if (val != error_mark_node)
8587 if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
8588 val = TREE_TYPE (val);
8589 if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
8590 val = make_pack_expansion (val, complain);
8593 else
8595 if (in_decl && (complain & tf_error))
8597 error ("type/value mismatch at argument %d in "
8598 "template parameter list for %qD",
8599 i + 1, in_decl);
8600 inform (input_location,
8601 " expected a template of type %qD, got %qT",
8602 parm, orig_arg);
8605 val = error_mark_node;
8608 // Check that the constraints are compatible before allowing the
8609 // substitution.
8610 if (val != error_mark_node)
8611 if (!is_compatible_template_arg (parm, arg))
8613 if (in_decl && (complain & tf_error))
8615 error ("constraint mismatch at argument %d in "
8616 "template parameter list for %qD",
8617 i + 1, in_decl);
8618 inform (input_location, " expected %qD but got %qD",
8619 parm, arg);
8621 val = error_mark_node;
8625 else
8626 val = orig_arg;
8627 /* We only form one instance of each template specialization.
8628 Therefore, if we use a non-canonical variant (i.e., a
8629 typedef), any future messages referring to the type will use
8630 the typedef, which is confusing if those future uses do not
8631 themselves also use the typedef. */
8632 if (TYPE_P (val))
8633 val = canonicalize_type_argument (val, complain);
8635 else
8637 tree t = TREE_TYPE (parm);
8639 if (TEMPLATE_PARM_LEVEL (get_template_parm_index (parm))
8640 > TMPL_ARGS_DEPTH (args))
8641 /* We don't have enough levels of args to do any substitution. This
8642 can happen in the context of -fnew-ttp-matching. */;
8643 else if (tree a = type_uses_auto (t))
8645 t = do_auto_deduction (t, arg, a, complain, adc_unify, args,
8646 LOOKUP_IMPLICIT, /*tmpl=*/in_decl);
8647 if (t == error_mark_node)
8648 return error_mark_node;
8650 else
8651 t = tsubst (t, args, complain, in_decl);
8653 /* Perform array-to-pointer and function-to-pointer conversion
8654 as per [temp.param]/10. */
8655 t = type_decays_to (t);
8657 if (invalid_nontype_parm_type_p (t, complain))
8658 return error_mark_node;
8660 /* Drop top-level cv-qualifiers on the substituted/deduced type of
8661 this non-type template parameter, as per [temp.param]/6. */
8662 t = cv_unqualified (t);
8664 if (t != TREE_TYPE (parm))
8665 t = canonicalize_type_argument (t, complain);
8667 if (!type_dependent_expression_p (orig_arg)
8668 && !uses_template_parms (t))
8669 /* We used to call digest_init here. However, digest_init
8670 will report errors, which we don't want when complain
8671 is zero. More importantly, digest_init will try too
8672 hard to convert things: for example, `0' should not be
8673 converted to pointer type at this point according to
8674 the standard. Accepting this is not merely an
8675 extension, since deciding whether or not these
8676 conversions can occur is part of determining which
8677 function template to call, or whether a given explicit
8678 argument specification is valid. */
8679 val = convert_nontype_argument (t, orig_arg, complain);
8680 else
8682 val = canonicalize_expr_argument (orig_arg, complain);
8683 val = maybe_convert_nontype_argument (t, val);
8687 if (val == NULL_TREE)
8688 val = error_mark_node;
8689 else if (val == error_mark_node && (complain & tf_error))
8690 error_at (cp_expr_loc_or_input_loc (orig_arg),
8691 "could not convert template argument %qE from %qT to %qT",
8692 orig_arg, TREE_TYPE (orig_arg), t);
8694 if (INDIRECT_REF_P (val))
8696 /* Reject template arguments that are references to built-in
8697 functions with no library fallbacks. */
8698 const_tree inner = TREE_OPERAND (val, 0);
8699 const_tree innertype = TREE_TYPE (inner);
8700 if (innertype
8701 && TYPE_REF_P (innertype)
8702 && TREE_CODE (TREE_TYPE (innertype)) == FUNCTION_TYPE
8703 && TREE_OPERAND_LENGTH (inner) > 0
8704 && reject_gcc_builtin (TREE_OPERAND (inner, 0)))
8705 return error_mark_node;
8708 if (TREE_CODE (val) == SCOPE_REF)
8710 /* Strip typedefs from the SCOPE_REF. */
8711 tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
8712 tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
8713 complain);
8714 val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
8715 QUALIFIED_NAME_IS_TEMPLATE (val));
8719 return val;
8722 /* Coerces the remaining template arguments in INNER_ARGS (from
8723 ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
8724 Returns the coerced argument pack. PARM_IDX is the position of this
8725 parameter in the template parameter list. ARGS is the original
8726 template argument list. */
8727 static tree
8728 coerce_template_parameter_pack (tree parms,
8729 int parm_idx,
8730 tree args,
8731 tree inner_args,
8732 int arg_idx,
8733 tree new_args,
8734 int* lost,
8735 tree in_decl,
8736 tsubst_flags_t complain)
8738 tree parm = TREE_VEC_ELT (parms, parm_idx);
8739 int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8740 tree packed_args;
8741 tree argument_pack;
8742 tree packed_parms = NULL_TREE;
8744 if (arg_idx > nargs)
8745 arg_idx = nargs;
8747 if (tree packs = fixed_parameter_pack_p (TREE_VALUE (parm)))
8749 /* When the template parameter is a non-type template parameter pack
8750 or template template parameter pack whose type or template
8751 parameters use parameter packs, we know exactly how many arguments
8752 we are looking for. Build a vector of the instantiated decls for
8753 these template parameters in PACKED_PARMS. */
8754 /* We can't use make_pack_expansion here because it would interpret a
8755 _DECL as a use rather than a declaration. */
8756 tree decl = TREE_VALUE (parm);
8757 tree exp = cxx_make_type (TYPE_PACK_EXPANSION);
8758 PACK_EXPANSION_PATTERN (exp) = decl;
8759 PACK_EXPANSION_PARAMETER_PACKS (exp) = packs;
8760 SET_TYPE_STRUCTURAL_EQUALITY (exp);
8762 TREE_VEC_LENGTH (args)--;
8763 packed_parms = tsubst_pack_expansion (exp, args, complain, decl);
8764 TREE_VEC_LENGTH (args)++;
8766 if (packed_parms == error_mark_node)
8767 return error_mark_node;
8769 /* If we're doing a partial instantiation of a member template,
8770 verify that all of the types used for the non-type
8771 template parameter pack are, in fact, valid for non-type
8772 template parameters. */
8773 if (arg_idx < nargs
8774 && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
8776 int j, len = TREE_VEC_LENGTH (packed_parms);
8777 for (j = 0; j < len; ++j)
8779 tree t = TREE_VEC_ELT (packed_parms, j);
8780 if (TREE_CODE (t) == PARM_DECL
8781 && invalid_nontype_parm_type_p (TREE_TYPE (t), complain))
8782 return error_mark_node;
8784 /* We don't know how many args we have yet, just
8785 use the unconverted ones for now. */
8786 return NULL_TREE;
8789 packed_args = make_tree_vec (TREE_VEC_LENGTH (packed_parms));
8791 /* Check if we have a placeholder pack, which indicates we're
8792 in the context of a introduction list. In that case we want
8793 to match this pack to the single placeholder. */
8794 else if (arg_idx < nargs
8795 && TREE_CODE (TREE_VEC_ELT (inner_args, arg_idx)) == WILDCARD_DECL
8796 && WILDCARD_PACK_P (TREE_VEC_ELT (inner_args, arg_idx)))
8798 nargs = arg_idx + 1;
8799 packed_args = make_tree_vec (1);
8801 else
8802 packed_args = make_tree_vec (nargs - arg_idx);
8804 /* Convert the remaining arguments, which will be a part of the
8805 parameter pack "parm". */
8806 int first_pack_arg = arg_idx;
8807 for (; arg_idx < nargs; ++arg_idx)
8809 tree arg = TREE_VEC_ELT (inner_args, arg_idx);
8810 tree actual_parm = TREE_VALUE (parm);
8811 int pack_idx = arg_idx - first_pack_arg;
8813 if (packed_parms)
8815 /* Once we've packed as many args as we have types, stop. */
8816 if (pack_idx >= TREE_VEC_LENGTH (packed_parms))
8817 break;
8818 else if (PACK_EXPANSION_P (arg))
8819 /* We don't know how many args we have yet, just
8820 use the unconverted ones for now. */
8821 return NULL_TREE;
8822 else
8823 actual_parm = TREE_VEC_ELT (packed_parms, pack_idx);
8826 if (arg == error_mark_node)
8828 if (complain & tf_error)
8829 error ("template argument %d is invalid", arg_idx + 1);
8831 else
8832 arg = convert_template_argument (actual_parm,
8833 arg, new_args, complain, parm_idx,
8834 in_decl);
8835 if (arg == error_mark_node)
8836 (*lost)++;
8837 TREE_VEC_ELT (packed_args, pack_idx) = arg;
8840 if (arg_idx - first_pack_arg < TREE_VEC_LENGTH (packed_args)
8841 && TREE_VEC_LENGTH (packed_args) > 0)
8843 if (complain & tf_error)
8844 error ("wrong number of template arguments (%d, should be %d)",
8845 arg_idx - first_pack_arg, TREE_VEC_LENGTH (packed_args));
8846 return error_mark_node;
8849 if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
8850 || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
8851 argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
8852 else
8854 argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
8855 TREE_CONSTANT (argument_pack) = 1;
8858 ARGUMENT_PACK_ARGS (argument_pack) = packed_args;
8859 if (CHECKING_P)
8860 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
8861 TREE_VEC_LENGTH (packed_args));
8862 return argument_pack;
8865 /* Returns the number of pack expansions in the template argument vector
8866 ARGS. */
8868 static int
8869 pack_expansion_args_count (tree args)
8871 int i;
8872 int count = 0;
8873 if (args)
8874 for (i = 0; i < TREE_VEC_LENGTH (args); ++i)
8876 tree elt = TREE_VEC_ELT (args, i);
8877 if (elt && PACK_EXPANSION_P (elt))
8878 ++count;
8880 return count;
8883 /* Convert all template arguments to their appropriate types, and
8884 return a vector containing the innermost resulting template
8885 arguments. If any error occurs, return error_mark_node. Error and
8886 warning messages are issued under control of COMPLAIN.
8888 If PARMS represents all template parameters levels, this function
8889 returns a vector of vectors representing all the resulting argument
8890 levels. Note that in this case, only the innermost arguments are
8891 coerced because the outermost ones are supposed to have been coerced
8892 already. Otherwise, if PARMS represents only (the innermost) vector
8893 of parameters, this function returns a vector containing just the
8894 innermost resulting arguments.
8896 If REQUIRE_ALL_ARGS is false, argument deduction will be performed
8897 for arguments not specified in ARGS. If REQUIRE_ALL_ARGS is true,
8898 arguments not specified in ARGS must have default arguments which
8899 we'll use to fill in ARGS. */
8901 tree
8902 coerce_template_parms (tree parms,
8903 tree args,
8904 tree in_decl,
8905 tsubst_flags_t complain,
8906 bool require_all_args /* = true */)
8908 int nparms, nargs, parm_idx, arg_idx, lost = 0;
8909 tree orig_inner_args;
8910 tree inner_args;
8912 /* When used as a boolean value, indicates whether this is a
8913 variadic template parameter list. Since it's an int, we can also
8914 subtract it from nparms to get the number of non-variadic
8915 parameters. */
8916 int variadic_p = 0;
8917 int variadic_args_p = 0;
8918 int post_variadic_parms = 0;
8920 /* Adjustment to nparms for fixed parameter packs. */
8921 int fixed_pack_adjust = 0;
8922 int fixed_packs = 0;
8923 int missing = 0;
8925 /* Likewise for parameters with default arguments. */
8926 int default_p = 0;
8928 if (args == error_mark_node)
8929 return error_mark_node;
8931 bool return_full_args = false;
8932 if (TREE_CODE (parms) == TREE_LIST)
8934 if (TMPL_PARMS_DEPTH (parms) > 1)
8936 gcc_assert (TMPL_PARMS_DEPTH (parms) == TMPL_ARGS_DEPTH (args));
8937 return_full_args = true;
8939 parms = INNERMOST_TEMPLATE_PARMS (parms);
8942 nparms = TREE_VEC_LENGTH (parms);
8944 /* Determine if there are any parameter packs or default arguments. */
8945 for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
8947 tree parm = TREE_VEC_ELT (parms, parm_idx);
8948 if (variadic_p)
8949 ++post_variadic_parms;
8950 if (template_parameter_pack_p (TREE_VALUE (parm)))
8951 ++variadic_p;
8952 if (TREE_PURPOSE (parm))
8953 ++default_p;
8956 inner_args = orig_inner_args = INNERMOST_TEMPLATE_ARGS (args);
8957 /* If there are no parameters that follow a parameter pack, we need to
8958 expand any argument packs so that we can deduce a parameter pack from
8959 some non-packed args followed by an argument pack, as in variadic85.C.
8960 If there are such parameters, we need to leave argument packs intact
8961 so the arguments are assigned properly. This can happen when dealing
8962 with a nested class inside a partial specialization of a class
8963 template, as in variadic92.C, or when deducing a template parameter pack
8964 from a sub-declarator, as in variadic114.C. */
8965 if (!post_variadic_parms)
8966 inner_args = expand_template_argument_pack (inner_args);
8968 /* Count any pack expansion args. */
8969 variadic_args_p = pack_expansion_args_count (inner_args);
8971 nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8972 if ((nargs - variadic_args_p > nparms && !variadic_p)
8973 || (nargs < nparms - variadic_p
8974 && require_all_args
8975 && !variadic_args_p
8976 && (TREE_VEC_ELT (parms, nargs) != error_mark_node
8977 && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs)))))
8979 bad_nargs:
8980 if (complain & tf_error)
8982 if (variadic_p || default_p)
8984 nparms -= variadic_p + default_p;
8985 error ("wrong number of template arguments "
8986 "(%d, should be at least %d)", nargs, nparms);
8988 else
8989 error ("wrong number of template arguments "
8990 "(%d, should be %d)", nargs, nparms);
8992 if (in_decl)
8993 inform (DECL_SOURCE_LOCATION (in_decl),
8994 "provided for %qD", in_decl);
8997 return error_mark_node;
8999 /* We can't pass a pack expansion to a non-pack parameter of an alias
9000 template (DR 1430). */
9001 else if (in_decl
9002 && (DECL_ALIAS_TEMPLATE_P (in_decl)
9003 || concept_definition_p (in_decl))
9004 && variadic_args_p
9005 && nargs - variadic_args_p < nparms - variadic_p)
9007 if (complain & tf_error)
9009 for (int i = 0; i < TREE_VEC_LENGTH (inner_args); ++i)
9011 tree arg = TREE_VEC_ELT (inner_args, i);
9012 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
9014 if (PACK_EXPANSION_P (arg)
9015 && !template_parameter_pack_p (parm))
9017 if (DECL_ALIAS_TEMPLATE_P (in_decl))
9018 error_at (location_of (arg),
9019 "pack expansion argument for non-pack parameter "
9020 "%qD of alias template %qD", parm, in_decl);
9021 else
9022 error_at (location_of (arg),
9023 "pack expansion argument for non-pack parameter "
9024 "%qD of concept %qD", parm, in_decl);
9025 inform (DECL_SOURCE_LOCATION (parm), "declared here");
9026 goto found;
9029 gcc_unreachable ();
9030 found:;
9032 return error_mark_node;
9035 /* We need to evaluate the template arguments, even though this
9036 template-id may be nested within a "sizeof". */
9037 cp_evaluated ev;
9039 tree new_args = add_outermost_template_args (args, make_tree_vec (nparms));
9040 tree& new_inner_args = TMPL_ARGS_LEVEL (new_args, TMPL_ARGS_DEPTH (new_args));
9041 int pack_adjust = 0;
9042 for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
9044 tree arg;
9045 tree parm;
9047 /* Get the Ith template parameter. */
9048 parm = TREE_VEC_ELT (parms, parm_idx);
9050 if (parm == error_mark_node)
9052 TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
9053 continue;
9056 /* Calculate the next argument. */
9057 if (arg_idx < nargs)
9058 arg = TREE_VEC_ELT (inner_args, arg_idx);
9059 else
9060 arg = NULL_TREE;
9062 if (template_parameter_pack_p (TREE_VALUE (parm))
9063 && (arg || require_all_args || !(complain & tf_partial))
9064 && !(arg && ARGUMENT_PACK_P (arg)))
9066 /* Some arguments will be placed in the
9067 template parameter pack PARM. */
9068 arg = coerce_template_parameter_pack (parms, parm_idx, args,
9069 inner_args, arg_idx,
9070 new_args, &lost,
9071 in_decl, complain);
9073 if (arg == NULL_TREE)
9075 /* We don't know how many args we have yet, just use the
9076 unconverted (and still packed) ones for now. */
9077 new_inner_args = orig_inner_args;
9078 arg_idx = nargs;
9079 break;
9082 TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
9084 /* Store this argument. */
9085 if (arg == error_mark_node)
9087 lost++;
9088 /* We are done with all of the arguments. */
9089 arg_idx = nargs;
9090 break;
9092 else
9094 pack_adjust = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg)) - 1;
9095 arg_idx += pack_adjust;
9096 if (fixed_parameter_pack_p (TREE_VALUE (parm)))
9098 ++fixed_packs;
9099 fixed_pack_adjust += pack_adjust;
9103 continue;
9105 else if (arg)
9107 if (PACK_EXPANSION_P (arg))
9109 /* "If every valid specialization of a variadic template
9110 requires an empty template parameter pack, the template is
9111 ill-formed, no diagnostic required." So check that the
9112 pattern works with this parameter. */
9113 tree pattern = PACK_EXPANSION_PATTERN (arg);
9114 tree conv = convert_template_argument (TREE_VALUE (parm),
9115 pattern, new_args,
9116 complain, parm_idx,
9117 in_decl);
9118 if (conv == error_mark_node)
9120 if (complain & tf_error)
9121 inform (input_location, "so any instantiation with a "
9122 "non-empty parameter pack would be ill-formed");
9123 ++lost;
9125 else if (TYPE_P (conv) && !TYPE_P (pattern))
9126 /* Recover from missing typename. */
9127 TREE_VEC_ELT (inner_args, arg_idx)
9128 = make_pack_expansion (conv, complain);
9130 /* We don't know how many args we have yet, just
9131 use the unconverted ones for now. */
9132 new_inner_args = inner_args;
9133 arg_idx = nargs;
9134 break;
9137 else if (require_all_args)
9139 /* There must be a default arg in this case. */
9140 arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
9141 complain, in_decl);
9142 /* The position of the first default template argument,
9143 is also the number of non-defaulted arguments in NEW_INNER_ARGS.
9144 Record that. */
9145 if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
9146 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
9147 arg_idx - pack_adjust);
9149 else
9150 break;
9152 if (arg == error_mark_node)
9154 if (complain & tf_error)
9155 error ("template argument %d is invalid", arg_idx + 1);
9157 else if (!arg)
9159 /* This can occur if there was an error in the template
9160 parameter list itself (which we would already have
9161 reported) that we are trying to recover from, e.g., a class
9162 template with a parameter list such as
9163 template<typename..., typename> (cpp0x/variadic150.C). */
9164 ++lost;
9166 /* This can also happen with a fixed parameter pack (71834). */
9167 if (arg_idx >= nargs)
9168 ++missing;
9170 else
9171 arg = convert_template_argument (TREE_VALUE (parm),
9172 arg, new_args, complain,
9173 parm_idx, in_decl);
9175 if (arg == error_mark_node)
9176 lost++;
9178 TREE_VEC_ELT (new_inner_args, arg_idx - pack_adjust) = arg;
9181 if (missing || arg_idx < nargs - variadic_args_p)
9183 /* If we had fixed parameter packs, we didn't know how many arguments we
9184 actually needed earlier; now we do. */
9185 nparms += fixed_pack_adjust;
9186 variadic_p -= fixed_packs;
9187 goto bad_nargs;
9190 if (arg_idx < nargs)
9192 /* We had some pack expansion arguments that will only work if the packs
9193 are empty, but wait until instantiation time to complain.
9194 See variadic-ttp3.C. */
9196 /* Except that we can't provide empty packs to alias templates or
9197 concepts when there are no corresponding parameters. Basically,
9198 we can get here with this:
9200 template<typename T> concept C = true;
9202 template<typename... Args>
9203 requires C<Args...>
9204 void f();
9206 When parsing C<Args...>, we try to form a concept check of
9207 C<?, Args...>. Without the extra check for substituting an empty
9208 pack past the last parameter, we can accept the check as valid.
9210 FIXME: This may be valid for alias templates (but I doubt it).
9212 FIXME: The error could be better also. */
9213 if (in_decl && concept_definition_p (in_decl))
9215 if (complain & tf_error)
9216 error_at (location_of (TREE_VEC_ELT (args, arg_idx)),
9217 "too many arguments");
9218 return error_mark_node;
9221 int len = nparms + (nargs - arg_idx);
9222 tree args = make_tree_vec (len);
9223 int i = 0;
9224 for (; i < nparms; ++i)
9225 TREE_VEC_ELT (args, i) = TREE_VEC_ELT (new_inner_args, i);
9226 for (; i < len; ++i, ++arg_idx)
9227 TREE_VEC_ELT (args, i) = TREE_VEC_ELT (inner_args,
9228 arg_idx - pack_adjust);
9229 new_inner_args = args;
9232 if (lost)
9234 gcc_assert (!(complain & tf_error) || seen_error ());
9235 return error_mark_node;
9238 if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
9239 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
9240 TREE_VEC_LENGTH (new_inner_args));
9242 return return_full_args ? new_args : new_inner_args;
9245 /* Returns true if T is a wrapper to make a C++20 template parameter
9246 object const. */
9248 static bool
9249 class_nttp_const_wrapper_p (tree t)
9251 if (cxx_dialect < cxx20)
9252 return false;
9253 return (TREE_CODE (t) == VIEW_CONVERT_EXPR
9254 && CP_TYPE_CONST_P (TREE_TYPE (t))
9255 && TREE_CODE (TREE_OPERAND (t, 0)) == TEMPLATE_PARM_INDEX);
9258 /* Returns 1 if template args OT and NT are equivalent. */
9261 template_args_equal (tree ot, tree nt, bool partial_order /* = false */)
9263 if (nt == ot)
9264 return 1;
9265 if (nt == NULL_TREE || ot == NULL_TREE)
9266 return false;
9267 if (nt == any_targ_node || ot == any_targ_node)
9268 return true;
9270 if (class_nttp_const_wrapper_p (nt))
9271 nt = TREE_OPERAND (nt, 0);
9272 if (class_nttp_const_wrapper_p (ot))
9273 ot = TREE_OPERAND (ot, 0);
9275 /* DR 1558: Don't treat an alias template specialization with dependent
9276 arguments as equivalent to its underlying type when used as a template
9277 argument; we need them to be distinct so that we substitute into the
9278 specialization arguments at instantiation time. And aliases can't be
9279 equivalent without being ==, so we don't need to look any deeper.
9281 During partial ordering, however, we need to treat them normally so we can
9282 order uses of the same alias with different cv-qualification (79960). */
9283 auto cso = make_temp_override (comparing_dependent_aliases);
9284 if (!partial_order)
9285 ++comparing_dependent_aliases;
9287 if (TREE_CODE (nt) == TREE_VEC || TREE_CODE (ot) == TREE_VEC)
9288 /* For member templates */
9289 return TREE_CODE (ot) == TREE_CODE (nt) && comp_template_args (ot, nt);
9290 else if (PACK_EXPANSION_P (ot) || PACK_EXPANSION_P (nt))
9291 return (PACK_EXPANSION_P (ot) && PACK_EXPANSION_P (nt)
9292 && template_args_equal (PACK_EXPANSION_PATTERN (ot),
9293 PACK_EXPANSION_PATTERN (nt))
9294 && template_args_equal (PACK_EXPANSION_EXTRA_ARGS (ot),
9295 PACK_EXPANSION_EXTRA_ARGS (nt)));
9296 else if (ARGUMENT_PACK_P (ot) || ARGUMENT_PACK_P (nt))
9297 return cp_tree_equal (ot, nt);
9298 else if (TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
9299 gcc_unreachable ();
9300 else if (TYPE_P (nt) || TYPE_P (ot))
9302 if (!(TYPE_P (nt) && TYPE_P (ot)))
9303 return false;
9304 return same_type_p (ot, nt);
9306 else
9308 /* Try to treat a template non-type argument that has been converted
9309 to the parameter type as equivalent to one that hasn't yet. */
9310 for (enum tree_code code1 = TREE_CODE (ot);
9311 CONVERT_EXPR_CODE_P (code1)
9312 || code1 == NON_LVALUE_EXPR;
9313 code1 = TREE_CODE (ot))
9314 ot = TREE_OPERAND (ot, 0);
9316 for (enum tree_code code2 = TREE_CODE (nt);
9317 CONVERT_EXPR_CODE_P (code2)
9318 || code2 == NON_LVALUE_EXPR;
9319 code2 = TREE_CODE (nt))
9320 nt = TREE_OPERAND (nt, 0);
9322 return cp_tree_equal (ot, nt);
9326 /* Returns true iff the OLDARGS and NEWARGS are in fact identical sets of
9327 template arguments. Returns false otherwise, and updates OLDARG_PTR and
9328 NEWARG_PTR with the offending arguments if they are non-NULL. */
9330 bool
9331 comp_template_args (tree oldargs, tree newargs,
9332 tree *oldarg_ptr /* = NULL */, tree *newarg_ptr /* = NULL */,
9333 bool partial_order /* = false */)
9335 if (oldargs == newargs)
9336 return true;
9338 if (!oldargs || !newargs)
9339 return false;
9341 if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
9342 return false;
9344 for (int i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
9346 tree nt = TREE_VEC_ELT (newargs, i);
9347 tree ot = TREE_VEC_ELT (oldargs, i);
9349 if (! template_args_equal (ot, nt, partial_order))
9351 if (oldarg_ptr != NULL)
9352 *oldarg_ptr = ot;
9353 if (newarg_ptr != NULL)
9354 *newarg_ptr = nt;
9355 return false;
9358 return true;
9361 inline bool
9362 comp_template_args_porder (tree oargs, tree nargs)
9364 return comp_template_args (oargs, nargs, NULL, NULL, true);
9367 /* Implement a freelist interface for objects of type T.
9369 Head is a separate object, rather than a regular member, so that we
9370 can define it as a GTY deletable pointer, which is highly
9371 desirable. A data member could be declared that way, but then the
9372 containing object would implicitly get GTY((user)), which would
9373 prevent us from instantiating freelists as global objects.
9374 Although this way we can create freelist global objects, they're
9375 such thin wrappers that instantiating temporaries at every use
9376 loses nothing and saves permanent storage for the freelist object.
9378 Member functions next, anew, poison and reinit have default
9379 implementations that work for most of the types we're interested
9380 in, but if they don't work for some type, they should be explicitly
9381 specialized. See the comments before them for requirements, and
9382 the example specializations for the tree_list_freelist. */
9383 template <typename T>
9384 class freelist
9386 /* Return the next object in a chain. We could just do type
9387 punning, but if we access the object with its underlying type, we
9388 avoid strict-aliasing trouble. This needs only work between
9389 poison and reinit. */
9390 static T *&next (T *obj) { return obj->next; }
9392 /* Return a newly allocated, uninitialized or minimally-initialized
9393 object of type T. Any initialization performed by anew should
9394 either remain across the life of the object and the execution of
9395 poison, or be redone by reinit. */
9396 static T *anew () { return ggc_alloc<T> (); }
9398 /* Optionally scribble all over the bits holding the object, so that
9399 they become (mostly?) uninitialized memory. This is called while
9400 preparing to make the object part of the free list. */
9401 static void poison (T *obj) {
9402 T *p ATTRIBUTE_UNUSED = obj;
9403 T **q ATTRIBUTE_UNUSED = &next (obj);
9405 #ifdef ENABLE_GC_CHECKING
9406 /* Poison the data, to indicate the data is garbage. */
9407 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, sizeof (*p)));
9408 memset (p, 0xa5, sizeof (*p));
9409 #endif
9410 /* Let valgrind know the object is free. */
9411 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, sizeof (*p)));
9413 /* Let valgrind know the next portion of the object is available,
9414 but uninitialized. */
9415 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
9418 /* Bring an object that underwent at least one lifecycle after anew
9419 and before the most recent free and poison, back to a usable
9420 state, reinitializing whatever is needed for it to be
9421 functionally equivalent to an object just allocated and returned
9422 by anew. This may poison or clear the next field, used by
9423 freelist housekeeping after poison was called. */
9424 static void reinit (T *obj) {
9425 T **q ATTRIBUTE_UNUSED = &next (obj);
9427 #ifdef ENABLE_GC_CHECKING
9428 memset (q, 0xa5, sizeof (*q));
9429 #endif
9430 /* Let valgrind know the entire object is available, but
9431 uninitialized. */
9432 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (*obj)));
9435 /* Reference a GTY-deletable pointer that points to the first object
9436 in the free list proper. */
9437 T *&head;
9438 public:
9439 /* Construct a freelist object chaining objects off of HEAD. */
9440 freelist (T *&head) : head(head) {}
9442 /* Add OBJ to the free object list. The former head becomes OBJ's
9443 successor. */
9444 void free (T *obj)
9446 poison (obj);
9447 next (obj) = head;
9448 head = obj;
9451 /* Take an object from the free list, if one is available, or
9452 allocate a new one. Objects taken from the free list should be
9453 regarded as filled with garbage, except for bits that are
9454 configured to be preserved across free and alloc. */
9455 T *alloc ()
9457 if (head)
9459 T *obj = head;
9460 head = next (head);
9461 reinit (obj);
9462 return obj;
9464 else
9465 return anew ();
9469 /* Explicitly specialize the interfaces for freelist<tree_node>: we
9470 want to allocate a TREE_LIST using the usual interface, and ensure
9471 TREE_CHAIN remains functional. Alas, we have to duplicate a bit of
9472 build_tree_list logic in reinit, so this could go out of sync. */
9473 template <>
9474 inline tree &
9475 freelist<tree_node>::next (tree obj)
9477 return TREE_CHAIN (obj);
9479 template <>
9480 inline tree
9481 freelist<tree_node>::anew ()
9483 return build_tree_list (NULL, NULL);
9485 template <>
9486 inline void
9487 freelist<tree_node>::poison (tree obj ATTRIBUTE_UNUSED)
9489 int size ATTRIBUTE_UNUSED = sizeof (tree_list);
9490 tree p ATTRIBUTE_UNUSED = obj;
9491 tree_base *b ATTRIBUTE_UNUSED = &obj->base;
9492 tree *q ATTRIBUTE_UNUSED = &next (obj);
9494 #ifdef ENABLE_GC_CHECKING
9495 gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
9497 /* Poison the data, to indicate the data is garbage. */
9498 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, size));
9499 memset (p, 0xa5, size);
9500 #endif
9501 /* Let valgrind know the object is free. */
9502 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, size));
9503 /* But we still want to use the TREE_CODE and TREE_CHAIN parts. */
9504 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9505 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
9507 #ifdef ENABLE_GC_CHECKING
9508 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (b, sizeof (*b)));
9509 /* Keep TREE_CHAIN functional. */
9510 TREE_SET_CODE (obj, TREE_LIST);
9511 #else
9512 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9513 #endif
9515 template <>
9516 inline void
9517 freelist<tree_node>::reinit (tree obj ATTRIBUTE_UNUSED)
9519 tree_base *b ATTRIBUTE_UNUSED = &obj->base;
9521 #ifdef ENABLE_GC_CHECKING
9522 gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
9523 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
9524 memset (obj, 0, sizeof (tree_list));
9525 #endif
9527 /* Let valgrind know the entire object is available, but
9528 uninitialized. */
9529 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
9531 #ifdef ENABLE_GC_CHECKING
9532 TREE_SET_CODE (obj, TREE_LIST);
9533 #else
9534 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9535 #endif
9538 /* Point to the first object in the TREE_LIST freelist. */
9539 static GTY((deletable)) tree tree_list_freelist_head;
9540 /* Return the/an actual TREE_LIST freelist. */
9541 static inline freelist<tree_node>
9542 tree_list_freelist ()
9544 return tree_list_freelist_head;
9547 /* Point to the first object in the tinst_level freelist. */
9548 static GTY((deletable)) tinst_level *tinst_level_freelist_head;
9549 /* Return the/an actual tinst_level freelist. */
9550 static inline freelist<tinst_level>
9551 tinst_level_freelist ()
9553 return tinst_level_freelist_head;
9556 /* Point to the first object in the pending_template freelist. */
9557 static GTY((deletable)) pending_template *pending_template_freelist_head;
9558 /* Return the/an actual pending_template freelist. */
9559 static inline freelist<pending_template>
9560 pending_template_freelist ()
9562 return pending_template_freelist_head;
9565 /* Build the TREE_LIST object out of a split list, store it
9566 permanently, and return it. */
9567 tree
9568 tinst_level::to_list ()
9570 gcc_assert (split_list_p ());
9571 tree ret = tree_list_freelist ().alloc ();
9572 TREE_PURPOSE (ret) = tldcl;
9573 TREE_VALUE (ret) = targs;
9574 tldcl = ret;
9575 targs = NULL;
9576 gcc_assert (tree_list_p ());
9577 return ret;
9580 const unsigned short tinst_level::refcount_infinity;
9582 /* Increment OBJ's refcount unless it is already infinite. */
9583 static tinst_level *
9584 inc_refcount_use (tinst_level *obj)
9586 if (obj && obj->refcount != tinst_level::refcount_infinity)
9587 ++obj->refcount;
9588 return obj;
9591 /* Release storage for OBJ and node, if it's a TREE_LIST. */
9592 void
9593 tinst_level::free (tinst_level *obj)
9595 if (obj->tree_list_p ())
9596 tree_list_freelist ().free (obj->get_node ());
9597 tinst_level_freelist ().free (obj);
9600 /* Decrement OBJ's refcount if not infinite. If it reaches zero, release
9601 OBJ's DECL and OBJ, and start over with the tinst_level object that
9602 used to be referenced by OBJ's NEXT. */
9603 static void
9604 dec_refcount_use (tinst_level *obj)
9606 while (obj
9607 && obj->refcount != tinst_level::refcount_infinity
9608 && !--obj->refcount)
9610 tinst_level *next = obj->next;
9611 tinst_level::free (obj);
9612 obj = next;
9616 /* Modify PTR so that it points to OBJ, adjusting the refcounts of OBJ
9617 and of the former PTR. Omitting the second argument is equivalent
9618 to passing (T*)NULL; this is allowed because passing the
9619 zero-valued integral constant NULL confuses type deduction and/or
9620 overload resolution. */
9621 template <typename T>
9622 static void
9623 set_refcount_ptr (T *& ptr, T *obj = NULL)
9625 T *save = ptr;
9626 ptr = inc_refcount_use (obj);
9627 dec_refcount_use (save);
9630 static void
9631 add_pending_template (tree d)
9633 tree ti = (TYPE_P (d)
9634 ? CLASSTYPE_TEMPLATE_INFO (d)
9635 : DECL_TEMPLATE_INFO (d));
9636 struct pending_template *pt;
9637 int level;
9639 if (TI_PENDING_TEMPLATE_FLAG (ti))
9640 return;
9642 /* We are called both from instantiate_decl, where we've already had a
9643 tinst_level pushed, and instantiate_template, where we haven't.
9644 Compensate. */
9645 gcc_assert (TREE_CODE (d) != TREE_LIST);
9646 level = !current_tinst_level
9647 || current_tinst_level->maybe_get_node () != d;
9649 if (level)
9650 push_tinst_level (d);
9652 pt = pending_template_freelist ().alloc ();
9653 pt->next = NULL;
9654 pt->tinst = NULL;
9655 set_refcount_ptr (pt->tinst, current_tinst_level);
9656 if (last_pending_template)
9657 last_pending_template->next = pt;
9658 else
9659 pending_templates = pt;
9661 last_pending_template = pt;
9663 TI_PENDING_TEMPLATE_FLAG (ti) = 1;
9665 if (level)
9666 pop_tinst_level ();
9670 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
9671 ARGLIST. Valid choices for FNS are given in the cp-tree.def
9672 documentation for TEMPLATE_ID_EXPR. */
9674 tree
9675 lookup_template_function (tree fns, tree arglist)
9677 if (fns == error_mark_node || arglist == error_mark_node)
9678 return error_mark_node;
9680 gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
9682 if (!is_overloaded_fn (fns) && !identifier_p (fns))
9684 error ("%q#D is not a function template", fns);
9685 return error_mark_node;
9688 if (BASELINK_P (fns))
9690 fns = copy_node (fns);
9691 BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
9692 unknown_type_node,
9693 BASELINK_FUNCTIONS (fns),
9694 arglist);
9695 return fns;
9698 return build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, arglist);
9701 /* Within the scope of a template class S<T>, the name S gets bound
9702 (in build_self_reference) to a TYPE_DECL for the class, not a
9703 TEMPLATE_DECL. If DECL is a TYPE_DECL for current_class_type,
9704 or one of its enclosing classes, and that type is a template,
9705 return the associated TEMPLATE_DECL. Otherwise, the original
9706 DECL is returned.
9708 Also handle the case when DECL is a TREE_LIST of ambiguous
9709 injected-class-names from different bases. */
9711 tree
9712 maybe_get_template_decl_from_type_decl (tree decl)
9714 if (decl == NULL_TREE)
9715 return decl;
9717 /* DR 176: A lookup that finds an injected-class-name (10.2
9718 [class.member.lookup]) can result in an ambiguity in certain cases
9719 (for example, if it is found in more than one base class). If all of
9720 the injected-class-names that are found refer to specializations of
9721 the same class template, and if the name is followed by a
9722 template-argument-list, the reference refers to the class template
9723 itself and not a specialization thereof, and is not ambiguous. */
9724 if (TREE_CODE (decl) == TREE_LIST)
9726 tree t, tmpl = NULL_TREE;
9727 for (t = decl; t; t = TREE_CHAIN (t))
9729 tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
9730 if (!tmpl)
9731 tmpl = elt;
9732 else if (tmpl != elt)
9733 break;
9735 if (tmpl && t == NULL_TREE)
9736 return tmpl;
9737 else
9738 return decl;
9741 return (decl != NULL_TREE
9742 && DECL_SELF_REFERENCE_P (decl)
9743 && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
9744 ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
9747 /* Given an IDENTIFIER_NODE (or type TEMPLATE_DECL) and a chain of
9748 parameters, find the desired type.
9750 D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
9752 IN_DECL, if non-NULL, is the template declaration we are trying to
9753 instantiate.
9755 If ENTERING_SCOPE is nonzero, we are about to enter the scope of
9756 the class we are looking up.
9758 Issue error and warning messages under control of COMPLAIN.
9760 If the template class is really a local class in a template
9761 function, then the FUNCTION_CONTEXT is the function in which it is
9762 being instantiated.
9764 ??? Note that this function is currently called *twice* for each
9765 template-id: the first time from the parser, while creating the
9766 incomplete type (finish_template_type), and the second type during the
9767 real instantiation (instantiate_template_class). This is surely something
9768 that we want to avoid. It also causes some problems with argument
9769 coercion (see convert_nontype_argument for more information on this). */
9771 tree
9772 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
9773 int entering_scope, tsubst_flags_t complain)
9775 auto_timevar tv (TV_TEMPLATE_INST);
9777 tree templ = NULL_TREE, parmlist;
9778 tree t;
9779 spec_entry **slot;
9780 spec_entry *entry;
9781 spec_entry elt;
9782 hashval_t hash;
9784 if (identifier_p (d1))
9786 tree value = innermost_non_namespace_value (d1);
9787 if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
9788 templ = value;
9789 else
9791 if (context)
9792 push_decl_namespace (context);
9793 templ = lookup_name (d1);
9794 templ = maybe_get_template_decl_from_type_decl (templ);
9795 if (context)
9796 pop_decl_namespace ();
9799 else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
9801 tree type = TREE_TYPE (d1);
9803 /* If we are declaring a constructor, say A<T>::A<T>, we will get
9804 an implicit typename for the second A. Deal with it. */
9805 if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
9806 type = TREE_TYPE (type);
9808 if (CLASSTYPE_TEMPLATE_INFO (type))
9810 templ = CLASSTYPE_TI_TEMPLATE (type);
9811 d1 = DECL_NAME (templ);
9814 else if (TREE_CODE (d1) == ENUMERAL_TYPE
9815 || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
9817 templ = TYPE_TI_TEMPLATE (d1);
9818 d1 = DECL_NAME (templ);
9820 else if (DECL_TYPE_TEMPLATE_P (d1))
9822 templ = d1;
9823 d1 = DECL_NAME (templ);
9825 else if (DECL_TEMPLATE_TEMPLATE_PARM_P (d1))
9827 templ = d1;
9828 d1 = DECL_NAME (templ);
9831 /* Issue an error message if we didn't find a template. */
9832 if (! templ)
9834 if (complain & tf_error)
9835 error ("%qT is not a template", d1);
9836 return error_mark_node;
9839 if (TREE_CODE (templ) != TEMPLATE_DECL
9840 /* Make sure it's a user visible template, if it was named by
9841 the user. */
9842 || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
9843 && !PRIMARY_TEMPLATE_P (templ)))
9845 if (complain & tf_error)
9847 error ("non-template type %qT used as a template", d1);
9848 if (in_decl)
9849 error ("for template declaration %q+D", in_decl);
9851 return error_mark_node;
9854 complain &= ~tf_user;
9856 /* An alias that just changes the name of a template is equivalent to the
9857 other template, so if any of the arguments are pack expansions, strip
9858 the alias to avoid problems with a pack expansion passed to a non-pack
9859 alias template parameter (DR 1430). */
9860 if (pack_expansion_args_count (INNERMOST_TEMPLATE_ARGS (arglist)))
9861 templ = get_underlying_template (templ);
9863 if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
9865 tree parm;
9866 tree arglist2 = coerce_template_args_for_ttp (templ, arglist, complain);
9867 if (arglist2 == error_mark_node
9868 || (!uses_template_parms (arglist2)
9869 && check_instantiated_args (templ, arglist2, complain)))
9870 return error_mark_node;
9872 parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
9873 return parm;
9875 else
9877 tree template_type = TREE_TYPE (templ);
9878 tree gen_tmpl;
9879 tree type_decl;
9880 tree found = NULL_TREE;
9881 int arg_depth;
9882 int parm_depth;
9883 int is_dependent_type;
9884 int use_partial_inst_tmpl = false;
9886 if (template_type == error_mark_node)
9887 /* An error occurred while building the template TEMPL, and a
9888 diagnostic has most certainly been emitted for that
9889 already. Let's propagate that error. */
9890 return error_mark_node;
9892 gen_tmpl = most_general_template (templ);
9893 if (modules_p ())
9894 lazy_load_pendings (gen_tmpl);
9896 parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
9897 parm_depth = TMPL_PARMS_DEPTH (parmlist);
9898 arg_depth = TMPL_ARGS_DEPTH (arglist);
9900 if (arg_depth == 1 && parm_depth > 1)
9902 /* We've been given an incomplete set of template arguments.
9903 For example, given:
9905 template <class T> struct S1 {
9906 template <class U> struct S2 {};
9907 template <class U> struct S2<U*> {};
9910 we will be called with an ARGLIST of `U*', but the
9911 TEMPLATE will be `template <class T> template
9912 <class U> struct S1<T>::S2'. We must fill in the missing
9913 arguments. */
9914 tree ti = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (templ));
9915 arglist = add_outermost_template_args (TI_ARGS (ti), arglist);
9916 arg_depth = TMPL_ARGS_DEPTH (arglist);
9919 /* Now we should have enough arguments. */
9920 gcc_assert (parm_depth == arg_depth);
9922 /* From here on, we're only interested in the most general
9923 template. */
9925 /* Shortcut looking up the current class scope again. */
9926 for (tree cur = current_nonlambda_class_type ();
9927 cur != NULL_TREE;
9928 cur = get_containing_scope (cur))
9930 if (!CLASS_TYPE_P (cur))
9931 continue;
9933 tree ti = CLASSTYPE_TEMPLATE_INFO (cur);
9934 if (!ti || arg_depth > TMPL_ARGS_DEPTH (TI_ARGS (ti)))
9935 break;
9937 if (gen_tmpl == most_general_template (TI_TEMPLATE (ti))
9938 && comp_template_args (arglist, TI_ARGS (ti)))
9939 return cur;
9942 /* Calculate the BOUND_ARGS. These will be the args that are
9943 actually tsubst'd into the definition to create the
9944 instantiation. */
9945 if (PRIMARY_TEMPLATE_P (gen_tmpl))
9946 arglist = coerce_template_parms (parmlist, arglist, gen_tmpl, complain);
9948 if (arglist == error_mark_node)
9949 /* We were unable to bind the arguments. */
9950 return error_mark_node;
9952 /* In the scope of a template class, explicit references to the
9953 template class refer to the type of the template, not any
9954 instantiation of it. For example, in:
9956 template <class T> class C { void f(C<T>); }
9958 the `C<T>' is just the same as `C'. Outside of the
9959 class, however, such a reference is an instantiation. */
9960 if (entering_scope
9961 || !PRIMARY_TEMPLATE_P (gen_tmpl)
9962 || currently_open_class (template_type))
9964 tree tinfo = TYPE_TEMPLATE_INFO (template_type);
9966 if (tinfo && comp_template_args (TI_ARGS (tinfo), arglist))
9967 return template_type;
9970 /* If we already have this specialization, return it. */
9971 elt.tmpl = gen_tmpl;
9972 elt.args = arglist;
9973 elt.spec = NULL_TREE;
9974 hash = spec_hasher::hash (&elt);
9975 entry = type_specializations->find_with_hash (&elt, hash);
9977 if (entry)
9978 return entry->spec;
9980 /* If the template's constraints are not satisfied,
9981 then we cannot form a valid type.
9983 Note that the check is deferred until after the hash
9984 lookup. This prevents redundant checks on previously
9985 instantiated specializations. */
9986 if (flag_concepts
9987 && !DECL_ALIAS_TEMPLATE_P (gen_tmpl)
9988 && !constraints_satisfied_p (gen_tmpl, arglist))
9990 if (complain & tf_error)
9992 auto_diagnostic_group d;
9993 error ("template constraint failure for %qD", gen_tmpl);
9994 diagnose_constraints (input_location, gen_tmpl, arglist);
9996 return error_mark_node;
9999 is_dependent_type = uses_template_parms (arglist);
10001 /* If the deduced arguments are invalid, then the binding
10002 failed. */
10003 if (!is_dependent_type
10004 && check_instantiated_args (gen_tmpl,
10005 INNERMOST_TEMPLATE_ARGS (arglist),
10006 complain))
10007 return error_mark_node;
10009 if (!is_dependent_type
10010 && !PRIMARY_TEMPLATE_P (gen_tmpl)
10011 && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
10012 && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
10013 /* This occurs when the user has tried to define a tagged type
10014 in a scope that forbids it. We emitted an error during the
10015 parse. We didn't complete the bail out then, so here we
10016 are. */
10017 return error_mark_node;
10019 context = DECL_CONTEXT (gen_tmpl);
10020 if (context && TYPE_P (context))
10022 if (!uses_template_parms (DECL_CONTEXT (templ)))
10023 /* If the context of the partially instantiated template is
10024 already non-dependent, then we might as well use it. */
10025 context = DECL_CONTEXT (templ);
10026 else
10028 context = tsubst_aggr_type (context, arglist,
10029 complain, in_decl, true);
10030 /* Try completing the enclosing context if it's not already so. */
10031 if (context != error_mark_node
10032 && !COMPLETE_TYPE_P (context))
10034 context = complete_type (context);
10035 if (COMPLETE_TYPE_P (context))
10037 /* Completion could have caused us to register the desired
10038 specialization already, so check the table again. */
10039 entry = type_specializations->find_with_hash (&elt, hash);
10040 if (entry)
10041 return entry->spec;
10046 else
10047 context = tsubst (context, arglist, complain, in_decl);
10049 if (context == error_mark_node)
10050 return error_mark_node;
10052 if (!context)
10053 context = global_namespace;
10055 /* Create the type. */
10056 if (DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10058 /* The user referred to a specialization of an alias
10059 template represented by GEN_TMPL.
10061 [temp.alias]/2 says:
10063 When a template-id refers to the specialization of an
10064 alias template, it is equivalent to the associated
10065 type obtained by substitution of its
10066 template-arguments for the template-parameters in the
10067 type-id of the alias template. */
10069 t = tsubst (TREE_TYPE (gen_tmpl), arglist, complain, in_decl);
10070 /* Note that the call above (by indirectly calling
10071 register_specialization in tsubst_decl) registers the
10072 TYPE_DECL representing the specialization of the alias
10073 template. So next time someone substitutes ARGLIST for
10074 the template parms into the alias template (GEN_TMPL),
10075 she'll get that TYPE_DECL back. */
10077 if (t == error_mark_node)
10078 return t;
10080 else if (TREE_CODE (template_type) == ENUMERAL_TYPE)
10082 if (!is_dependent_type)
10084 set_current_access_from_decl (TYPE_NAME (template_type));
10085 t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
10086 tsubst (ENUM_UNDERLYING_TYPE (template_type),
10087 arglist, complain, in_decl),
10088 tsubst_attributes (TYPE_ATTRIBUTES (template_type),
10089 arglist, complain, in_decl),
10090 SCOPED_ENUM_P (template_type), NULL);
10092 if (t == error_mark_node)
10093 return t;
10095 else
10097 /* We don't want to call start_enum for this type, since
10098 the values for the enumeration constants may involve
10099 template parameters. And, no one should be interested
10100 in the enumeration constants for such a type. */
10101 t = cxx_make_type (ENUMERAL_TYPE);
10102 SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
10104 SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
10105 ENUM_FIXED_UNDERLYING_TYPE_P (t)
10106 = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
10108 else if (CLASS_TYPE_P (template_type))
10110 /* Lambda closures are regenerated in tsubst_lambda_expr, not
10111 instantiated here. */
10112 gcc_assert (!LAMBDA_TYPE_P (template_type));
10114 t = make_class_type (TREE_CODE (template_type));
10115 CLASSTYPE_DECLARED_CLASS (t)
10116 = CLASSTYPE_DECLARED_CLASS (template_type);
10117 SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
10119 /* A local class. Make sure the decl gets registered properly. */
10120 if (context == current_function_decl)
10121 if (pushtag (DECL_NAME (gen_tmpl), t)
10122 == error_mark_node)
10123 return error_mark_node;
10125 if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
10126 /* This instantiation is another name for the primary
10127 template type. Set the TYPE_CANONICAL field
10128 appropriately. */
10129 TYPE_CANONICAL (t) = template_type;
10130 else if (any_template_arguments_need_structural_equality_p (arglist))
10131 SET_TYPE_STRUCTURAL_EQUALITY (t);
10133 else
10134 gcc_unreachable ();
10136 /* If we called start_enum or pushtag above, this information
10137 will already be set up. */
10138 type_decl = TYPE_NAME (t);
10139 if (!type_decl)
10141 TYPE_CONTEXT (t) = FROB_CONTEXT (context);
10143 type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
10144 DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
10145 DECL_SOURCE_LOCATION (type_decl)
10146 = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
10149 set_instantiating_module (type_decl);
10150 /* Although GEN_TMPL is the TEMPLATE_DECL, it has the same value
10151 of export flag. We want to propagate this because it might
10152 be a friend declaration that pushes a new hidden binding. */
10153 DECL_MODULE_EXPORT_P (type_decl) = DECL_MODULE_EXPORT_P (gen_tmpl);
10155 if (CLASS_TYPE_P (template_type))
10157 TREE_PRIVATE (type_decl)
10158 = TREE_PRIVATE (TYPE_MAIN_DECL (template_type));
10159 TREE_PROTECTED (type_decl)
10160 = TREE_PROTECTED (TYPE_MAIN_DECL (template_type));
10161 if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
10163 DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
10164 DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
10168 if (OVERLOAD_TYPE_P (t)
10169 && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10171 static const char *tags[] = {"abi_tag", "may_alias"};
10173 for (unsigned ix = 0; ix != 2; ix++)
10175 tree attributes
10176 = lookup_attribute (tags[ix], TYPE_ATTRIBUTES (template_type));
10178 if (attributes)
10179 TYPE_ATTRIBUTES (t)
10180 = tree_cons (TREE_PURPOSE (attributes),
10181 TREE_VALUE (attributes),
10182 TYPE_ATTRIBUTES (t));
10186 /* Let's consider the explicit specialization of a member
10187 of a class template specialization that is implicitly instantiated,
10188 e.g.:
10189 template<class T>
10190 struct S
10192 template<class U> struct M {}; //#0
10195 template<>
10196 template<>
10197 struct S<int>::M<char> //#1
10199 int i;
10201 [temp.expl.spec]/4 says this is valid.
10203 In this case, when we write:
10204 S<int>::M<char> m;
10206 M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
10207 the one of #0.
10209 When we encounter #1, we want to store the partial instantiation
10210 of M (template<class T> S<int>::M<T>) in its CLASSTYPE_TI_TEMPLATE.
10212 For all cases other than this "explicit specialization of member of a
10213 class template", we just want to store the most general template into
10214 the CLASSTYPE_TI_TEMPLATE of M.
10216 This case of "explicit specialization of member of a class template"
10217 only happens when:
10218 1/ the enclosing class is an instantiation of, and therefore not
10219 the same as, the context of the most general template, and
10220 2/ we aren't looking at the partial instantiation itself, i.e.
10221 the innermost arguments are not the same as the innermost parms of
10222 the most general template.
10224 So it's only when 1/ and 2/ happens that we want to use the partial
10225 instantiation of the member template in lieu of its most general
10226 template. */
10228 if (PRIMARY_TEMPLATE_P (gen_tmpl)
10229 && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
10230 /* the enclosing class must be an instantiation... */
10231 && CLASS_TYPE_P (context)
10232 && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
10234 TREE_VEC_LENGTH (arglist)--;
10235 ++processing_template_decl;
10236 tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (gen_tmpl));
10237 tree partial_inst_args =
10238 tsubst (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)),
10239 arglist, complain, NULL_TREE);
10240 --processing_template_decl;
10241 TREE_VEC_LENGTH (arglist)++;
10242 if (partial_inst_args == error_mark_node)
10243 return error_mark_node;
10244 use_partial_inst_tmpl =
10245 /*...and we must not be looking at the partial instantiation
10246 itself. */
10247 !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
10248 partial_inst_args);
10251 if (!use_partial_inst_tmpl)
10252 /* This case is easy; there are no member templates involved. */
10253 found = gen_tmpl;
10254 else
10256 /* This is a full instantiation of a member template. Find
10257 the partial instantiation of which this is an instance. */
10259 /* Temporarily reduce by one the number of levels in the ARGLIST
10260 so as to avoid comparing the last set of arguments. */
10261 TREE_VEC_LENGTH (arglist)--;
10262 /* We don't use COMPLAIN in the following call because this isn't
10263 the immediate context of deduction. For instance, tf_partial
10264 could be set here as we might be at the beginning of template
10265 argument deduction when any explicitly specified template
10266 arguments are substituted into the function type. tf_partial
10267 could lead into trouble because we wouldn't find the partial
10268 instantiation that might have been created outside tf_partial
10269 context, because the levels of template parameters wouldn't
10270 match, because in a tf_partial context, tsubst doesn't reduce
10271 TEMPLATE_PARM_LEVEL. */
10272 found = tsubst (gen_tmpl, arglist, tf_none, NULL_TREE);
10273 TREE_VEC_LENGTH (arglist)++;
10274 /* FOUND is either a proper class type, or an alias
10275 template specialization. In the later case, it's a
10276 TYPE_DECL, resulting from the substituting of arguments
10277 for parameters in the TYPE_DECL of the alias template
10278 done earlier. So be careful while getting the template
10279 of FOUND. */
10280 found = (TREE_CODE (found) == TEMPLATE_DECL
10281 ? found
10282 : (TREE_CODE (found) == TYPE_DECL
10283 ? DECL_TI_TEMPLATE (found)
10284 : CLASSTYPE_TI_TEMPLATE (found)));
10286 if (DECL_CLASS_TEMPLATE_P (found)
10287 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (found)))
10289 /* If this partial instantiation is specialized, we want to
10290 use it for hash table lookup. */
10291 elt.tmpl = found;
10292 elt.args = arglist = INNERMOST_TEMPLATE_ARGS (arglist);
10293 hash = spec_hasher::hash (&elt);
10297 /* Build template info for the new specialization. */
10298 SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
10300 elt.spec = t;
10301 slot = type_specializations->find_slot_with_hash (&elt, hash, INSERT);
10302 gcc_checking_assert (*slot == NULL);
10303 entry = ggc_alloc<spec_entry> ();
10304 *entry = elt;
10305 *slot = entry;
10307 /* Note this use of the partial instantiation so we can check it
10308 later in maybe_process_partial_specialization. */
10309 DECL_TEMPLATE_INSTANTIATIONS (found)
10310 = tree_cons (arglist, t,
10311 DECL_TEMPLATE_INSTANTIATIONS (found));
10313 if (TREE_CODE (template_type) == ENUMERAL_TYPE
10314 && !uses_template_parms (current_nonlambda_scope ())
10315 && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10316 /* Now that the type has been registered on the instantiations
10317 list, we set up the enumerators. Because the enumeration
10318 constants may involve the enumeration type itself, we make
10319 sure to register the type first, and then create the
10320 constants. That way, doing tsubst_expr for the enumeration
10321 constants won't result in recursive calls here; we'll find
10322 the instantiation and exit above. */
10323 tsubst_enum (template_type, t, arglist);
10325 if (CLASS_TYPE_P (template_type) && is_dependent_type)
10326 /* If the type makes use of template parameters, the
10327 code that generates debugging information will crash. */
10328 DECL_IGNORED_P (TYPE_MAIN_DECL (t)) = 1;
10330 /* Possibly limit visibility based on template args. */
10331 TREE_PUBLIC (type_decl) = 1;
10332 determine_visibility (type_decl);
10334 inherit_targ_abi_tags (t);
10336 return t;
10340 /* Return a TEMPLATE_ID_EXPR for the given variable template and ARGLIST. */
10342 tree
10343 lookup_template_variable (tree templ, tree arglist, tsubst_flags_t complain)
10345 if (flag_concepts && variable_concept_p (templ))
10346 return build_concept_check (templ, arglist, tf_none);
10348 tree parms = DECL_INNERMOST_TEMPLATE_PARMS (templ);
10349 arglist = coerce_template_parms (parms, arglist, templ, complain);
10350 if (arglist == error_mark_node)
10351 return error_mark_node;
10353 /* The type of the expression is NULL_TREE since the template-id could refer
10354 to an explicit or partial specialization. */
10355 return build2 (TEMPLATE_ID_EXPR, NULL_TREE, templ, arglist);
10358 /* Instantiate a variable declaration from a TEMPLATE_ID_EXPR if it's
10359 not dependent. */
10361 tree
10362 finish_template_variable (tree var, tsubst_flags_t complain)
10364 tree templ = TREE_OPERAND (var, 0);
10365 tree arglist = TREE_OPERAND (var, 1);
10367 /* If the template or arguments are dependent, then we
10368 can't resolve the TEMPLATE_ID_EXPR yet. */
10369 if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (templ)) != 1
10370 || any_dependent_template_arguments_p (arglist))
10371 return var;
10373 if (flag_concepts && !constraints_satisfied_p (templ, arglist))
10375 if (complain & tf_error)
10377 auto_diagnostic_group d;
10378 error ("use of invalid variable template %qE", var);
10379 diagnose_constraints (location_of (var), templ, arglist);
10381 return error_mark_node;
10384 return instantiate_template (templ, arglist, complain);
10387 /* Construct a TEMPLATE_ID_EXPR for the given variable template TEMPL having
10388 TARGS template args, and instantiate it if it's not dependent. */
10390 tree
10391 lookup_and_finish_template_variable (tree templ, tree targs,
10392 tsubst_flags_t complain)
10394 tree var = lookup_template_variable (templ, targs, complain);
10395 if (var == error_mark_node)
10396 return error_mark_node;
10397 /* We may be called while doing a partial substitution, but the
10398 type of the variable template may be auto, in which case we
10399 will call do_auto_deduction in mark_used (which clears tf_partial)
10400 and the auto must be properly reduced at that time for the
10401 deduction to work. */
10402 complain &= ~tf_partial;
10403 var = finish_template_variable (var, complain);
10404 mark_used (var);
10405 return var;
10408 /* If the set of template parameters PARMS contains a template parameter
10409 at the given LEVEL and INDEX, then return this parameter. Otherwise
10410 return NULL_TREE. */
10412 static tree
10413 corresponding_template_parameter_list (tree parms, int level, int index)
10415 while (TMPL_PARMS_DEPTH (parms) > level)
10416 parms = TREE_CHAIN (parms);
10418 if (TMPL_PARMS_DEPTH (parms) != level
10419 || TREE_VEC_LENGTH (TREE_VALUE (parms)) <= index)
10420 return NULL_TREE;
10422 return TREE_VEC_ELT (TREE_VALUE (parms), index);
10425 /* Return the TREE_LIST for the template parameter from PARMS that positionally
10426 corresponds to the template parameter PARM, or else return NULL_TREE. */
10428 static tree
10429 corresponding_template_parameter_list (tree parms, tree parm)
10431 int level, index;
10432 template_parm_level_and_index (parm, &level, &index);
10433 return corresponding_template_parameter_list (parms, level, index);
10436 /* As above, but pull out the actual parameter. */
10438 static tree
10439 corresponding_template_parameter (tree parms, tree parm)
10441 tree list = corresponding_template_parameter_list (parms, parm);
10442 if (!list)
10443 return NULL_TREE;
10445 tree t = TREE_VALUE (list);
10446 /* As in template_parm_to_arg. */
10447 if (TREE_CODE (t) == TYPE_DECL || TREE_CODE (t) == TEMPLATE_DECL)
10448 t = TREE_TYPE (t);
10449 else
10450 t = DECL_INITIAL (t);
10452 gcc_assert (TEMPLATE_PARM_P (t));
10453 return t;
10456 struct pair_fn_data
10458 tree_fn_t fn;
10459 tree_fn_t any_fn;
10460 void *data;
10461 /* True when we should also visit template parameters that occur in
10462 non-deduced contexts. */
10463 bool include_nondeduced_p;
10464 hash_set<tree> *visited;
10467 /* Called from for_each_template_parm via walk_tree. */
10469 static tree
10470 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
10472 tree t = *tp;
10473 struct pair_fn_data *pfd = (struct pair_fn_data *) d;
10474 tree_fn_t fn = pfd->fn;
10475 void *data = pfd->data;
10476 tree result = NULL_TREE;
10478 #define WALK_SUBTREE(NODE) \
10479 do \
10481 result = for_each_template_parm (NODE, fn, data, pfd->visited, \
10482 pfd->include_nondeduced_p, \
10483 pfd->any_fn); \
10484 if (result) goto out; \
10486 while (0)
10488 if (pfd->any_fn && (*pfd->any_fn)(t, data))
10489 return t;
10491 if (TYPE_P (t)
10492 && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE))
10493 WALK_SUBTREE (TYPE_CONTEXT (t));
10495 switch (TREE_CODE (t))
10497 case RECORD_TYPE:
10498 if (TYPE_PTRMEMFUNC_P (t))
10499 break;
10500 /* Fall through. */
10502 case UNION_TYPE:
10503 case ENUMERAL_TYPE:
10504 if (!TYPE_TEMPLATE_INFO (t))
10505 *walk_subtrees = 0;
10506 else
10507 WALK_SUBTREE (TYPE_TI_ARGS (t));
10508 break;
10510 case INTEGER_TYPE:
10511 WALK_SUBTREE (TYPE_MIN_VALUE (t));
10512 WALK_SUBTREE (TYPE_MAX_VALUE (t));
10513 break;
10515 case METHOD_TYPE:
10516 /* Since we're not going to walk subtrees, we have to do this
10517 explicitly here. */
10518 WALK_SUBTREE (TYPE_METHOD_BASETYPE (t));
10519 /* Fall through. */
10521 case FUNCTION_TYPE:
10522 /* Check the return type. */
10523 WALK_SUBTREE (TREE_TYPE (t));
10525 /* Check the parameter types. Since default arguments are not
10526 instantiated until they are needed, the TYPE_ARG_TYPES may
10527 contain expressions that involve template parameters. But,
10528 no-one should be looking at them yet. And, once they're
10529 instantiated, they don't contain template parameters, so
10530 there's no point in looking at them then, either. */
10532 tree parm;
10534 for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
10535 WALK_SUBTREE (TREE_VALUE (parm));
10537 /* Since we've already handled the TYPE_ARG_TYPES, we don't
10538 want walk_tree walking into them itself. */
10539 *walk_subtrees = 0;
10542 if (flag_noexcept_type)
10544 tree spec = TYPE_RAISES_EXCEPTIONS (t);
10545 if (spec)
10546 WALK_SUBTREE (TREE_PURPOSE (spec));
10548 break;
10550 case TYPEOF_TYPE:
10551 case DECLTYPE_TYPE:
10552 if (pfd->include_nondeduced_p
10553 && for_each_template_parm (TYPE_VALUES_RAW (t), fn, data,
10554 pfd->visited,
10555 pfd->include_nondeduced_p,
10556 pfd->any_fn))
10557 return error_mark_node;
10558 *walk_subtrees = false;
10559 break;
10561 case TRAIT_TYPE:
10562 if (pfd->include_nondeduced_p)
10564 WALK_SUBTREE (TRAIT_TYPE_TYPE1 (t));
10565 WALK_SUBTREE (TRAIT_TYPE_TYPE2 (t));
10567 *walk_subtrees = false;
10568 break;
10570 case FUNCTION_DECL:
10571 case VAR_DECL:
10572 if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10573 WALK_SUBTREE (DECL_TI_ARGS (t));
10574 break;
10576 case PARM_DECL:
10577 WALK_SUBTREE (TREE_TYPE (t));
10578 break;
10580 case CONST_DECL:
10581 if (DECL_TEMPLATE_PARM_P (t))
10582 WALK_SUBTREE (DECL_INITIAL (t));
10583 if (DECL_CONTEXT (t)
10584 && pfd->include_nondeduced_p)
10585 WALK_SUBTREE (DECL_CONTEXT (t));
10586 break;
10588 case BOUND_TEMPLATE_TEMPLATE_PARM:
10589 /* Record template parameters such as `T' inside `TT<T>'. */
10590 WALK_SUBTREE (TYPE_TI_ARGS (t));
10591 /* Fall through. */
10593 case TEMPLATE_TEMPLATE_PARM:
10594 case TEMPLATE_TYPE_PARM:
10595 case TEMPLATE_PARM_INDEX:
10596 if (fn && (*fn)(t, data))
10597 return t;
10598 else if (!fn)
10599 return t;
10600 break;
10602 case TEMPLATE_DECL:
10603 /* A template template parameter is encountered. */
10604 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10605 WALK_SUBTREE (TREE_TYPE (t));
10607 /* Already substituted template template parameter */
10608 *walk_subtrees = 0;
10609 break;
10611 case TYPENAME_TYPE:
10612 /* A template-id in a TYPENAME_TYPE might be a deduced context after
10613 partial instantiation. */
10614 WALK_SUBTREE (TYPENAME_TYPE_FULLNAME (t));
10615 *walk_subtrees = 0;
10616 break;
10618 case INDIRECT_REF:
10619 case COMPONENT_REF:
10620 /* If there's no type, then this thing must be some expression
10621 involving template parameters. */
10622 if (!fn && !TREE_TYPE (t))
10623 return error_mark_node;
10624 break;
10626 case CONSTRUCTOR:
10627 case TRAIT_EXPR:
10628 case PLUS_EXPR:
10629 case MULT_EXPR:
10630 case SCOPE_REF:
10631 /* These are non-deduced contexts. */
10632 if (!pfd->include_nondeduced_p)
10633 *walk_subtrees = 0;
10634 break;
10636 case MODOP_EXPR:
10637 case CAST_EXPR:
10638 case IMPLICIT_CONV_EXPR:
10639 case REINTERPRET_CAST_EXPR:
10640 case CONST_CAST_EXPR:
10641 case STATIC_CAST_EXPR:
10642 case DYNAMIC_CAST_EXPR:
10643 case ARROW_EXPR:
10644 case DOTSTAR_EXPR:
10645 case TYPEID_EXPR:
10646 case PSEUDO_DTOR_EXPR:
10647 if (!fn)
10648 return error_mark_node;
10649 break;
10651 default:
10652 break;
10655 #undef WALK_SUBTREE
10657 /* We didn't find any template parameters we liked. */
10658 out:
10659 return result;
10662 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
10663 BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
10664 call FN with the parameter and the DATA.
10665 If FN returns nonzero, the iteration is terminated, and
10666 for_each_template_parm returns 1. Otherwise, the iteration
10667 continues. If FN never returns a nonzero value, the value
10668 returned by for_each_template_parm is 0. If FN is NULL, it is
10669 considered to be the function which always returns 1.
10671 If INCLUDE_NONDEDUCED_P, then this routine will also visit template
10672 parameters that occur in non-deduced contexts. When false, only
10673 visits those template parameters that can be deduced. */
10675 static tree
10676 for_each_template_parm (tree t, tree_fn_t fn, void* data,
10677 hash_set<tree> *visited,
10678 bool include_nondeduced_p,
10679 tree_fn_t any_fn)
10681 struct pair_fn_data pfd;
10682 tree result;
10684 /* Set up. */
10685 pfd.fn = fn;
10686 pfd.any_fn = any_fn;
10687 pfd.data = data;
10688 pfd.include_nondeduced_p = include_nondeduced_p;
10690 /* Walk the tree. (Conceptually, we would like to walk without
10691 duplicates, but for_each_template_parm_r recursively calls
10692 for_each_template_parm, so we would need to reorganize a fair
10693 bit to use walk_tree_without_duplicates, so we keep our own
10694 visited list.) */
10695 if (visited)
10696 pfd.visited = visited;
10697 else
10698 pfd.visited = new hash_set<tree>;
10699 result = cp_walk_tree (&t,
10700 for_each_template_parm_r,
10701 &pfd,
10702 pfd.visited);
10704 /* Clean up. */
10705 if (!visited)
10707 delete pfd.visited;
10708 pfd.visited = 0;
10711 return result;
10714 struct find_template_parameter_info
10716 explicit find_template_parameter_info (tree ctx_parms)
10717 : ctx_parms (ctx_parms),
10718 max_depth (TMPL_PARMS_DEPTH (ctx_parms))
10721 hash_set<tree> visited;
10722 hash_set<tree> parms;
10723 tree parm_list = NULL_TREE;
10724 tree *parm_list_tail = &parm_list;
10725 tree ctx_parms;
10726 int max_depth;
10728 tree find_in (tree);
10729 tree find_in_recursive (tree);
10730 bool found (tree);
10731 unsigned num_found () { return parms.elements (); }
10734 /* Appends the declaration of T to the list in DATA. */
10736 static int
10737 keep_template_parm (tree t, void* data)
10739 find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
10741 /* Template parameters declared within the expression are not part of
10742 the parameter mapping. For example, in this concept:
10744 template<typename T>
10745 concept C = requires { <expr> } -> same_as<int>;
10747 the return specifier same_as<int> declares a new decltype parameter
10748 that must not be part of the parameter mapping. The same is true
10749 for generic lambda parameters, lambda template parameters, etc. */
10750 int level;
10751 int index;
10752 template_parm_level_and_index (t, &level, &index);
10753 if (level == 0 || level > ftpi->max_depth)
10754 return 0;
10756 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
10757 /* We want the underlying TEMPLATE_TEMPLATE_PARM, not the
10758 BOUND_TEMPLATE_TEMPLATE_PARM itself. */
10759 t = TREE_TYPE (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (t));
10761 /* This template parameter might be an argument to a cached dependent
10762 specalization that was formed earlier inside some other template, in
10763 which case the parameter is not among the ones that are in-scope.
10764 Look in CTX_PARMS to find the corresponding in-scope template
10765 parameter, and use it instead. */
10766 if (tree in_scope = corresponding_template_parameter (ftpi->ctx_parms, t))
10767 t = in_scope;
10769 /* Arguments like const T yield parameters like const T. This means that
10770 a template-id like X<T, const T> would yield two distinct parameters:
10771 T and const T. Adjust types to their unqualified versions. */
10772 if (TYPE_P (t))
10773 t = TYPE_MAIN_VARIANT (t);
10774 if (!ftpi->parms.add (t))
10776 /* Append T to PARM_LIST. */
10777 tree node = build_tree_list (NULL_TREE, t);
10778 *ftpi->parm_list_tail = node;
10779 ftpi->parm_list_tail = &TREE_CHAIN (node);
10782 /* Verify the parameter we found has a valid index. */
10783 if (flag_checking)
10785 tree parms = ftpi->ctx_parms;
10786 while (TMPL_PARMS_DEPTH (parms) > level)
10787 parms = TREE_CHAIN (parms);
10788 if (int len = TREE_VEC_LENGTH (TREE_VALUE (parms)))
10789 gcc_assert (index < len);
10792 return 0;
10795 /* Ensure that we recursively examine certain terms that are not normally
10796 visited in for_each_template_parm_r. */
10798 static int
10799 any_template_parm_r (tree t, void *data)
10801 find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
10803 #define WALK_SUBTREE(NODE) \
10804 do \
10806 for_each_template_parm (NODE, keep_template_parm, data, \
10807 &ftpi->visited, true, \
10808 any_template_parm_r); \
10810 while (0)
10812 /* A mention of a member alias/typedef is a use of all of its template
10813 arguments, including those from the enclosing class, so we don't use
10814 alias_template_specialization_p here. */
10815 if (TYPE_P (t) && typedef_variant_p (t))
10816 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
10817 WALK_SUBTREE (TI_ARGS (tinfo));
10819 switch (TREE_CODE (t))
10821 case TEMPLATE_TYPE_PARM:
10822 /* Type constraints of a placeholder type may contain parameters. */
10823 if (is_auto (t))
10824 if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (t))
10825 WALK_SUBTREE (constr);
10826 break;
10828 case TEMPLATE_ID_EXPR:
10829 /* Search through references to variable templates. */
10830 WALK_SUBTREE (TREE_OPERAND (t, 0));
10831 WALK_SUBTREE (TREE_OPERAND (t, 1));
10832 break;
10834 case TEMPLATE_PARM_INDEX:
10835 WALK_SUBTREE (TREE_TYPE (t));
10836 break;
10838 case TEMPLATE_DECL:
10839 /* If T is a member template that shares template parameters with
10840 ctx_parms, we need to mark all those parameters for mapping.
10841 To that end, it should suffice to just walk the DECL_CONTEXT of
10842 the template (assuming the template is not overly general). */
10843 WALK_SUBTREE (DECL_CONTEXT (t));
10844 break;
10846 case LAMBDA_EXPR:
10848 /* Look in the parms and body. */
10849 tree fn = lambda_function (t);
10850 WALK_SUBTREE (TREE_TYPE (fn));
10851 WALK_SUBTREE (DECL_SAVED_TREE (fn));
10853 break;
10855 case IDENTIFIER_NODE:
10856 if (IDENTIFIER_CONV_OP_P (t))
10857 /* The conversion-type-id of a conversion operator may be dependent. */
10858 WALK_SUBTREE (TREE_TYPE (t));
10859 break;
10861 case CONVERT_EXPR:
10862 if (is_dummy_object (t))
10863 WALK_SUBTREE (TREE_TYPE (t));
10864 break;
10866 default:
10867 break;
10870 /* Keep walking. */
10871 return 0;
10874 /* Look through T for template parameters. */
10876 tree
10877 find_template_parameter_info::find_in (tree t)
10879 return for_each_template_parm (t, keep_template_parm, this, &visited,
10880 /*include_nondeduced*/true,
10881 any_template_parm_r);
10884 /* As above, but also recursively look into the default arguments of template
10885 parameters we found. Used for alias CTAD. */
10887 tree
10888 find_template_parameter_info::find_in_recursive (tree t)
10890 if (tree r = find_in (t))
10891 return r;
10892 /* Since newly found parms are added to the end of the list, we
10893 can just walk it until we reach the end. */
10894 for (tree pl = parm_list; pl; pl = TREE_CHAIN (pl))
10896 tree parm = TREE_VALUE (pl);
10897 tree list = corresponding_template_parameter_list (ctx_parms, parm);
10898 if (tree r = find_in (TREE_PURPOSE (list)))
10899 return r;
10901 return NULL_TREE;
10904 /* True if PARM was found by a previous call to find_in. PARM can be a
10905 TREE_LIST, a DECL_TEMPLATE_PARM_P, or a TEMPLATE_PARM_P. */
10907 bool
10908 find_template_parameter_info::found (tree parm)
10910 if (TREE_CODE (parm) == TREE_LIST)
10911 parm = TREE_VALUE (parm);
10912 if (TREE_CODE (parm) == TYPE_DECL)
10913 parm = TREE_TYPE (parm);
10914 else
10915 parm = DECL_INITIAL (parm);
10916 gcc_checking_assert (TEMPLATE_PARM_P (parm));
10917 return parms.contains (parm);
10920 /* Returns a list of unique template parameters found within T, where CTX_PARMS
10921 are the template parameters in scope. */
10923 tree
10924 find_template_parameters (tree t, tree ctx_parms)
10926 if (!ctx_parms)
10927 return NULL_TREE;
10929 find_template_parameter_info ftpi (ctx_parms);
10930 ftpi.find_in (t);
10931 return ftpi.parm_list;
10934 /* Returns true if T depends on any template parameter. */
10936 bool
10937 uses_template_parms (tree t)
10939 if (t == NULL_TREE || t == error_mark_node)
10940 return false;
10942 /* Namespaces can't depend on any template parameters. */
10943 if (TREE_CODE (t) == NAMESPACE_DECL)
10944 return false;
10946 processing_template_decl_sentinel ptds (/*reset*/false);
10947 ++processing_template_decl;
10949 if (TYPE_P (t))
10950 return dependent_type_p (t);
10951 else if (TREE_CODE (t) == TREE_VEC)
10952 return any_dependent_template_arguments_p (t);
10953 else if (TREE_CODE (t) == TREE_LIST)
10954 return (uses_template_parms (TREE_VALUE (t))
10955 || uses_template_parms (TREE_CHAIN (t)));
10956 else if (TREE_CODE (t) == TYPE_DECL)
10957 return dependent_type_p (TREE_TYPE (t));
10958 else
10959 return instantiation_dependent_expression_p (t);
10962 /* Returns true if T depends on any template parameter with level LEVEL. */
10964 bool
10965 uses_template_parms_level (tree t, int level)
10967 return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
10968 /*include_nondeduced_p=*/true);
10971 /* Returns true if the signature of DECL depends on any template parameter from
10972 its enclosing class. */
10974 static bool
10975 uses_outer_template_parms (tree decl)
10977 int depth;
10978 if (DECL_TEMPLATE_TEMPLATE_PARM_P (decl))
10979 depth = TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl)) - 1;
10980 else
10981 depth = template_class_depth (CP_DECL_CONTEXT (decl));
10982 if (depth == 0)
10983 return false;
10984 if (for_each_template_parm (TREE_TYPE (decl), template_parm_outer_level,
10985 &depth, NULL, /*include_nondeduced_p=*/true))
10986 return true;
10987 if (PRIMARY_TEMPLATE_P (decl)
10988 || DECL_TEMPLATE_TEMPLATE_PARM_P (decl))
10990 tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (decl));
10991 for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
10993 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
10994 tree defarg = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
10995 if (TREE_CODE (parm) == PARM_DECL
10996 && for_each_template_parm (TREE_TYPE (parm),
10997 template_parm_outer_level,
10998 &depth, NULL, /*nondeduced*/true))
10999 return true;
11000 if (TREE_CODE (parm) == TEMPLATE_DECL
11001 && uses_outer_template_parms (parm))
11002 return true;
11003 if (defarg
11004 && for_each_template_parm (defarg, template_parm_outer_level,
11005 &depth, NULL, /*nondeduced*/true))
11006 return true;
11009 if (uses_outer_template_parms_in_constraints (decl))
11010 return true;
11011 return false;
11014 /* Returns true if the constraints of DECL depend on any template parameters
11015 from its enclosing scope. */
11017 bool
11018 uses_outer_template_parms_in_constraints (tree decl)
11020 tree ci = get_constraints (decl);
11021 if (ci)
11022 ci = CI_ASSOCIATED_CONSTRAINTS (ci);
11023 if (!ci)
11024 return false;
11025 int depth = template_class_depth (CP_DECL_CONTEXT (decl));
11026 if (depth == 0)
11027 return false;
11028 return for_each_template_parm (ci, template_parm_outer_level,
11029 &depth, NULL, /*nondeduced*/true);
11032 /* Returns TRUE iff INST is an instantiation we don't need to do in an
11033 ill-formed translation unit, i.e. a variable or function that isn't
11034 usable in a constant expression. */
11036 static inline bool
11037 neglectable_inst_p (tree d)
11039 return (d && DECL_P (d)
11040 && !undeduced_auto_decl (d)
11041 && !(TREE_CODE (d) == FUNCTION_DECL
11042 ? FNDECL_MANIFESTLY_CONST_EVALUATED (d)
11043 : decl_maybe_constant_var_p (d)));
11046 /* Returns TRUE iff we should refuse to instantiate DECL because it's
11047 neglectable and instantiated from within an erroneous instantiation. */
11049 static bool
11050 limit_bad_template_recursion (tree decl)
11052 struct tinst_level *lev = current_tinst_level;
11053 int errs = errorcount + sorrycount;
11054 if (errs == 0 || !neglectable_inst_p (decl))
11055 return false;
11057 /* Avoid instantiating members of an ill-formed class. */
11058 bool refuse
11059 = (DECL_CLASS_SCOPE_P (decl)
11060 && CLASSTYPE_ERRONEOUS (DECL_CONTEXT (decl)));
11062 if (!refuse)
11064 for (; lev; lev = lev->next)
11065 if (neglectable_inst_p (lev->maybe_get_node ()))
11066 break;
11067 refuse = (lev && errs > lev->errors);
11070 if (refuse)
11072 /* Don't warn about it not being defined. */
11073 suppress_warning (decl, OPT_Wunused);
11074 tree clone;
11075 FOR_EACH_CLONE (clone, decl)
11076 suppress_warning (clone, OPT_Wunused);
11078 return refuse;
11081 static int tinst_depth;
11082 extern int max_tinst_depth;
11083 int depth_reached;
11085 static GTY(()) struct tinst_level *last_error_tinst_level;
11087 /* We're starting to instantiate D; record the template instantiation context
11088 at LOC for diagnostics and to restore it later. */
11090 bool
11091 push_tinst_level_loc (tree tldcl, tree targs, location_t loc)
11093 struct tinst_level *new_level;
11095 if (tinst_depth >= max_tinst_depth)
11097 /* Tell error.cc not to try to instantiate any templates. */
11098 at_eof = 2;
11099 fatal_error (input_location,
11100 "template instantiation depth exceeds maximum of %d"
11101 " (use %<-ftemplate-depth=%> to increase the maximum)",
11102 max_tinst_depth);
11103 return false;
11106 /* If the current instantiation caused problems, don't let it instantiate
11107 anything else. Do allow deduction substitution and decls usable in
11108 constant expressions. */
11109 if (!targs && limit_bad_template_recursion (tldcl))
11111 /* Avoid no_linkage_errors and unused function (and all other)
11112 warnings for this decl. */
11113 suppress_warning (tldcl);
11114 return false;
11117 /* When not -quiet, dump template instantiations other than functions, since
11118 announce_function will take care of those. */
11119 if (!quiet_flag && !targs
11120 && TREE_CODE (tldcl) != TREE_LIST
11121 && TREE_CODE (tldcl) != FUNCTION_DECL)
11122 fprintf (stderr, " %s", decl_as_string (tldcl, TFF_DECL_SPECIFIERS));
11124 new_level = tinst_level_freelist ().alloc ();
11125 new_level->tldcl = tldcl;
11126 new_level->targs = targs;
11127 new_level->locus = loc;
11128 new_level->errors = errorcount + sorrycount;
11129 new_level->next = NULL;
11130 new_level->refcount = 0;
11131 new_level->path = new_level->visible = nullptr;
11132 set_refcount_ptr (new_level->next, current_tinst_level);
11133 set_refcount_ptr (current_tinst_level, new_level);
11135 ++tinst_depth;
11136 if (GATHER_STATISTICS && (tinst_depth > depth_reached))
11137 depth_reached = tinst_depth;
11139 return true;
11142 /* We're starting substitution of TMPL<ARGS>; record the template
11143 substitution context for diagnostics and to restore it later. */
11145 bool
11146 push_tinst_level (tree tmpl, tree args)
11148 return push_tinst_level_loc (tmpl, args, input_location);
11151 /* We're starting to instantiate D; record INPUT_LOCATION and the
11152 template instantiation context for diagnostics and to restore it
11153 later. */
11155 bool
11156 push_tinst_level (tree d)
11158 return push_tinst_level_loc (d, input_location);
11161 /* Likewise, but record LOC as the program location. */
11163 bool
11164 push_tinst_level_loc (tree d, location_t loc)
11166 gcc_assert (TREE_CODE (d) != TREE_LIST);
11167 return push_tinst_level_loc (d, NULL, loc);
11170 /* We're done instantiating this template; return to the instantiation
11171 context. */
11173 void
11174 pop_tinst_level (void)
11176 /* Restore the filename and line number stashed away when we started
11177 this instantiation. */
11178 input_location = current_tinst_level->locus;
11179 set_refcount_ptr (current_tinst_level, current_tinst_level->next);
11180 --tinst_depth;
11183 /* We're instantiating a deferred template; restore the template
11184 instantiation context in which the instantiation was requested, which
11185 is one step out from LEVEL. Return the corresponding DECL or TYPE. */
11187 static tree
11188 reopen_tinst_level (struct tinst_level *level)
11190 struct tinst_level *t;
11192 tinst_depth = 0;
11193 for (t = level; t; t = t->next)
11194 ++tinst_depth;
11196 set_refcount_ptr (current_tinst_level, level);
11197 pop_tinst_level ();
11198 if (current_tinst_level)
11199 current_tinst_level->errors = errorcount+sorrycount;
11200 return level->maybe_get_node ();
11203 /* Returns the TINST_LEVEL which gives the original instantiation
11204 context. */
11206 struct tinst_level *
11207 outermost_tinst_level (void)
11209 struct tinst_level *level = current_tinst_level;
11210 if (level)
11211 while (level->next)
11212 level = level->next;
11213 return level;
11216 /* True iff T is a friend function declaration that is not itself a template
11217 and is not defined in a class template. */
11219 bool
11220 non_templated_friend_p (tree t)
11222 if (t && TREE_CODE (t) == FUNCTION_DECL
11223 && DECL_UNIQUE_FRIEND_P (t))
11225 tree ti = DECL_TEMPLATE_INFO (t);
11226 if (!ti)
11227 return true;
11228 /* DECL_FRIEND_CONTEXT is set for a friend defined in class. */
11229 if (DECL_FRIEND_CONTEXT (t))
11230 return false;
11231 /* Non-templated friends in a class template are still represented with a
11232 TEMPLATE_DECL; check that its primary template is the befriending
11233 class. Note that DECL_PRIMARY_TEMPLATE is null for
11234 template <class T> friend A<T>::f(); */
11235 tree tmpl = TI_TEMPLATE (ti);
11236 tree primary = DECL_PRIMARY_TEMPLATE (tmpl);
11237 return (primary && primary != tmpl);
11239 else
11240 return false;
11243 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL. ARGS is the
11244 vector of template arguments, as for tsubst.
11246 Returns an appropriate tsubst'd friend declaration. */
11248 static tree
11249 tsubst_friend_function (tree decl, tree args)
11251 tree new_friend;
11253 if (TREE_CODE (decl) == FUNCTION_DECL
11254 && DECL_TEMPLATE_INSTANTIATION (decl)
11255 && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
11256 /* This was a friend declared with an explicit template
11257 argument list, e.g.:
11259 friend void f<>(T);
11261 to indicate that f was a template instantiation, not a new
11262 function declaration. Now, we have to figure out what
11263 instantiation of what template. */
11265 tree template_id, arglist, fns;
11266 tree new_args;
11267 tree tmpl;
11268 tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
11270 /* Friend functions are looked up in the containing namespace scope.
11271 We must enter that scope, to avoid finding member functions of the
11272 current class with same name. */
11273 push_nested_namespace (ns);
11274 fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
11275 tf_warning_or_error, NULL_TREE);
11276 pop_nested_namespace (ns);
11277 arglist = tsubst (DECL_TI_ARGS (decl), args,
11278 tf_warning_or_error, NULL_TREE);
11279 template_id = lookup_template_function (fns, arglist);
11281 new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
11282 tmpl = determine_specialization (template_id, new_friend,
11283 &new_args,
11284 /*need_member_template=*/0,
11285 TREE_VEC_LENGTH (args),
11286 tsk_none);
11287 return instantiate_template (tmpl, new_args, tf_error);
11290 new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
11291 if (new_friend == error_mark_node)
11292 return error_mark_node;
11294 /* The NEW_FRIEND will look like an instantiation, to the
11295 compiler, but is not an instantiation from the point of view of
11296 the language. For example, we might have had:
11298 template <class T> struct S {
11299 template <class U> friend void f(T, U);
11302 Then, in S<int>, template <class U> void f(int, U) is not an
11303 instantiation of anything. */
11305 DECL_USE_TEMPLATE (new_friend) = 0;
11306 if (TREE_CODE (new_friend) == TEMPLATE_DECL)
11308 DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (new_friend) = false;
11309 DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
11310 DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
11311 = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
11313 /* Substitute TEMPLATE_PARMS_CONSTRAINTS so that parameter levels will
11314 match in decls_match. */
11315 tree parms = DECL_TEMPLATE_PARMS (new_friend);
11316 tree treqs = TEMPLATE_PARMS_CONSTRAINTS (parms);
11317 treqs = maybe_substitute_reqs_for (treqs, new_friend);
11318 if (treqs != TEMPLATE_PARMS_CONSTRAINTS (parms))
11320 TEMPLATE_PARMS_CONSTRAINTS (parms) = treqs;
11321 /* As well as each TEMPLATE_PARM_CONSTRAINTS. */
11322 tsubst_each_template_parm_constraints (parms, args,
11323 tf_warning_or_error);
11327 /* The mangled name for the NEW_FRIEND is incorrect. The function
11328 is not a template instantiation and should not be mangled like
11329 one. Therefore, we forget the mangling here; we'll recompute it
11330 later if we need it. */
11331 if (TREE_CODE (new_friend) != TEMPLATE_DECL)
11333 SET_DECL_RTL (new_friend, NULL);
11334 SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
11337 if (DECL_NAMESPACE_SCOPE_P (new_friend))
11339 tree old_decl;
11340 tree ns;
11342 /* We must save some information from NEW_FRIEND before calling
11343 duplicate decls since that function will free NEW_FRIEND if
11344 possible. */
11345 tree new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
11346 tree new_friend_result_template_info = NULL_TREE;
11347 bool new_friend_is_defn =
11348 (new_friend_template_info
11349 && (DECL_INITIAL (DECL_TEMPLATE_RESULT
11350 (template_for_substitution (new_friend)))
11351 != NULL_TREE));
11352 tree not_tmpl = new_friend;
11354 if (TREE_CODE (new_friend) == TEMPLATE_DECL)
11356 /* This declaration is a `primary' template. */
11357 DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
11359 not_tmpl = DECL_TEMPLATE_RESULT (new_friend);
11360 new_friend_result_template_info = DECL_TEMPLATE_INFO (not_tmpl);
11362 else if (!constraints_satisfied_p (new_friend))
11363 /* Only define a constrained hidden friend when satisfied. */
11364 return error_mark_node;
11366 /* Inside pushdecl_namespace_level, we will push into the
11367 current namespace. However, the friend function should go
11368 into the namespace of the template. */
11369 ns = decl_namespace_context (new_friend);
11370 push_nested_namespace (ns);
11371 old_decl = pushdecl_namespace_level (new_friend, /*hiding=*/true);
11372 pop_nested_namespace (ns);
11374 if (old_decl == error_mark_node)
11375 return error_mark_node;
11377 if (old_decl != new_friend)
11379 /* This new friend declaration matched an existing
11380 declaration. For example, given:
11382 template <class T> void f(T);
11383 template <class U> class C {
11384 template <class T> friend void f(T) {}
11387 the friend declaration actually provides the definition
11388 of `f', once C has been instantiated for some type. So,
11389 old_decl will be the out-of-class template declaration,
11390 while new_friend is the in-class definition.
11392 But, if `f' was called before this point, the
11393 instantiation of `f' will have DECL_TI_ARGS corresponding
11394 to `T' but not to `U', references to which might appear
11395 in the definition of `f'. Previously, the most general
11396 template for an instantiation of `f' was the out-of-class
11397 version; now it is the in-class version. Therefore, we
11398 run through all specialization of `f', adding to their
11399 DECL_TI_ARGS appropriately. In particular, they need a
11400 new set of outer arguments, corresponding to the
11401 arguments for this class instantiation.
11403 The same situation can arise with something like this:
11405 friend void f(int);
11406 template <class T> class C {
11407 friend void f(T) {}
11410 when `C<int>' is instantiated. Now, `f(int)' is defined
11411 in the class. */
11413 if (!new_friend_is_defn)
11414 /* On the other hand, if the in-class declaration does
11415 *not* provide a definition, then we don't want to alter
11416 existing definitions. We can just leave everything
11417 alone. */
11419 else
11421 tree new_template = TI_TEMPLATE (new_friend_template_info);
11422 tree new_args = TI_ARGS (new_friend_template_info);
11424 /* Overwrite whatever template info was there before, if
11425 any, with the new template information pertaining to
11426 the declaration. */
11427 DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
11429 if (TREE_CODE (old_decl) != TEMPLATE_DECL)
11431 /* We should have called reregister_specialization in
11432 duplicate_decls. */
11433 gcc_assert (retrieve_specialization (new_template,
11434 new_args, 0)
11435 == old_decl);
11437 /* Instantiate it if the global has already been used. */
11438 if (DECL_ODR_USED (old_decl))
11439 instantiate_decl (old_decl, /*defer_ok=*/true,
11440 /*expl_inst_class_mem_p=*/false);
11442 else
11444 tree t;
11446 /* Indicate that the old function template is a partial
11447 instantiation. */
11448 DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
11449 = new_friend_result_template_info;
11451 gcc_assert (new_template
11452 == most_general_template (new_template));
11453 gcc_assert (new_template != old_decl);
11455 /* Reassign any specializations already in the hash table
11456 to the new more general template, and add the
11457 additional template args. */
11458 for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
11459 t != NULL_TREE;
11460 t = TREE_CHAIN (t))
11462 tree spec = TREE_VALUE (t);
11463 spec_entry elt;
11465 elt.tmpl = old_decl;
11466 elt.args = DECL_TI_ARGS (spec);
11467 elt.spec = NULL_TREE;
11469 decl_specializations->remove_elt (&elt);
11471 DECL_TI_ARGS (spec)
11472 = add_outermost_template_args (new_args,
11473 DECL_TI_ARGS (spec));
11475 register_specialization
11476 (spec, new_template, DECL_TI_ARGS (spec), true, 0);
11479 DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
11483 /* The information from NEW_FRIEND has been merged into OLD_DECL
11484 by duplicate_decls. */
11485 new_friend = old_decl;
11488 /* We've just introduced a namespace-scope function in the purview
11489 without necessarily having opened the enclosing namespace, so
11490 make sure the namespace is in the purview now too. */
11491 if (modules_p ()
11492 && DECL_MODULE_PURVIEW_P (STRIP_TEMPLATE (new_friend))
11493 && TREE_CODE (DECL_CONTEXT (new_friend)) == NAMESPACE_DECL)
11494 DECL_MODULE_PURVIEW_P (DECL_CONTEXT (new_friend)) = true;
11496 else
11498 tree context = DECL_CONTEXT (new_friend);
11499 bool dependent_p;
11501 /* In the code
11502 template <class T> class C {
11503 template <class U> friend void C1<U>::f (); // case 1
11504 friend void C2<T>::f (); // case 2
11506 we only need to make sure CONTEXT is a complete type for
11507 case 2. To distinguish between the two cases, we note that
11508 CONTEXT of case 1 remains dependent type after tsubst while
11509 this isn't true for case 2. */
11510 ++processing_template_decl;
11511 dependent_p = dependent_type_p (context);
11512 --processing_template_decl;
11514 if (!dependent_p
11515 && !complete_type_or_else (context, NULL_TREE))
11516 return error_mark_node;
11518 if (COMPLETE_TYPE_P (context))
11520 tree fn = new_friend;
11521 /* do_friend adds the TEMPLATE_DECL for any member friend
11522 template even if it isn't a member template, i.e.
11523 template <class T> friend A<T>::f();
11524 Look through it in that case. */
11525 if (TREE_CODE (fn) == TEMPLATE_DECL
11526 && !PRIMARY_TEMPLATE_P (fn))
11527 fn = DECL_TEMPLATE_RESULT (fn);
11528 /* Check to see that the declaration is really present, and,
11529 possibly obtain an improved declaration. */
11530 fn = check_classfn (context, fn, NULL_TREE);
11532 if (fn)
11533 new_friend = fn;
11537 return new_friend;
11540 /* FRIEND_TMPL is a friend TEMPLATE_DECL. ARGS is the vector of
11541 template arguments, as for tsubst.
11543 Returns an appropriate tsubst'd friend type or error_mark_node on
11544 failure. */
11546 static tree
11547 tsubst_friend_class (tree friend_tmpl, tree args)
11549 tree tmpl;
11551 if (DECL_TEMPLATE_TEMPLATE_PARM_P (friend_tmpl))
11553 tmpl = tsubst (TREE_TYPE (friend_tmpl), args, tf_none, NULL_TREE);
11554 return TREE_TYPE (tmpl);
11557 tree context = CP_DECL_CONTEXT (friend_tmpl);
11558 if (TREE_CODE (context) == NAMESPACE_DECL)
11559 push_nested_namespace (context);
11560 else
11562 context = tsubst (context, args, tf_error, NULL_TREE);
11563 push_nested_class (context);
11566 tmpl = lookup_name (DECL_NAME (friend_tmpl), LOOK_where::CLASS_NAMESPACE,
11567 LOOK_want::NORMAL | LOOK_want::HIDDEN_FRIEND);
11569 if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
11571 /* The friend template has already been declared. Just
11572 check to see that the declarations match, and install any new
11573 default parameters. We must tsubst the default parameters,
11574 of course. We only need the innermost template parameters
11575 because that is all that redeclare_class_template will look
11576 at. */
11577 if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
11578 > TMPL_ARGS_DEPTH (args))
11580 tree parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
11581 args, tf_warning_or_error);
11582 tsubst_each_template_parm_constraints (parms, args,
11583 tf_warning_or_error);
11584 location_t saved_input_location = input_location;
11585 input_location = DECL_SOURCE_LOCATION (friend_tmpl);
11586 tree cons = get_constraints (friend_tmpl);
11587 ++processing_template_decl;
11588 cons = tsubst_constraint_info (cons, args, tf_warning_or_error,
11589 DECL_FRIEND_CONTEXT (friend_tmpl));
11590 --processing_template_decl;
11591 redeclare_class_template (TREE_TYPE (tmpl), parms, cons);
11592 input_location = saved_input_location;
11595 else
11597 /* The friend template has not already been declared. In this
11598 case, the instantiation of the template class will cause the
11599 injection of this template into the namespace scope. */
11600 tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
11602 if (tmpl != error_mark_node)
11604 /* The new TMPL is not an instantiation of anything, so we
11605 forget its origins. We don't reset CLASSTYPE_TI_TEMPLATE
11606 for the new type because that is supposed to be the
11607 corresponding template decl, i.e., TMPL. */
11608 DECL_USE_TEMPLATE (tmpl) = 0;
11609 DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
11610 CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
11611 CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
11612 = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
11614 /* Substitute into and set the constraints on the new declaration. */
11615 if (tree ci = get_constraints (friend_tmpl))
11617 ++processing_template_decl;
11618 ci = tsubst_constraint_info (ci, args, tf_warning_or_error,
11619 DECL_FRIEND_CONTEXT (friend_tmpl));
11620 --processing_template_decl;
11621 set_constraints (tmpl, ci);
11622 tsubst_each_template_parm_constraints (DECL_TEMPLATE_PARMS (tmpl),
11623 args, tf_warning_or_error);
11626 /* Inject this template into the enclosing namspace scope. */
11627 tmpl = pushdecl_namespace_level (tmpl, /*hiding=*/true);
11631 if (TREE_CODE (context) == NAMESPACE_DECL)
11632 pop_nested_namespace (context);
11633 else
11634 pop_nested_class ();
11636 return TREE_TYPE (tmpl);
11639 /* Returns zero if TYPE cannot be completed later due to circularity.
11640 Otherwise returns one. */
11642 static int
11643 can_complete_type_without_circularity (tree type)
11645 if (type == NULL_TREE || type == error_mark_node)
11646 return 0;
11647 else if (COMPLETE_TYPE_P (type))
11648 return 1;
11649 else if (TREE_CODE (type) == ARRAY_TYPE)
11650 return can_complete_type_without_circularity (TREE_TYPE (type));
11651 else if (CLASS_TYPE_P (type)
11652 && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
11653 return 0;
11654 else
11655 return 1;
11658 static tree tsubst_omp_clauses (tree, enum c_omp_region_type, tree,
11659 tsubst_flags_t, tree);
11661 /* Instantiate the contract statement. */
11663 static tree
11664 tsubst_contract (tree decl, tree t, tree args, tsubst_flags_t complain,
11665 tree in_decl)
11667 tree type = decl ? TREE_TYPE (TREE_TYPE (decl)) : NULL_TREE;
11668 bool auto_p = type_uses_auto (type);
11670 tree r = copy_node (t);
11672 /* Rebuild the result variable. */
11673 if (type && POSTCONDITION_P (t) && POSTCONDITION_IDENTIFIER (t))
11675 tree oldvar = POSTCONDITION_IDENTIFIER (t);
11677 tree newvar = copy_node (oldvar);
11678 TREE_TYPE (newvar) = type;
11679 DECL_CONTEXT (newvar) = decl;
11680 POSTCONDITION_IDENTIFIER (r) = newvar;
11682 /* Make sure the postcondition is valid. */
11683 location_t loc = DECL_SOURCE_LOCATION (oldvar);
11684 if (!auto_p)
11685 if (!check_postcondition_result (decl, type, loc))
11686 return invalidate_contract (r);
11688 /* Make the variable available for lookup. */
11689 register_local_specialization (newvar, oldvar);
11692 /* Instantiate the condition. If the return type is undeduced, process
11693 the expression as if inside a template to avoid spurious type errors. */
11694 if (auto_p)
11695 ++processing_template_decl;
11696 ++processing_contract_condition;
11697 CONTRACT_CONDITION (r)
11698 = tsubst_expr (CONTRACT_CONDITION (t), args, complain, in_decl);
11699 --processing_contract_condition;
11700 if (auto_p)
11701 --processing_template_decl;
11703 /* And the comment. */
11704 CONTRACT_COMMENT (r)
11705 = tsubst_expr (CONTRACT_COMMENT (r), args, complain, in_decl);
11707 return r;
11710 /* Update T by instantiating its contract attribute. */
11712 static void
11713 tsubst_contract_attribute (tree decl, tree t, tree args,
11714 tsubst_flags_t complain, tree in_decl)
11716 /* For non-specializations, adjust the current declaration to the most general
11717 version of in_decl. Because we defer the instantiation of contracts as long
11718 as possible, they are still written in terms of the parameters (and return
11719 type) of the most general template. */
11720 tree tmpl = DECL_TI_TEMPLATE (in_decl);
11721 if (!DECL_TEMPLATE_SPECIALIZATION (tmpl))
11722 in_decl = DECL_TEMPLATE_RESULT (most_general_template (in_decl));
11723 local_specialization_stack specs (lss_copy);
11724 register_parameter_specializations (in_decl, decl);
11726 /* Get the contract to be instantiated. */
11727 tree contract = CONTRACT_STATEMENT (t);
11729 /* Use the complete set of template arguments for instantiation. The
11730 contract may not have been instantiated and still refer to outer levels
11731 of template parameters. */
11732 args = DECL_TI_ARGS (decl);
11734 /* For member functions, make this available for semantic analysis. */
11735 tree save_ccp = current_class_ptr;
11736 tree save_ccr = current_class_ref;
11737 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
11739 tree arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
11740 tree this_type = TREE_TYPE (TREE_VALUE (arg_types));
11741 inject_this_parameter (this_type, cp_type_quals (this_type));
11744 contract = tsubst_contract (decl, contract, args, complain, in_decl);
11746 current_class_ptr = save_ccp;
11747 current_class_ref = save_ccr;
11749 /* Rebuild the attribute. */
11750 TREE_VALUE (t) = build_tree_list (NULL_TREE, contract);
11753 /* Rebuild the attribute list for DECL, substituting into contracts
11754 as needed. */
11756 void
11757 tsubst_contract_attributes (tree decl, tree args, tsubst_flags_t complain, tree in_decl)
11759 tree list = copy_list (DECL_ATTRIBUTES (decl));
11760 for (tree attr = list; attr; attr = CONTRACT_CHAIN (attr))
11762 if (cxx_contract_attribute_p (attr))
11763 tsubst_contract_attribute (decl, attr, args, complain, in_decl);
11765 DECL_ATTRIBUTES (decl) = list;
11768 /* Instantiate a single dependent attribute T (a TREE_LIST), and return either
11769 T or a new TREE_LIST, possibly a chain in the case of a pack expansion. */
11771 static tree
11772 tsubst_attribute (tree t, tree *decl_p, tree args,
11773 tsubst_flags_t complain, tree in_decl)
11775 gcc_assert (ATTR_IS_DEPENDENT (t));
11777 /* Note that contract attributes are never substituted from this function.
11778 Their instantiation is triggered by regenerate_from_template_decl when
11779 we instantiate the body of the function. */
11781 tree val = TREE_VALUE (t);
11782 if (val == NULL_TREE)
11783 /* Nothing to do. */;
11784 else if ((flag_openmp || flag_openmp_simd)
11785 && is_attribute_p ("omp declare simd",
11786 get_attribute_name (t)))
11788 tree clauses = TREE_VALUE (val);
11789 clauses = tsubst_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD, args,
11790 complain, in_decl);
11791 c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
11792 clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
11793 tree parms = DECL_ARGUMENTS (*decl_p);
11794 clauses
11795 = c_omp_declare_simd_clauses_to_numbers (parms, clauses);
11796 if (clauses)
11797 val = build_tree_list (NULL_TREE, clauses);
11798 else
11799 val = NULL_TREE;
11801 else if (flag_openmp
11802 && is_attribute_p ("omp declare variant base",
11803 get_attribute_name (t)))
11805 ++cp_unevaluated_operand;
11806 tree varid = tsubst_expr (TREE_PURPOSE (val), args, complain, in_decl);
11807 --cp_unevaluated_operand;
11808 tree chain = TREE_CHAIN (val);
11809 location_t match_loc = cp_expr_loc_or_input_loc (TREE_PURPOSE (chain));
11810 tree ctx = copy_list (TREE_VALUE (val));
11811 tree simd = get_identifier ("simd");
11812 tree score = get_identifier (" score");
11813 tree condition = get_identifier ("condition");
11814 for (tree t1 = ctx; t1; t1 = TREE_CHAIN (t1))
11816 const char *set = IDENTIFIER_POINTER (TREE_PURPOSE (t1));
11817 TREE_VALUE (t1) = copy_list (TREE_VALUE (t1));
11818 for (tree t2 = TREE_VALUE (t1); t2; t2 = TREE_CHAIN (t2))
11820 if (TREE_PURPOSE (t2) == simd && set[0] == 'c')
11822 tree clauses = TREE_VALUE (t2);
11823 clauses = tsubst_omp_clauses (clauses,
11824 C_ORT_OMP_DECLARE_SIMD, args,
11825 complain, in_decl);
11826 c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
11827 clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
11828 TREE_VALUE (t2) = clauses;
11830 else
11832 TREE_VALUE (t2) = copy_list (TREE_VALUE (t2));
11833 for (tree t3 = TREE_VALUE (t2); t3; t3 = TREE_CHAIN (t3))
11834 if (TREE_VALUE (t3))
11836 bool allow_string
11837 = ((TREE_PURPOSE (t2) != condition || set[0] != 'u')
11838 && TREE_PURPOSE (t3) != score);
11839 tree v = TREE_VALUE (t3);
11840 if (TREE_CODE (v) == STRING_CST && allow_string)
11841 continue;
11842 v = tsubst_expr (v, args, complain, in_decl);
11843 v = fold_non_dependent_expr (v);
11844 if (!INTEGRAL_TYPE_P (TREE_TYPE (v))
11845 || (TREE_PURPOSE (t3) == score
11846 ? TREE_CODE (v) != INTEGER_CST
11847 : !tree_fits_shwi_p (v)))
11849 location_t loc
11850 = cp_expr_loc_or_loc (TREE_VALUE (t3),
11851 match_loc);
11852 if (TREE_PURPOSE (t3) == score)
11853 error_at (loc, "score argument must be "
11854 "constant integer expression");
11855 else if (allow_string)
11856 error_at (loc, "property must be constant "
11857 "integer expression or string "
11858 "literal");
11859 else
11860 error_at (loc, "property must be constant "
11861 "integer expression");
11862 return NULL_TREE;
11864 else if (TREE_PURPOSE (t3) == score
11865 && tree_int_cst_sgn (v) < 0)
11867 location_t loc
11868 = cp_expr_loc_or_loc (TREE_VALUE (t3),
11869 match_loc);
11870 error_at (loc, "score argument must be "
11871 "non-negative");
11872 return NULL_TREE;
11874 TREE_VALUE (t3) = v;
11879 val = tree_cons (varid, ctx, chain);
11881 /* If the first attribute argument is an identifier, don't
11882 pass it through tsubst. Attributes like mode, format,
11883 cleanup and several target specific attributes expect it
11884 unmodified. */
11885 else if (attribute_takes_identifier_p (get_attribute_name (t)))
11887 tree chain
11888 = tsubst_expr (TREE_CHAIN (val), args, complain, in_decl);
11889 if (chain != TREE_CHAIN (val))
11890 val = tree_cons (NULL_TREE, TREE_VALUE (val), chain);
11892 else if (PACK_EXPANSION_P (val))
11894 /* An attribute pack expansion. */
11895 tree purp = TREE_PURPOSE (t);
11896 tree pack = tsubst_pack_expansion (val, args, complain, in_decl);
11897 if (pack == error_mark_node)
11898 return error_mark_node;
11899 int len = TREE_VEC_LENGTH (pack);
11900 tree list = NULL_TREE;
11901 tree *q = &list;
11902 for (int i = 0; i < len; ++i)
11904 tree elt = TREE_VEC_ELT (pack, i);
11905 *q = build_tree_list (purp, elt);
11906 q = &TREE_CHAIN (*q);
11908 return list;
11910 else
11911 val = tsubst_expr (val, args, complain, in_decl);
11913 if (val == error_mark_node)
11914 return error_mark_node;
11915 if (val != TREE_VALUE (t))
11916 return build_tree_list (TREE_PURPOSE (t), val);
11917 return t;
11920 /* Instantiate any dependent attributes in ATTRIBUTES, returning either it
11921 unchanged or a new TREE_LIST chain. */
11923 static tree
11924 tsubst_attributes (tree attributes, tree args,
11925 tsubst_flags_t complain, tree in_decl)
11927 tree last_dep = NULL_TREE;
11929 for (tree t = attributes; t; t = TREE_CHAIN (t))
11930 if (ATTR_IS_DEPENDENT (t))
11932 last_dep = t;
11933 attributes = copy_list (attributes);
11934 break;
11937 if (last_dep)
11938 for (tree *p = &attributes; *p; )
11940 tree t = *p;
11941 if (ATTR_IS_DEPENDENT (t))
11943 tree subst = tsubst_attribute (t, NULL, args, complain, in_decl);
11944 if (subst != t)
11946 *p = subst;
11947 while (*p)
11948 p = &TREE_CHAIN (*p);
11949 *p = TREE_CHAIN (t);
11950 continue;
11953 p = &TREE_CHAIN (*p);
11956 return attributes;
11959 /* Apply any attributes which had to be deferred until instantiation
11960 time. DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
11961 ARGS, COMPLAIN, IN_DECL are as tsubst. Returns true normally,
11962 false on error. */
11964 static bool
11965 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
11966 tree args, tsubst_flags_t complain, tree in_decl)
11968 tree t;
11969 tree *p;
11971 if (attributes == NULL_TREE)
11972 return true;
11974 if (DECL_P (*decl_p))
11976 if (TREE_TYPE (*decl_p) == error_mark_node)
11977 return false;
11978 p = &DECL_ATTRIBUTES (*decl_p);
11979 /* DECL_ATTRIBUTES comes from copy_node in tsubst_decl, and is identical
11980 to our attributes parameter. */
11981 gcc_assert (*p == attributes);
11983 else
11985 p = &TYPE_ATTRIBUTES (*decl_p);
11986 /* TYPE_ATTRIBUTES was set up (with abi_tag and may_alias) in
11987 lookup_template_class_1, and should be preserved. */
11988 gcc_assert (*p != attributes);
11989 while (*p)
11990 p = &TREE_CHAIN (*p);
11993 /* save_template_attributes puts the dependent attributes at the beginning of
11994 the list; find the non-dependent ones. */
11995 for (t = attributes; t; t = TREE_CHAIN (t))
11996 if (!ATTR_IS_DEPENDENT (t))
11997 break;
11998 tree nondep = t;
12000 /* Apply any non-dependent attributes. */
12001 *p = nondep;
12003 if (nondep == attributes)
12004 return true;
12006 /* And then any dependent ones. */
12007 tree late_attrs = NULL_TREE;
12008 tree *q = &late_attrs;
12009 for (t = attributes; t != nondep; t = TREE_CHAIN (t))
12011 *q = tsubst_attribute (t, decl_p, args, complain, in_decl);
12012 if (*q == error_mark_node)
12013 return false;
12014 if (*q == t)
12016 *q = copy_node (t);
12017 TREE_CHAIN (*q) = NULL_TREE;
12019 while (*q)
12020 q = &TREE_CHAIN (*q);
12023 /* cplus_decl_attributes can add some attributes implicitly. For templates,
12024 those attributes should have been added already when those templates were
12025 parsed, and shouldn't be added based on from which context they are
12026 first time instantiated. */
12027 auto o1 = make_temp_override (current_optimize_pragma, NULL_TREE);
12028 auto o2 = make_temp_override (optimization_current_node,
12029 optimization_default_node);
12030 auto o3 = make_temp_override (current_target_pragma, NULL_TREE);
12031 auto o4 = make_temp_override (scope_chain->omp_declare_target_attribute,
12032 NULL);
12033 auto o5 = make_temp_override (scope_chain->omp_begin_assumes, NULL);
12035 cplus_decl_attributes (decl_p, late_attrs, attr_flags);
12037 return true;
12040 /* The template TMPL is being instantiated with the template arguments TARGS.
12041 Perform the access checks that we deferred when parsing the template. */
12043 static void
12044 perform_instantiation_time_access_checks (tree tmpl, tree targs)
12046 unsigned i;
12047 deferred_access_check *chk;
12049 if (!CLASS_TYPE_P (tmpl) && TREE_CODE (tmpl) != FUNCTION_DECL)
12050 return;
12052 if (vec<deferred_access_check, va_gc> *access_checks
12053 = TI_DEFERRED_ACCESS_CHECKS (get_template_info (tmpl)))
12054 FOR_EACH_VEC_ELT (*access_checks, i, chk)
12056 tree decl = chk->decl;
12057 tree diag_decl = chk->diag_decl;
12058 tree type_scope = TREE_TYPE (chk->binfo);
12060 if (uses_template_parms (type_scope))
12061 type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
12063 /* Make access check error messages point to the location
12064 of the use of the typedef. */
12065 iloc_sentinel ils (chk->loc);
12066 perform_or_defer_access_check (TYPE_BINFO (type_scope),
12067 decl, diag_decl, tf_warning_or_error);
12071 tree
12072 instantiate_class_template (tree type)
12074 auto_timevar tv (TV_TEMPLATE_INST);
12076 tree templ, args, pattern, t, member;
12077 tree typedecl;
12078 tree pbinfo;
12079 tree base_list;
12080 unsigned int saved_maximum_field_alignment;
12081 tree fn_context;
12083 if (type == error_mark_node)
12084 return error_mark_node;
12086 if (COMPLETE_OR_OPEN_TYPE_P (type)
12087 || (uses_template_parms (type)
12088 && !TYPE_FUNCTION_SCOPE_P (type)))
12089 return type;
12091 /* Figure out which template is being instantiated. */
12092 templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
12093 gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
12095 /* Mark the type as in the process of being defined. */
12096 TYPE_BEING_DEFINED (type) = 1;
12098 /* We may be in the middle of deferred access check. Disable
12099 it now. */
12100 deferring_access_check_sentinel acs (dk_no_deferred);
12102 /* Determine what specialization of the original template to
12103 instantiate. */
12104 t = most_specialized_partial_spec (type, tf_warning_or_error);
12105 if (t == error_mark_node)
12106 return error_mark_node;
12107 else if (t)
12109 /* This TYPE is actually an instantiation of a partial
12110 specialization. We replace the innermost set of ARGS with
12111 the arguments appropriate for substitution. For example,
12112 given:
12114 template <class T> struct S {};
12115 template <class T> struct S<T*> {};
12117 and supposing that we are instantiating S<int*>, ARGS will
12118 presently be {int*} -- but we need {int}. */
12119 pattern = TREE_TYPE (TI_TEMPLATE (t));
12120 args = TI_ARGS (t);
12122 else
12124 pattern = TREE_TYPE (templ);
12125 args = CLASSTYPE_TI_ARGS (type);
12128 /* If the template we're instantiating is incomplete, then clearly
12129 there's nothing we can do. */
12130 if (!COMPLETE_TYPE_P (pattern))
12132 /* We can try again later. */
12133 TYPE_BEING_DEFINED (type) = 0;
12134 return type;
12137 /* If we've recursively instantiated too many templates, stop. */
12138 if (! push_tinst_level (type))
12139 return type;
12141 int saved_unevaluated_operand = cp_unevaluated_operand;
12142 int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
12144 fn_context = decl_function_context (TYPE_MAIN_DECL (type));
12145 /* Also avoid push_to_top_level for a lambda in an NSDMI. */
12146 if (!fn_context && LAMBDA_TYPE_P (type) && TYPE_CLASS_SCOPE_P (type))
12147 fn_context = error_mark_node;
12148 if (!fn_context)
12149 push_to_top_level ();
12150 else
12152 cp_unevaluated_operand = 0;
12153 c_inhibit_evaluation_warnings = 0;
12156 mark_template_arguments_used (templ, CLASSTYPE_TI_ARGS (type));
12158 /* Use #pragma pack from the template context. */
12159 saved_maximum_field_alignment = maximum_field_alignment;
12160 maximum_field_alignment = TYPE_PRECISION (pattern);
12162 SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
12164 /* Set the input location to the most specialized template definition.
12165 This is needed if tsubsting causes an error. */
12166 typedecl = TYPE_MAIN_DECL (pattern);
12167 input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
12168 DECL_SOURCE_LOCATION (typedecl);
12170 set_instantiating_module (TYPE_NAME (type));
12172 TYPE_PACKED (type) = TYPE_PACKED (pattern);
12173 SET_TYPE_ALIGN (type, TYPE_ALIGN (pattern));
12174 TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
12175 CLASSTYPE_NON_AGGREGATE (type) = CLASSTYPE_NON_AGGREGATE (pattern);
12176 if (ANON_AGGR_TYPE_P (pattern))
12177 SET_ANON_AGGR_TYPE_P (type);
12178 if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
12180 CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
12181 CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
12182 /* Adjust visibility for template arguments. */
12183 determine_visibility (TYPE_MAIN_DECL (type));
12185 if (CLASS_TYPE_P (type))
12186 CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
12188 pbinfo = TYPE_BINFO (pattern);
12190 /* We should never instantiate a nested class before its enclosing
12191 class; we need to look up the nested class by name before we can
12192 instantiate it, and that lookup should instantiate the enclosing
12193 class. */
12194 gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
12195 || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
12197 base_list = NULL_TREE;
12198 /* Defer access checking while we substitute into the types named in
12199 the base-clause. */
12200 push_deferring_access_checks (dk_deferred);
12201 if (BINFO_N_BASE_BINFOS (pbinfo))
12203 tree pbase_binfo;
12204 int i;
12206 /* Substitute into each of the bases to determine the actual
12207 basetypes. */
12208 for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
12210 tree base;
12211 tree access = BINFO_BASE_ACCESS (pbinfo, i);
12212 tree expanded_bases = NULL_TREE;
12213 int idx, len = 1;
12215 if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
12217 expanded_bases =
12218 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
12219 args, tf_error, NULL_TREE);
12220 if (expanded_bases == error_mark_node)
12221 continue;
12223 len = TREE_VEC_LENGTH (expanded_bases);
12226 for (idx = 0; idx < len; idx++)
12228 if (expanded_bases)
12229 /* Extract the already-expanded base class. */
12230 base = TREE_VEC_ELT (expanded_bases, idx);
12231 else
12232 /* Substitute to figure out the base class. */
12233 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error,
12234 NULL_TREE);
12236 if (base == error_mark_node)
12237 continue;
12239 base_list = tree_cons (access, base, base_list);
12240 if (BINFO_VIRTUAL_P (pbase_binfo))
12241 TREE_TYPE (base_list) = integer_type_node;
12245 /* The list is now in reverse order; correct that. */
12246 base_list = nreverse (base_list);
12248 /* Now call xref_basetypes to set up all the base-class
12249 information. */
12250 xref_basetypes (type, base_list);
12252 apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
12253 (int) ATTR_FLAG_TYPE_IN_PLACE,
12254 args, tf_error, NULL_TREE);
12255 fixup_attribute_variants (type);
12257 /* Now that our base classes are set up, enter the scope of the
12258 class, so that name lookups into base classes, etc. will work
12259 correctly. This is precisely analogous to what we do in
12260 begin_class_definition when defining an ordinary non-template
12261 class, except we also need to push the enclosing classes. */
12262 push_nested_class (type);
12264 /* Now check accessibility of the types named in its base-clause,
12265 relative to the scope of the class. */
12266 pop_to_parent_deferring_access_checks ();
12268 /* A vector to hold members marked with attribute used. */
12269 auto_vec<tree> used;
12271 /* Now members are processed in the order of declaration. */
12272 for (member = CLASSTYPE_DECL_LIST (pattern);
12273 member; member = TREE_CHAIN (member))
12275 tree t = TREE_VALUE (member);
12277 if (TREE_PURPOSE (member))
12279 if (TYPE_P (t))
12281 if (LAMBDA_TYPE_P (t))
12282 /* A closure type for a lambda in an NSDMI or default argument.
12283 Ignore it; it will be regenerated when needed. */
12284 continue;
12286 /* If the member is a class template, we've
12287 already substituted its type. */
12288 if (CLASS_TYPE_P (t)
12289 && CLASSTYPE_IS_TEMPLATE (t))
12290 continue;
12292 tree newtag = tsubst (t, args, tf_error, NULL_TREE);
12293 if (newtag == error_mark_node)
12294 continue;
12296 if (TREE_CODE (newtag) != ENUMERAL_TYPE)
12298 tree name = TYPE_IDENTIFIER (t);
12300 /* Now, install the tag. We don't use pushtag
12301 because that does too much work -- creating an
12302 implicit typedef, which we've already done. */
12303 set_identifier_type_value (name, TYPE_NAME (newtag));
12304 maybe_add_class_template_decl_list (type, newtag, false);
12305 TREE_PUBLIC (TYPE_NAME (newtag)) = true;
12306 determine_visibility (TYPE_NAME (newtag));
12309 else if (DECL_DECLARES_FUNCTION_P (t))
12311 tree r;
12313 if (TREE_CODE (t) == TEMPLATE_DECL)
12314 ++processing_template_decl;
12315 r = tsubst (t, args, tf_error, NULL_TREE);
12316 if (TREE_CODE (t) == TEMPLATE_DECL)
12317 --processing_template_decl;
12319 set_current_access_from_decl (r);
12320 finish_member_declaration (r);
12321 /* Instantiate members marked with attribute used. */
12322 if (r != error_mark_node && DECL_PRESERVE_P (r))
12323 used.safe_push (r);
12324 if (TREE_CODE (r) == FUNCTION_DECL
12325 && DECL_OMP_DECLARE_REDUCTION_P (r))
12326 cp_check_omp_declare_reduction (r);
12328 else if ((DECL_CLASS_TEMPLATE_P (t) || DECL_IMPLICIT_TYPEDEF_P (t))
12329 && LAMBDA_TYPE_P (TREE_TYPE (t)))
12330 /* A closure type for a lambda in an NSDMI or default argument.
12331 Ignore it; it will be regenerated when needed. */;
12332 else
12334 /* Build new TYPE_FIELDS. */
12335 if (TREE_CODE (t) == STATIC_ASSERT)
12336 tsubst_expr (t, args, tf_warning_or_error, NULL_TREE);
12337 else if (TREE_CODE (t) != CONST_DECL)
12339 tree r;
12340 tree vec = NULL_TREE;
12341 int len = 1;
12343 gcc_checking_assert (TREE_CODE (t) != CONST_DECL);
12344 /* The file and line for this declaration, to
12345 assist in error message reporting. Since we
12346 called push_tinst_level above, we don't need to
12347 restore these. */
12348 input_location = DECL_SOURCE_LOCATION (t);
12350 if (TREE_CODE (t) == TEMPLATE_DECL)
12351 ++processing_template_decl;
12352 r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
12353 if (TREE_CODE (t) == TEMPLATE_DECL)
12354 --processing_template_decl;
12356 if (TREE_CODE (r) == TREE_VEC)
12358 /* A capture pack became multiple fields. */
12359 vec = r;
12360 len = TREE_VEC_LENGTH (vec);
12363 for (int i = 0; i < len; ++i)
12365 if (vec)
12366 r = TREE_VEC_ELT (vec, i);
12367 if (VAR_P (r))
12369 /* In [temp.inst]:
12371 [t]he initialization (and any associated
12372 side-effects) of a static data member does
12373 not occur unless the static data member is
12374 itself used in a way that requires the
12375 definition of the static data member to
12376 exist.
12378 Therefore, we do not substitute into the
12379 initialized for the static data member here. */
12380 finish_static_data_member_decl
12382 /*init=*/NULL_TREE,
12383 /*init_const_expr_p=*/false,
12384 /*asmspec_tree=*/NULL_TREE,
12385 /*flags=*/0);
12386 /* Instantiate members marked with attribute used. */
12387 if (r != error_mark_node && DECL_PRESERVE_P (r))
12388 used.safe_push (r);
12390 else if (TREE_CODE (r) == FIELD_DECL)
12392 /* Determine whether R has a valid type and can be
12393 completed later. If R is invalid, then its type
12394 is replaced by error_mark_node. */
12395 tree rtype = TREE_TYPE (r);
12396 if (can_complete_type_without_circularity (rtype))
12397 complete_type (rtype);
12399 if (!complete_or_array_type_p (rtype))
12401 /* If R's type couldn't be completed and
12402 it isn't a flexible array member (whose
12403 type is incomplete by definition) give
12404 an error. */
12405 cxx_incomplete_type_error (r, rtype);
12406 TREE_TYPE (r) = error_mark_node;
12408 else if (TREE_CODE (rtype) == ARRAY_TYPE
12409 && TYPE_DOMAIN (rtype) == NULL_TREE
12410 && (TREE_CODE (type) == UNION_TYPE
12411 || TREE_CODE (type) == QUAL_UNION_TYPE))
12413 error ("flexible array member %qD in union", r);
12414 TREE_TYPE (r) = error_mark_node;
12416 else if (!verify_type_context (input_location,
12417 TCTX_FIELD, rtype))
12418 TREE_TYPE (r) = error_mark_node;
12421 /* If it is a TYPE_DECL for a class-scoped
12422 ENUMERAL_TYPE, such a thing will already have
12423 been added to the field list by tsubst_enum
12424 in finish_member_declaration case above. */
12425 if (!(TREE_CODE (r) == TYPE_DECL
12426 && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
12427 && DECL_ARTIFICIAL (r)))
12429 set_current_access_from_decl (r);
12430 finish_member_declaration (r);
12436 else
12438 if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t)
12439 || DECL_TEMPLATE_TEMPLATE_PARM_P (t))
12441 /* Build new CLASSTYPE_FRIEND_CLASSES. */
12443 tree friend_type = t;
12444 if (TREE_CODE (friend_type) == TEMPLATE_DECL)
12446 /* template <class T> friend class C; */
12447 friend_type = tsubst_friend_class (friend_type, args);
12449 else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
12451 /* template <class T> friend class C::D; */
12452 friend_type = tsubst (friend_type, args,
12453 tf_warning_or_error, NULL_TREE);
12454 if (TREE_CODE (friend_type) == TEMPLATE_DECL)
12455 friend_type = TREE_TYPE (friend_type);
12457 else if (TREE_CODE (friend_type) == TYPENAME_TYPE
12458 || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
12460 /* This could be either
12462 friend class T::C;
12464 when dependent_type_p is false or
12466 template <class U> friend class T::C;
12468 otherwise. */
12469 /* Bump processing_template_decl in case this is something like
12470 template <class T> friend struct A<T>::B. */
12471 ++processing_template_decl;
12472 friend_type = tsubst (friend_type, args,
12473 tf_warning_or_error, NULL_TREE);
12474 --processing_template_decl;
12476 else if (uses_template_parms (friend_type))
12477 /* friend class C<T>; */
12478 friend_type = tsubst (friend_type, args,
12479 tf_warning_or_error, NULL_TREE);
12481 /* Otherwise it's
12483 friend class C;
12485 where C is already declared or
12487 friend class C<int>;
12489 We don't have to do anything in these cases. */
12491 if (friend_type != error_mark_node)
12492 make_friend_class (type, friend_type, /*complain=*/false);
12494 else
12496 /* Build new DECL_FRIENDLIST. */
12497 tree r;
12499 /* The file and line for this declaration, to
12500 assist in error message reporting. Since we
12501 called push_tinst_level above, we don't need to
12502 restore these. */
12503 input_location = DECL_SOURCE_LOCATION (t);
12505 if (TREE_CODE (t) == TEMPLATE_DECL)
12507 ++processing_template_decl;
12508 push_deferring_access_checks (dk_no_check);
12511 r = tsubst_friend_function (t, args);
12512 add_friend (type, r, /*complain=*/false);
12513 if (TREE_CODE (t) == TEMPLATE_DECL)
12515 pop_deferring_access_checks ();
12516 --processing_template_decl;
12522 if (fn_context)
12524 /* Restore these before substituting into the lambda capture
12525 initializers. */
12526 cp_unevaluated_operand = saved_unevaluated_operand;
12527 c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
12530 /* Set the file and line number information to whatever is given for
12531 the class itself. This puts error messages involving generated
12532 implicit functions at a predictable point, and the same point
12533 that would be used for non-template classes. */
12534 input_location = DECL_SOURCE_LOCATION (typedecl);
12536 unreverse_member_declarations (type);
12537 finish_struct_1 (type);
12538 TYPE_BEING_DEFINED (type) = 0;
12540 /* Remember if instantiating this class ran into errors, so we can avoid
12541 instantiating member functions in limit_bad_template_recursion. We set
12542 this flag even if the problem was in another instantiation triggered by
12543 this one, as that will likely also cause trouble for member functions. */
12544 if (errorcount + sorrycount > current_tinst_level->errors)
12545 CLASSTYPE_ERRONEOUS (type) = true;
12547 /* We don't instantiate default arguments for member functions. 14.7.1:
12549 The implicit instantiation of a class template specialization causes
12550 the implicit instantiation of the declarations, but not of the
12551 definitions or default arguments, of the class member functions,
12552 member classes, static data members and member templates.... */
12554 perform_instantiation_time_access_checks (pattern, args);
12555 perform_deferred_access_checks (tf_warning_or_error);
12557 /* Now that we've gone through all the members, instantiate those
12558 marked with attribute used. We must do this in the context of
12559 the class -- not the context we pushed from, as that might be
12560 inside a template and change the behaviour of mark_used. */
12561 for (tree x : used)
12562 mark_used (x);
12564 pop_nested_class ();
12565 maximum_field_alignment = saved_maximum_field_alignment;
12566 if (!fn_context)
12567 pop_from_top_level ();
12568 pop_tinst_level ();
12570 /* The vtable for a template class can be emitted in any translation
12571 unit in which the class is instantiated. When there is no key
12572 method, however, finish_struct_1 will already have added TYPE to
12573 the keyed_classes. */
12574 if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
12575 vec_safe_push (keyed_classes, type);
12577 return type;
12580 tree
12581 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12583 tree r;
12585 if (!t)
12586 r = t;
12587 else if (TYPE_P (t))
12588 r = tsubst (t, args, complain, in_decl);
12589 else
12591 if (!(complain & tf_warning))
12592 ++c_inhibit_evaluation_warnings;
12593 r = tsubst_expr (t, args, complain, in_decl);
12594 if (!(complain & tf_warning))
12595 --c_inhibit_evaluation_warnings;
12598 return r;
12601 /* Given a function parameter pack TMPL_PARM and some function parameters
12602 instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
12603 and set *SPEC_P to point at the next point in the list. */
12605 tree
12606 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
12608 /* Collect all of the extra "packed" parameters into an
12609 argument pack. */
12610 tree argpack;
12611 tree spec_parm = *spec_p;
12612 int len;
12614 for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
12615 if (tmpl_parm
12616 && !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
12617 break;
12619 spec_parm = *spec_p;
12620 if (len == 1 && DECL_PACK_P (spec_parm))
12622 /* The instantiation is still a parameter pack; don't wrap it in a
12623 NONTYPE_ARGUMENT_PACK. */
12624 argpack = spec_parm;
12625 spec_parm = DECL_CHAIN (spec_parm);
12627 else
12629 /* Fill in PARMVEC with all of the parameters. */
12630 tree parmvec = make_tree_vec (len);
12631 argpack = make_node (NONTYPE_ARGUMENT_PACK);
12632 for (int i = 0; i < len; i++)
12634 tree elt = spec_parm;
12635 if (DECL_PACK_P (elt))
12636 elt = make_pack_expansion (elt);
12637 TREE_VEC_ELT (parmvec, i) = elt;
12638 spec_parm = DECL_CHAIN (spec_parm);
12641 /* Build the argument packs. */
12642 ARGUMENT_PACK_ARGS (argpack) = parmvec;
12644 *spec_p = spec_parm;
12646 return argpack;
12649 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
12650 NONTYPE_ARGUMENT_PACK. */
12652 static tree
12653 make_fnparm_pack (tree spec_parm)
12655 return extract_fnparm_pack (NULL_TREE, &spec_parm);
12658 /* Return 1 if the Ith element of the argument pack ARG_PACK is a
12659 pack expansion with no extra args, 2 if it has extra args, or 0
12660 if it is not a pack expansion. */
12662 static int
12663 argument_pack_element_is_expansion_p (tree arg_pack, int i)
12665 if (TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
12666 /* We're being called before this happens in tsubst_pack_expansion. */
12667 arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
12668 tree vec = ARGUMENT_PACK_ARGS (arg_pack);
12669 if (i >= TREE_VEC_LENGTH (vec))
12670 return 0;
12671 tree elt = TREE_VEC_ELT (vec, i);
12672 if (DECL_P (elt))
12673 /* A decl pack is itself an expansion. */
12674 elt = TREE_TYPE (elt);
12675 if (!PACK_EXPANSION_P (elt))
12676 return 0;
12677 if (PACK_EXPANSION_EXTRA_ARGS (elt))
12678 return 2;
12679 return 1;
12683 /* Creates and return an ARGUMENT_PACK_SELECT tree node. */
12685 static tree
12686 make_argument_pack_select (tree arg_pack, unsigned index)
12688 tree aps = make_node (ARGUMENT_PACK_SELECT);
12690 ARGUMENT_PACK_SELECT_FROM_PACK (aps) = arg_pack;
12691 ARGUMENT_PACK_SELECT_INDEX (aps) = index;
12693 return aps;
12696 /* This is a subroutine of tsubst_pack_expansion.
12698 It returns TRUE if we need to use the PACK_EXPANSION_EXTRA_ARGS
12699 mechanism to store the (non complete list of) arguments of the
12700 substitution and return a non substituted pack expansion, in order
12701 to wait for when we have enough arguments to really perform the
12702 substitution. */
12704 static bool
12705 use_pack_expansion_extra_args_p (tree t,
12706 tree parm_packs,
12707 int arg_pack_len,
12708 bool has_empty_arg)
12710 if (has_empty_arg
12711 && PACK_EXPANSION_FORCE_EXTRA_ARGS_P (t))
12712 return true;
12714 /* If one pack has an expansion and another pack has a normal
12715 argument or if one pack has an empty argument and an another
12716 one hasn't then tsubst_pack_expansion cannot perform the
12717 substitution and need to fall back on the
12718 PACK_EXPANSION_EXTRA mechanism. */
12719 if (parm_packs == NULL_TREE)
12720 return false;
12721 else if (has_empty_arg)
12723 /* If all the actual packs are pack expansions, we can still
12724 subsitute directly. */
12725 for (tree p = parm_packs; p; p = TREE_CHAIN (p))
12727 tree a = TREE_VALUE (p);
12728 if (TREE_CODE (a) == ARGUMENT_PACK_SELECT)
12729 a = ARGUMENT_PACK_SELECT_FROM_PACK (a);
12730 a = ARGUMENT_PACK_ARGS (a);
12731 if (TREE_VEC_LENGTH (a) == 1)
12732 a = TREE_VEC_ELT (a, 0);
12733 if (PACK_EXPANSION_P (a))
12734 continue;
12735 return true;
12737 return false;
12740 for (int i = 0 ; i < arg_pack_len; ++i)
12742 bool has_expansion_arg = false;
12743 bool has_non_expansion_arg = false;
12744 for (tree parm_pack = parm_packs;
12745 parm_pack;
12746 parm_pack = TREE_CHAIN (parm_pack))
12748 tree arg = TREE_VALUE (parm_pack);
12750 int exp = argument_pack_element_is_expansion_p (arg, i);
12751 if (exp == 2)
12752 /* We can't substitute a pack expansion with extra args into
12753 our pattern. */
12754 return true;
12755 else if (exp)
12756 has_expansion_arg = true;
12757 else
12758 has_non_expansion_arg = true;
12761 if (has_expansion_arg && has_non_expansion_arg)
12763 gcc_checking_assert (false);
12764 return true;
12767 return false;
12770 /* [temp.variadic]/6 says that:
12772 The instantiation of a pack expansion [...]
12773 produces a list E1,E2, ..., En, where N is the number of elements
12774 in the pack expansion parameters.
12776 This subroutine of tsubst_pack_expansion produces one of these Ei.
12778 PATTERN is the pattern of the pack expansion. PARM_PACKS is a
12779 TREE_LIST in which each TREE_PURPOSE is a parameter pack of
12780 PATTERN, and each TREE_VALUE is its corresponding argument pack.
12781 INDEX is the index 'i' of the element Ei to produce. ARGS,
12782 COMPLAIN, and IN_DECL are the same parameters as for the
12783 tsubst_pack_expansion function.
12785 The function returns the resulting Ei upon successful completion,
12786 or error_mark_node.
12788 Note that this function possibly modifies the ARGS parameter, so
12789 it's the responsibility of the caller to restore it. */
12791 static tree
12792 gen_elem_of_pack_expansion_instantiation (tree pattern,
12793 tree parm_packs,
12794 unsigned index,
12795 tree args /* This parm gets
12796 modified. */,
12797 tsubst_flags_t complain,
12798 tree in_decl)
12800 tree t;
12801 bool ith_elem_is_expansion = false;
12803 /* For each parameter pack, change the substitution of the parameter
12804 pack to the ith argument in its argument pack, then expand the
12805 pattern. */
12806 for (tree pack = parm_packs; pack; pack = TREE_CHAIN (pack))
12808 tree parm = TREE_PURPOSE (pack);
12809 tree arg_pack = TREE_VALUE (pack);
12810 tree aps; /* instance of ARGUMENT_PACK_SELECT. */
12812 ith_elem_is_expansion |=
12813 argument_pack_element_is_expansion_p (arg_pack, index);
12815 /* Select the Ith argument from the pack. */
12816 if (TREE_CODE (parm) == PARM_DECL
12817 || VAR_P (parm)
12818 || TREE_CODE (parm) == FIELD_DECL)
12820 if (index == 0)
12822 aps = make_argument_pack_select (arg_pack, index);
12823 if (!mark_used (parm, complain) && !(complain & tf_error))
12824 return error_mark_node;
12825 register_local_specialization (aps, parm);
12827 else
12828 aps = retrieve_local_specialization (parm);
12830 else
12832 int idx, level;
12833 template_parm_level_and_index (parm, &level, &idx);
12835 if (index == 0)
12837 aps = make_argument_pack_select (arg_pack, index);
12838 /* Update the corresponding argument. */
12839 TMPL_ARG (args, level, idx) = aps;
12841 else
12842 /* Re-use the ARGUMENT_PACK_SELECT. */
12843 aps = TMPL_ARG (args, level, idx);
12845 ARGUMENT_PACK_SELECT_INDEX (aps) = index;
12848 /* Substitute into the PATTERN with the (possibly altered)
12849 arguments. */
12850 if (pattern == in_decl)
12851 /* Expanding a fixed parameter pack from
12852 coerce_template_parameter_pack. */
12853 t = tsubst_decl (pattern, args, complain);
12854 else if (pattern == error_mark_node)
12855 t = error_mark_node;
12856 else if (!TYPE_P (pattern))
12857 t = tsubst_expr (pattern, args, complain, in_decl);
12858 else
12860 t = tsubst (pattern, args, complain, in_decl);
12861 if (is_auto (t) && !ith_elem_is_expansion)
12862 /* When expanding the fake auto... pack expansion from add_capture, we
12863 need to mark that the expansion is no longer a pack. */
12864 TEMPLATE_TYPE_PARAMETER_PACK (t) = false;
12867 /* If the Ith argument pack element is a pack expansion, then
12868 the Ith element resulting from the substituting is going to
12869 be a pack expansion as well. */
12870 if (ith_elem_is_expansion)
12871 t = make_pack_expansion (t, complain);
12873 return t;
12876 /* When the unexpanded parameter pack in a fold expression expands to an empty
12877 sequence, the value of the expression is as follows; the program is
12878 ill-formed if the operator is not listed in this table.
12880 && true
12881 || false
12882 , void() */
12884 tree
12885 expand_empty_fold (tree t, tsubst_flags_t complain)
12887 tree_code code = (tree_code)TREE_INT_CST_LOW (TREE_OPERAND (t, 0));
12888 if (!FOLD_EXPR_MODIFY_P (t))
12889 switch (code)
12891 case TRUTH_ANDIF_EXPR:
12892 return boolean_true_node;
12893 case TRUTH_ORIF_EXPR:
12894 return boolean_false_node;
12895 case COMPOUND_EXPR:
12896 return void_node;
12897 default:
12898 break;
12901 if (complain & tf_error)
12902 error_at (location_of (t),
12903 "fold of empty expansion over %O", code);
12904 return error_mark_node;
12907 /* Given a fold-expression T and a current LEFT and RIGHT operand,
12908 form an expression that combines the two terms using the
12909 operator of T. */
12911 static tree
12912 fold_expression (tree t, tree left, tree right, tsubst_flags_t complain)
12914 tree_code code = FOLD_EXPR_OP (t);
12916 tree lookups = templated_operator_saved_lookups (t);
12918 // Handle compound assignment operators.
12919 if (FOLD_EXPR_MODIFY_P (t))
12920 return build_x_modify_expr (input_location, left, code, right,
12921 lookups, complain);
12923 warning_sentinel s(warn_parentheses);
12924 switch (code)
12926 case COMPOUND_EXPR:
12927 return build_x_compound_expr (input_location, left, right,
12928 lookups, complain);
12929 default:
12930 return build_x_binary_op (input_location, code,
12931 left, TREE_CODE (left),
12932 right, TREE_CODE (right),
12933 lookups, /*overload=*/NULL,
12934 complain);
12938 /* Substitute ARGS into the pack of a fold expression T. */
12940 static inline tree
12941 tsubst_fold_expr_pack (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12943 return tsubst_pack_expansion (FOLD_EXPR_PACK (t), args, complain, in_decl);
12946 /* Substitute ARGS into the pack of a fold expression T. */
12948 static inline tree
12949 tsubst_fold_expr_init (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12951 return tsubst_expr (FOLD_EXPR_INIT (t), args, complain, in_decl);
12954 /* Expand a PACK of arguments into a grouped as left fold.
12955 Given a pack containing elements A0, A1, ..., An and an
12956 operator @, this builds the expression:
12958 ((A0 @ A1) @ A2) ... @ An
12960 Note that PACK must not be empty.
12962 The operator is defined by the original fold expression T. */
12964 static tree
12965 expand_left_fold (tree t, tree pack, tsubst_flags_t complain)
12967 tree left = TREE_VEC_ELT (pack, 0);
12968 for (int i = 1; i < TREE_VEC_LENGTH (pack); ++i)
12970 tree right = TREE_VEC_ELT (pack, i);
12971 left = fold_expression (t, left, right, complain);
12973 return left;
12976 /* Substitute into a unary left fold expression. */
12978 static tree
12979 tsubst_unary_left_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 if (PACK_EXPANSION_P (pack))
12987 tree r = copy_node (t);
12988 FOLD_EXPR_PACK (r) = pack;
12989 return r;
12991 if (TREE_VEC_LENGTH (pack) == 0)
12992 return expand_empty_fold (t, complain);
12993 else
12994 return expand_left_fold (t, pack, complain);
12997 /* Substitute into a binary left fold expression.
12999 Do ths by building a single (non-empty) vector of argumnts and
13000 building the expression from those elements. */
13002 static tree
13003 tsubst_binary_left_fold (tree t, tree args, tsubst_flags_t complain,
13004 tree in_decl)
13006 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
13007 if (pack == error_mark_node)
13008 return error_mark_node;
13009 tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
13010 if (init == error_mark_node)
13011 return error_mark_node;
13013 if (PACK_EXPANSION_P (pack))
13015 tree r = copy_node (t);
13016 FOLD_EXPR_PACK (r) = pack;
13017 FOLD_EXPR_INIT (r) = init;
13018 return r;
13021 tree vec = make_tree_vec (TREE_VEC_LENGTH (pack) + 1);
13022 TREE_VEC_ELT (vec, 0) = init;
13023 for (int i = 0; i < TREE_VEC_LENGTH (pack); ++i)
13024 TREE_VEC_ELT (vec, i + 1) = TREE_VEC_ELT (pack, i);
13026 return expand_left_fold (t, vec, complain);
13029 /* Expand a PACK of arguments into a grouped as right fold.
13030 Given a pack containing elementns A0, A1, ..., and an
13031 operator @, this builds the expression:
13033 A0@ ... (An-2 @ (An-1 @ An))
13035 Note that PACK must not be empty.
13037 The operator is defined by the original fold expression T. */
13039 tree
13040 expand_right_fold (tree t, tree pack, tsubst_flags_t complain)
13042 // Build the expression.
13043 int n = TREE_VEC_LENGTH (pack);
13044 tree right = TREE_VEC_ELT (pack, n - 1);
13045 for (--n; n != 0; --n)
13047 tree left = TREE_VEC_ELT (pack, n - 1);
13048 right = fold_expression (t, left, right, complain);
13050 return right;
13053 /* Substitute into a unary right fold expression. */
13055 static tree
13056 tsubst_unary_right_fold (tree t, tree args, tsubst_flags_t complain,
13057 tree in_decl)
13059 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
13060 if (pack == error_mark_node)
13061 return error_mark_node;
13062 if (PACK_EXPANSION_P (pack))
13064 tree r = copy_node (t);
13065 FOLD_EXPR_PACK (r) = pack;
13066 return r;
13068 if (TREE_VEC_LENGTH (pack) == 0)
13069 return expand_empty_fold (t, complain);
13070 else
13071 return expand_right_fold (t, pack, complain);
13074 /* Substitute into a binary right fold expression.
13076 Do ths by building a single (non-empty) vector of arguments and
13077 building the expression from those elements. */
13079 static tree
13080 tsubst_binary_right_fold (tree t, tree args, tsubst_flags_t complain,
13081 tree in_decl)
13083 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
13084 if (pack == error_mark_node)
13085 return error_mark_node;
13086 tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
13087 if (init == error_mark_node)
13088 return error_mark_node;
13090 if (PACK_EXPANSION_P (pack))
13092 tree r = copy_node (t);
13093 FOLD_EXPR_PACK (r) = pack;
13094 FOLD_EXPR_INIT (r) = init;
13095 return r;
13098 int n = TREE_VEC_LENGTH (pack);
13099 tree vec = make_tree_vec (n + 1);
13100 for (int i = 0; i < n; ++i)
13101 TREE_VEC_ELT (vec, i) = TREE_VEC_ELT (pack, i);
13102 TREE_VEC_ELT (vec, n) = init;
13104 return expand_right_fold (t, vec, complain);
13107 /* Walk through the pattern of a pack expansion, adding everything in
13108 local_specializations to a list. */
13110 class el_data
13112 public:
13113 /* Set of variables declared within the pattern. */
13114 hash_set<tree> internal;
13115 /* Set of AST nodes that have been visited by the traversal. */
13116 hash_set<tree> visited;
13117 /* List of local_specializations used within the pattern. */
13118 tree extra;
13119 tsubst_flags_t complain;
13120 /* True iff we don't want to walk into unevaluated contexts. */
13121 bool skip_unevaluated_operands = false;
13122 /* The unevaluated contexts that we avoided walking. */
13123 auto_vec<tree> skipped_trees;
13125 el_data (tsubst_flags_t c)
13126 : extra (NULL_TREE), complain (c) {}
13128 static tree
13129 extract_locals_r (tree *tp, int *walk_subtrees, void *data_)
13131 el_data &data = *reinterpret_cast<el_data*>(data_);
13132 tree *extra = &data.extra;
13133 tsubst_flags_t complain = data.complain;
13135 if (data.skip_unevaluated_operands
13136 && unevaluated_p (TREE_CODE (*tp)))
13138 data.skipped_trees.safe_push (*tp);
13139 *walk_subtrees = 0;
13140 return NULL_TREE;
13143 if (TYPE_P (*tp) && typedef_variant_p (*tp))
13144 /* Remember local typedefs (85214). */
13145 tp = &TYPE_NAME (*tp);
13147 if (TREE_CODE (*tp) == DECL_EXPR)
13149 tree decl = DECL_EXPR_DECL (*tp);
13150 data.internal.add (decl);
13151 if (VAR_P (decl)
13152 && DECL_DECOMPOSITION_P (decl)
13153 && TREE_TYPE (decl) != error_mark_node)
13155 gcc_assert (DECL_NAME (decl) == NULL_TREE);
13156 for (tree decl2 = DECL_CHAIN (decl);
13157 decl2
13158 && VAR_P (decl2)
13159 && DECL_DECOMPOSITION_P (decl2)
13160 && DECL_NAME (decl2)
13161 && TREE_TYPE (decl2) != error_mark_node;
13162 decl2 = DECL_CHAIN (decl2))
13164 gcc_assert (DECL_DECOMP_BASE (decl2) == decl);
13165 data.internal.add (decl2);
13169 else if (TREE_CODE (*tp) == LAMBDA_EXPR)
13171 /* Since we defer implicit capture, look in the parms and body. */
13172 tree fn = lambda_function (*tp);
13173 cp_walk_tree (&TREE_TYPE (fn), &extract_locals_r, &data,
13174 &data.visited);
13175 cp_walk_tree (&DECL_SAVED_TREE (fn), &extract_locals_r, &data,
13176 &data.visited);
13178 else if (tree spec = retrieve_local_specialization (*tp))
13180 if (data.internal.contains (*tp))
13181 /* Don't mess with variables declared within the pattern. */
13182 return NULL_TREE;
13183 if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
13185 /* Maybe pull out the PARM_DECL for a partial instantiation. */
13186 tree args = ARGUMENT_PACK_ARGS (spec);
13187 if (TREE_VEC_LENGTH (args) == 1)
13189 tree elt = TREE_VEC_ELT (args, 0);
13190 if (PACK_EXPANSION_P (elt))
13191 elt = PACK_EXPANSION_PATTERN (elt);
13192 if (DECL_PACK_P (elt))
13193 spec = elt;
13195 if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
13197 /* Handle lambda capture here, since we aren't doing any
13198 substitution now, and so tsubst_copy won't call
13199 process_outer_var_ref. */
13200 tree args = ARGUMENT_PACK_ARGS (spec);
13201 int len = TREE_VEC_LENGTH (args);
13202 for (int i = 0; i < len; ++i)
13204 tree arg = TREE_VEC_ELT (args, i);
13205 tree carg = arg;
13206 if (outer_automatic_var_p (arg))
13207 carg = process_outer_var_ref (arg, complain);
13208 if (carg != arg)
13210 /* Make a new NONTYPE_ARGUMENT_PACK of the capture
13211 proxies. */
13212 if (i == 0)
13214 spec = copy_node (spec);
13215 args = copy_node (args);
13216 ARGUMENT_PACK_ARGS (spec) = args;
13217 register_local_specialization (spec, *tp);
13219 TREE_VEC_ELT (args, i) = carg;
13224 if (outer_automatic_var_p (spec))
13225 spec = process_outer_var_ref (spec, complain);
13226 *extra = tree_cons (*tp, spec, *extra);
13228 return NULL_TREE;
13230 static tree
13231 extract_local_specs (tree pattern, tsubst_flags_t complain)
13233 el_data data (complain);
13234 /* Walk the pattern twice, ignoring unevaluated operands the first time
13235 around, so that if a local specialization appears in both an evaluated
13236 and unevaluated context we prefer to process it in the evaluated context
13237 (since e.g. process_outer_var_ref is a no-op inside an unevaluated
13238 context). */
13239 data.skip_unevaluated_operands = true;
13240 cp_walk_tree (&pattern, extract_locals_r, &data, &data.visited);
13241 /* Now walk the unevaluated contexts we skipped the first time around. */
13242 data.skip_unevaluated_operands = false;
13243 for (tree t : data.skipped_trees)
13245 data.visited.remove (t);
13246 cp_walk_tree (&t, extract_locals_r, &data, &data.visited);
13248 return data.extra;
13251 /* Extract any uses of local_specializations from PATTERN and add them to ARGS
13252 for use in PACK_EXPANSION_EXTRA_ARGS. */
13254 tree
13255 build_extra_args (tree pattern, tree args, tsubst_flags_t complain)
13257 /* Make a copy of the extra arguments so that they won't get changed
13258 out from under us. */
13259 tree extra = preserve_args (copy_template_args (args), /*cow_p=*/false);
13260 if (local_specializations)
13261 if (tree locals = extract_local_specs (pattern, complain))
13262 extra = tree_cons (NULL_TREE, extra, locals);
13263 return extra;
13266 /* Apply any local specializations from PACK_EXPANSION_EXTRA_ARGS and add the
13267 normal template args to ARGS. */
13269 tree
13270 add_extra_args (tree extra, tree args, tsubst_flags_t complain, tree in_decl)
13272 if (extra && TREE_CODE (extra) == TREE_LIST)
13274 for (tree elt = TREE_CHAIN (extra); elt; elt = TREE_CHAIN (elt))
13276 /* The partial instantiation involved local declarations collected in
13277 extract_local_specs; map from the general template to our local
13278 context. */
13279 tree gen = TREE_PURPOSE (elt);
13280 tree inst = TREE_VALUE (elt);
13281 if (DECL_P (inst))
13282 if (tree local = retrieve_local_specialization (inst))
13283 inst = local;
13284 /* else inst is already a full instantiation of the pack. */
13285 register_local_specialization (inst, gen);
13287 gcc_assert (!TREE_PURPOSE (extra));
13288 extra = TREE_VALUE (extra);
13290 if (uses_template_parms (extra))
13292 /* This can happen after dependent substitution into a
13293 requires-expr or a lambda that uses constexpr if. */
13294 extra = tsubst_template_args (extra, args, complain, in_decl);
13295 args = add_outermost_template_args (args, extra);
13297 else
13298 args = add_to_template_args (extra, args);
13299 return args;
13302 /* Substitute ARGS into T, which is an pack expansion
13303 (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
13304 TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
13305 (if only a partial substitution could be performed) or
13306 ERROR_MARK_NODE if there was an error. */
13307 tree
13308 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
13309 tree in_decl)
13311 tree pattern;
13312 tree pack, packs = NULL_TREE;
13313 bool unsubstituted_packs = false;
13314 int i, len = -1;
13315 tree result;
13316 bool need_local_specializations = false;
13317 int levels;
13319 gcc_assert (PACK_EXPANSION_P (t));
13320 pattern = PACK_EXPANSION_PATTERN (t);
13322 /* Add in any args remembered from an earlier partial instantiation. */
13323 args = add_extra_args (PACK_EXPANSION_EXTRA_ARGS (t), args, complain, in_decl);
13325 levels = TMPL_ARGS_DEPTH (args);
13327 /* Determine the argument packs that will instantiate the parameter
13328 packs used in the expansion expression. While we're at it,
13329 compute the number of arguments to be expanded and make sure it
13330 is consistent. */
13331 for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
13332 pack = TREE_CHAIN (pack))
13334 tree parm_pack = TREE_VALUE (pack);
13335 tree arg_pack = NULL_TREE;
13336 tree orig_arg = NULL_TREE;
13337 int level = 0;
13339 if (TREE_CODE (parm_pack) == BASES)
13341 gcc_assert (parm_pack == pattern);
13342 if (BASES_DIRECT (parm_pack))
13343 return calculate_direct_bases (tsubst_expr (BASES_TYPE (parm_pack),
13344 args, complain,
13345 in_decl),
13346 complain);
13347 else
13348 return calculate_bases (tsubst_expr (BASES_TYPE (parm_pack),
13349 args, complain, in_decl),
13350 complain);
13352 else if (builtin_pack_call_p (parm_pack))
13354 if (parm_pack != pattern)
13356 if (complain & tf_error)
13357 sorry ("%qE is not the entire pattern of the pack expansion",
13358 parm_pack);
13359 return error_mark_node;
13361 return expand_builtin_pack_call (parm_pack, args,
13362 complain, in_decl);
13364 else if (TREE_CODE (parm_pack) == PARM_DECL)
13366 /* We know we have correct local_specializations if this
13367 expansion is at function scope, or if we're dealing with a
13368 local parameter in a requires expression; for the latter,
13369 tsubst_requires_expr set it up appropriately. */
13370 if (PACK_EXPANSION_LOCAL_P (t) || CONSTRAINT_VAR_P (parm_pack))
13371 arg_pack = retrieve_local_specialization (parm_pack);
13372 else
13373 /* We can't rely on local_specializations for a parameter
13374 name used later in a function declaration (such as in a
13375 late-specified return type). Even if it exists, it might
13376 have the wrong value for a recursive call. */
13377 need_local_specializations = true;
13379 if (!arg_pack)
13381 /* This parameter pack was used in an unevaluated context. Just
13382 make a dummy decl, since it's only used for its type. */
13383 ++cp_unevaluated_operand;
13384 arg_pack = tsubst_decl (parm_pack, args, complain);
13385 --cp_unevaluated_operand;
13386 if (arg_pack && DECL_PACK_P (arg_pack))
13387 /* Partial instantiation of the parm_pack, we can't build
13388 up an argument pack yet. */
13389 arg_pack = NULL_TREE;
13390 else
13391 arg_pack = make_fnparm_pack (arg_pack);
13393 else if (DECL_PACK_P (arg_pack))
13394 /* This argument pack isn't fully instantiated yet. */
13395 arg_pack = NULL_TREE;
13397 else if (is_capture_proxy (parm_pack))
13399 arg_pack = retrieve_local_specialization (parm_pack);
13400 if (DECL_PACK_P (arg_pack))
13401 arg_pack = NULL_TREE;
13403 else
13405 int idx;
13406 template_parm_level_and_index (parm_pack, &level, &idx);
13407 if (level <= levels)
13408 arg_pack = TMPL_ARG (args, level, idx);
13410 if (arg_pack && TREE_CODE (arg_pack) == TEMPLATE_TYPE_PARM
13411 && TEMPLATE_TYPE_PARAMETER_PACK (arg_pack))
13412 arg_pack = NULL_TREE;
13415 orig_arg = arg_pack;
13416 if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
13417 arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
13419 if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
13420 /* This can only happen if we forget to expand an argument
13421 pack somewhere else. Just return an error, silently. */
13423 result = make_tree_vec (1);
13424 TREE_VEC_ELT (result, 0) = error_mark_node;
13425 return result;
13428 if (arg_pack)
13430 int my_len =
13431 TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
13433 /* Don't bother trying to do a partial substitution with
13434 incomplete packs; we'll try again after deduction. */
13435 if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
13436 return t;
13438 if (len < 0)
13439 len = my_len;
13440 else if (len != my_len)
13442 if (!(complain & tf_error))
13443 /* Fail quietly. */;
13444 else if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
13445 error ("mismatched argument pack lengths while expanding %qT",
13446 pattern);
13447 else
13448 error ("mismatched argument pack lengths while expanding %qE",
13449 pattern);
13450 return error_mark_node;
13453 /* Keep track of the parameter packs and their corresponding
13454 argument packs. */
13455 packs = tree_cons (parm_pack, arg_pack, packs);
13456 TREE_TYPE (packs) = orig_arg;
13458 else
13460 /* We can't substitute for this parameter pack. We use a flag as
13461 well as the missing_level counter because function parameter
13462 packs don't have a level. */
13463 gcc_assert (processing_template_decl || is_auto (parm_pack));
13464 unsubstituted_packs = true;
13468 /* If the expansion is just T..., return the matching argument pack, unless
13469 we need to call convert_from_reference on all the elements. This is an
13470 important optimization; see c++/68422. */
13471 if (!unsubstituted_packs
13472 && TREE_PURPOSE (packs) == pattern)
13474 tree args = ARGUMENT_PACK_ARGS (TREE_VALUE (packs));
13476 /* If the argument pack is a single pack expansion, pull it out. */
13477 if (TREE_VEC_LENGTH (args) == 1
13478 && pack_expansion_args_count (args))
13479 return TREE_VEC_ELT (args, 0);
13481 /* Types need no adjustment, nor does sizeof..., and if we still have
13482 some pack expansion args we won't do anything yet. */
13483 if (TREE_CODE (t) == TYPE_PACK_EXPANSION
13484 || PACK_EXPANSION_SIZEOF_P (t)
13485 || pack_expansion_args_count (args))
13486 return args;
13487 /* Also optimize expression pack expansions if we can tell that the
13488 elements won't have reference type. */
13489 tree type = TREE_TYPE (pattern);
13490 if (type && !TYPE_REF_P (type)
13491 && !PACK_EXPANSION_P (type)
13492 && !WILDCARD_TYPE_P (type))
13493 return args;
13494 /* Otherwise use the normal path so we get convert_from_reference. */
13497 /* We cannot expand this expansion expression, because we don't have
13498 all of the argument packs we need. */
13499 if (use_pack_expansion_extra_args_p (t, packs, len, unsubstituted_packs))
13501 /* We got some full packs, but we can't substitute them in until we
13502 have values for all the packs. So remember these until then. */
13504 t = make_pack_expansion (pattern, complain);
13505 PACK_EXPANSION_EXTRA_ARGS (t)
13506 = build_extra_args (pattern, args, complain);
13507 return t;
13510 /* If NEED_LOCAL_SPECIALIZATIONS then we're in a late-specified return
13511 type, so create our own local specializations map; the current map is
13512 either NULL or (in the case of recursive unification) might have
13513 bindings that we don't want to use or alter. */
13514 local_specialization_stack lss (need_local_specializations
13515 ? lss_blank : lss_nop);
13517 if (unsubstituted_packs)
13519 /* There were no real arguments, we're just replacing a parameter
13520 pack with another version of itself. Substitute into the
13521 pattern and return a PACK_EXPANSION_*. The caller will need to
13522 deal with that. */
13523 if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
13524 result = tsubst_expr (pattern, args, complain, in_decl);
13525 else
13526 result = tsubst (pattern, args, complain, in_decl);
13527 result = make_pack_expansion (result, complain);
13528 PACK_EXPANSION_LOCAL_P (result) = PACK_EXPANSION_LOCAL_P (t);
13529 PACK_EXPANSION_SIZEOF_P (result) = PACK_EXPANSION_SIZEOF_P (t);
13530 if (PACK_EXPANSION_AUTO_P (t))
13532 /* This is a fake auto... pack expansion created in add_capture with
13533 _PACKS that don't appear in the pattern. Copy one over. */
13534 packs = PACK_EXPANSION_PARAMETER_PACKS (t);
13535 pack = retrieve_local_specialization (TREE_VALUE (packs));
13536 gcc_checking_assert (DECL_PACK_P (pack));
13537 PACK_EXPANSION_PARAMETER_PACKS (result)
13538 = build_tree_list (NULL_TREE, pack);
13539 PACK_EXPANSION_AUTO_P (result) = true;
13541 return result;
13544 gcc_assert (len >= 0);
13546 /* For each argument in each argument pack, substitute into the
13547 pattern. */
13548 result = make_tree_vec (len);
13549 tree elem_args = copy_template_args (args);
13550 for (i = 0; i < len; ++i)
13552 t = gen_elem_of_pack_expansion_instantiation (pattern, packs,
13554 elem_args, complain,
13555 in_decl);
13556 TREE_VEC_ELT (result, i) = t;
13557 if (t == error_mark_node)
13559 result = error_mark_node;
13560 break;
13564 /* Update ARGS to restore the substitution from parameter packs to
13565 their argument packs. */
13566 for (pack = packs; pack; pack = TREE_CHAIN (pack))
13568 tree parm = TREE_PURPOSE (pack);
13570 if (TREE_CODE (parm) == PARM_DECL
13571 || VAR_P (parm)
13572 || TREE_CODE (parm) == FIELD_DECL)
13573 register_local_specialization (TREE_TYPE (pack), parm);
13574 else
13576 int idx, level;
13578 if (TREE_VALUE (pack) == NULL_TREE)
13579 continue;
13581 template_parm_level_and_index (parm, &level, &idx);
13583 /* Update the corresponding argument. */
13584 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
13585 TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
13586 TREE_TYPE (pack);
13587 else
13588 TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
13592 /* If the dependent pack arguments were such that we end up with only a
13593 single pack expansion again, there's no need to keep it in a TREE_VEC. */
13594 if (len == 1 && TREE_CODE (result) == TREE_VEC
13595 && PACK_EXPANSION_P (TREE_VEC_ELT (result, 0)))
13596 return TREE_VEC_ELT (result, 0);
13598 return result;
13601 /* Make an argument pack out of the TREE_VEC VEC. */
13603 static tree
13604 make_argument_pack (tree vec)
13606 tree pack;
13608 if (TYPE_P (TREE_VEC_ELT (vec, 0)))
13609 pack = cxx_make_type (TYPE_ARGUMENT_PACK);
13610 else
13612 pack = make_node (NONTYPE_ARGUMENT_PACK);
13613 TREE_CONSTANT (pack) = 1;
13615 ARGUMENT_PACK_ARGS (pack) = vec;
13616 return pack;
13619 /* Return an exact copy of template args T that can be modified
13620 independently. */
13622 static tree
13623 copy_template_args (tree t)
13625 if (t == error_mark_node)
13626 return t;
13628 int len = TREE_VEC_LENGTH (t);
13629 tree new_vec = make_tree_vec (len);
13631 for (int i = 0; i < len; ++i)
13633 tree elt = TREE_VEC_ELT (t, i);
13634 if (elt && TREE_CODE (elt) == TREE_VEC)
13635 elt = copy_template_args (elt);
13636 TREE_VEC_ELT (new_vec, i) = elt;
13639 NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_vec)
13640 = NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
13642 return new_vec;
13645 /* Substitute ARGS into the *_ARGUMENT_PACK orig_arg. */
13647 tree
13648 tsubst_argument_pack (tree orig_arg, tree args, tsubst_flags_t complain,
13649 tree in_decl)
13651 /* This flag is used only during deduction, and we don't expect to
13652 substitute such ARGUMENT_PACKs. */
13653 gcc_assert (!ARGUMENT_PACK_INCOMPLETE_P (orig_arg));
13655 /* Substitute into each of the arguments. */
13656 tree pack_args = tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
13657 args, complain, in_decl);
13658 if (pack_args == error_mark_node)
13659 return error_mark_node;
13661 if (pack_args == ARGUMENT_PACK_ARGS (orig_arg))
13662 return orig_arg;
13664 /* If we're substituting into a generic ARGUMENT_PACK for a variadic
13665 template parameter, we might be able to avoid allocating a new
13666 ARGUMENT_PACK and reuse the corresponding ARGUMENT_PACK from ARGS
13667 if the substituted result is identical to it. */
13668 if (tree parm = template_arg_to_parm (orig_arg))
13670 int level, index;
13671 template_parm_level_and_index (parm, &level, &index);
13672 if (TMPL_ARGS_DEPTH (args) >= level)
13673 if (tree arg = TMPL_ARG (args, level, index))
13674 if (TREE_CODE (arg) == TREE_CODE (orig_arg)
13675 && ARGUMENT_PACK_ARGS (arg) == pack_args)
13677 gcc_assert (!ARGUMENT_PACK_INCOMPLETE_P (arg));
13678 return arg;
13682 tree new_arg;
13683 if (TYPE_P (orig_arg))
13685 new_arg = cxx_make_type (TREE_CODE (orig_arg));
13686 SET_TYPE_STRUCTURAL_EQUALITY (new_arg);
13688 else
13690 new_arg = make_node (TREE_CODE (orig_arg));
13691 TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
13693 ARGUMENT_PACK_ARGS (new_arg) = pack_args;
13694 return new_arg;
13697 /* Substitute ARGS into the vector or list of template arguments T. */
13699 tree
13700 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
13702 if (t == error_mark_node)
13703 return error_mark_node;
13705 /* In "sizeof(X<I>)" we need to evaluate "I". */
13706 cp_evaluated ev;
13708 const int len = TREE_VEC_LENGTH (t);
13709 tree *elts = XALLOCAVEC (tree, len);
13710 int expanded_len_adjust = 0;
13712 /* True iff the substituted result is identical to T. */
13713 bool const_subst_p = true;
13715 for (int i = 0; i < len; i++)
13717 tree orig_arg = TREE_VEC_ELT (t, i);
13718 tree new_arg;
13720 if (!orig_arg)
13721 new_arg = NULL_TREE;
13722 else if (TREE_CODE (orig_arg) == TREE_VEC)
13723 new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
13724 else if (PACK_EXPANSION_P (orig_arg))
13726 /* Substitute into an expansion expression. */
13727 new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
13729 if (TREE_CODE (new_arg) == TREE_VEC)
13730 /* Add to the expanded length adjustment the number of
13731 expanded arguments. We subtract one from this
13732 measurement, because the argument pack expression
13733 itself is already counted as 1 in
13734 LEN. EXPANDED_LEN_ADJUST can actually be negative, if
13735 the argument pack is empty. */
13736 expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
13738 else if (ARGUMENT_PACK_P (orig_arg))
13739 new_arg = tsubst_argument_pack (orig_arg, args, complain, in_decl);
13740 else
13741 new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
13743 if (new_arg == error_mark_node)
13744 return error_mark_node;
13746 elts[i] = new_arg;
13747 if (new_arg != orig_arg)
13748 const_subst_p = false;
13751 if (const_subst_p)
13752 return t;
13754 tree maybe_reuse = NULL_TREE;
13756 /* If ARGS and T are both multi-level, the substituted result may be
13757 identical to ARGS. */
13758 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (t)
13759 && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args)
13760 && TMPL_ARGS_DEPTH (t) == TMPL_ARGS_DEPTH (args))
13761 maybe_reuse = args;
13762 /* If T appears to be a vector of generic template arguments, the
13763 substituted result may be identical to the corresponding level
13764 from ARGS. */
13765 else if (tree parm = template_arg_to_parm (TREE_VEC_ELT (t, 0)))
13767 int level, index;
13768 template_parm_level_and_index (parm, &level, &index);
13769 if (index == 0 && TMPL_ARGS_DEPTH (args) >= level)
13770 maybe_reuse = TMPL_ARGS_LEVEL (args, level);
13773 /* If the substituted result is identical to MAYBE_REUSE, return
13774 it and avoid allocating a new TREE_VEC, as an optimization. */
13775 if (maybe_reuse != NULL_TREE
13776 && TREE_VEC_LENGTH (maybe_reuse) == len
13777 && std::equal (elts, elts+len, TREE_VEC_BEGIN (maybe_reuse)))
13778 return maybe_reuse;
13780 /* If T consists of only a pack expansion for which substitution yielded
13781 a TREE_VEC of the expanded elements, then reuse that TREE_VEC instead
13782 of effectively making a copy. */
13783 if (len == 1
13784 && PACK_EXPANSION_P (TREE_VEC_ELT (t, 0))
13785 && TREE_CODE (elts[0]) == TREE_VEC)
13786 return elts[0];
13788 /* Make space for the expanded arguments coming from template
13789 argument packs. */
13790 tree r = make_tree_vec (len + expanded_len_adjust);
13791 /* T can contain TREE_VECs. That happens if T contains the
13792 arguments for a member template.
13793 In that case each TREE_VEC in T represents a level of template
13794 arguments, and T won't carry any non defaulted argument count.
13795 It will rather be the nested TREE_VECs that will carry one.
13796 In other words, T carries a non defaulted argument count only
13797 if it doesn't contain any nested TREE_VEC. */
13798 if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (t))
13800 int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
13801 count += expanded_len_adjust;
13802 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (r, count);
13805 int out = 0;
13806 for (int i = 0; i < len; i++)
13808 tree orig_arg = TREE_VEC_ELT (t, i);
13809 if (orig_arg
13810 && PACK_EXPANSION_P (orig_arg)
13811 && TREE_CODE (elts[i]) == TREE_VEC)
13813 /* Now expand the template argument pack "in place". */
13814 for (int idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
13815 TREE_VEC_ELT (r, out) = TREE_VEC_ELT (elts[i], idx);
13817 else
13819 TREE_VEC_ELT (r, out) = elts[i];
13820 out++;
13823 gcc_assert (out == TREE_VEC_LENGTH (r));
13825 return r;
13828 /* Substitute ARGS into one level PARMS of template parameters. */
13830 static tree
13831 tsubst_template_parms_level (tree parms, tree args, tsubst_flags_t complain)
13833 if (parms == error_mark_node)
13834 return error_mark_node;
13836 tree new_vec = make_tree_vec (TREE_VEC_LENGTH (parms));
13838 for (int i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
13840 tree tuple = TREE_VEC_ELT (parms, i);
13842 if (tuple == error_mark_node)
13843 continue;
13845 TREE_VEC_ELT (new_vec, i) =
13846 tsubst_template_parm (tuple, args, complain);
13849 return new_vec;
13852 /* Return the result of substituting ARGS into the template parameters
13853 given by PARMS. If there are m levels of ARGS and m + n levels of
13854 PARMS, then the result will contain n levels of PARMS. For
13855 example, if PARMS is `template <class T> template <class U>
13856 template <T*, U, class V>' and ARGS is {{int}, {double}} then the
13857 result will be `template <int*, double, class V>'. */
13859 static tree
13860 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
13862 tree r = NULL_TREE;
13863 tree* new_parms;
13865 /* When substituting into a template, we must set
13866 PROCESSING_TEMPLATE_DECL as the template parameters may be
13867 dependent if they are based on one-another, and the dependency
13868 predicates are short-circuit outside of templates. */
13869 ++processing_template_decl;
13871 for (new_parms = &r;
13872 parms && TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
13873 new_parms = &(TREE_CHAIN (*new_parms)),
13874 parms = TREE_CHAIN (parms))
13876 tree new_vec = tsubst_template_parms_level (TREE_VALUE (parms),
13877 args, complain);
13878 *new_parms =
13879 tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
13880 - TMPL_ARGS_DEPTH (args)),
13881 new_vec, NULL_TREE);
13882 TEMPLATE_PARMS_CONSTRAINTS (*new_parms)
13883 = TEMPLATE_PARMS_CONSTRAINTS (parms);
13886 --processing_template_decl;
13888 return r;
13891 /* Return the result of substituting ARGS into one template parameter
13892 given by T. T Must be a TREE_LIST which TREE_VALUE is the template
13893 parameter and which TREE_PURPOSE is the default argument of the
13894 template parameter. */
13896 static tree
13897 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
13899 tree default_value, parm_decl;
13901 if (args == NULL_TREE
13902 || t == NULL_TREE
13903 || t == error_mark_node)
13904 return t;
13906 gcc_assert (TREE_CODE (t) == TREE_LIST);
13908 default_value = TREE_PURPOSE (t);
13909 parm_decl = TREE_VALUE (t);
13911 parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
13912 if (TREE_CODE (parm_decl) == PARM_DECL
13913 && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
13914 parm_decl = error_mark_node;
13915 default_value = tsubst_template_arg (default_value, args,
13916 complain, NULL_TREE);
13918 tree r = build_tree_list (default_value, parm_decl);
13919 TEMPLATE_PARM_CONSTRAINTS (r) = TEMPLATE_PARM_CONSTRAINTS (t);
13920 return r;
13923 /* Substitute in-place the TEMPLATE_PARM_CONSTRAINTS of each template
13924 parameter in PARMS for sake of declaration matching. */
13926 static void
13927 tsubst_each_template_parm_constraints (tree parms, tree args,
13928 tsubst_flags_t complain)
13930 ++processing_template_decl;
13931 for (; parms; parms = TREE_CHAIN (parms))
13933 tree level = TREE_VALUE (parms);
13934 for (tree parm : tree_vec_range (level))
13935 TEMPLATE_PARM_CONSTRAINTS (parm)
13936 = tsubst_constraint (TEMPLATE_PARM_CONSTRAINTS (parm), args,
13937 complain, NULL_TREE);
13939 --processing_template_decl;
13942 /* Substitute the ARGS into the indicated aggregate (or enumeration)
13943 type T. If T is not an aggregate or enumeration type, it is
13944 handled as if by tsubst. IN_DECL is as for tsubst. If
13945 ENTERING_SCOPE is nonzero, T is the context for a template which
13946 we are presently tsubst'ing. Return the substituted value. */
13948 static tree
13949 tsubst_aggr_type (tree t,
13950 tree args,
13951 tsubst_flags_t complain,
13952 tree in_decl,
13953 int entering_scope)
13955 if (t == NULL_TREE)
13956 return NULL_TREE;
13958 /* Handle typedefs via tsubst so that they get consistently reused. */
13959 if (typedef_variant_p (t))
13961 t = tsubst (t, args, complain, in_decl);
13962 if (t == error_mark_node)
13963 return error_mark_node;
13965 /* The effect of entering_scope is that for a dependent specialization
13966 A<T>, lookup_template_class prefers to return A's primary template
13967 type instead of the implicit instantiation. So when entering_scope,
13968 we mirror this behavior by inspecting TYPE_CANONICAL appropriately,
13969 taking advantage of the fact that lookup_template_class links the two
13970 types by setting TYPE_CANONICAL of the latter to the former. */
13971 if (entering_scope
13972 && CLASS_TYPE_P (t)
13973 && dependent_type_p (t)
13974 && TYPE_CANONICAL (t) == TREE_TYPE (TYPE_TI_TEMPLATE (t)))
13975 t = TYPE_CANONICAL (t);
13977 return t;
13980 switch (TREE_CODE (t))
13982 case RECORD_TYPE:
13983 case ENUMERAL_TYPE:
13984 case UNION_TYPE:
13985 return tsubst_aggr_type_1 (t, args, complain, in_decl, entering_scope);
13987 default:
13988 return tsubst (t, args, complain, in_decl);
13992 /* The part of tsubst_aggr_type that's shared with the RECORD_, UNION_
13993 and ENUMERAL_TYPE cases of tsubst. */
13995 static tree
13996 tsubst_aggr_type_1 (tree t,
13997 tree args,
13998 tsubst_flags_t complain,
13999 tree in_decl,
14000 int entering_scope)
14002 if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
14004 complain &= ~tf_qualifying_scope;
14006 /* Figure out what arguments are appropriate for the
14007 type we are trying to find. For example, given:
14009 template <class T> struct S;
14010 template <class T, class U> void f(T, U) { S<U> su; }
14012 and supposing that we are instantiating f<int, double>,
14013 then our ARGS will be {int, double}, but, when looking up
14014 S we only want {double}. */
14015 tree argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
14016 complain, in_decl);
14017 if (argvec == error_mark_node)
14018 return error_mark_node;
14020 tree r = lookup_template_class (t, argvec, in_decl, NULL_TREE,
14021 entering_scope, complain);
14022 return cp_build_qualified_type (r, cp_type_quals (t), complain);
14024 else
14025 /* This is not a template type, so there's nothing to do. */
14026 return t;
14029 /* Map from a FUNCTION_DECL to a vec of default argument instantiations,
14030 indexed in reverse order of the parameters. */
14032 static GTY((cache)) hash_table<tree_vec_map_cache_hasher> *defarg_inst;
14034 /* Return a reference to the vec* of defarg insts for FN. */
14036 static vec<tree,va_gc> *&
14037 defarg_insts_for (tree fn)
14039 if (!defarg_inst)
14040 defarg_inst = hash_table<tree_vec_map_cache_hasher>::create_ggc (13);
14041 tree_vec_map in = { { fn }, nullptr };
14042 tree_vec_map **slot
14043 = defarg_inst->find_slot_with_hash (&in, DECL_UID (fn), INSERT);
14044 if (!*slot)
14046 *slot = ggc_alloc<tree_vec_map> ();
14047 **slot = in;
14049 return (*slot)->to;
14052 /* Substitute into the default argument ARG (a default argument for
14053 FN), which has the indicated TYPE. */
14055 tree
14056 tsubst_default_argument (tree fn, int parmnum, tree type, tree arg,
14057 tsubst_flags_t complain)
14059 int errs = errorcount + sorrycount;
14061 /* This can happen in invalid code. */
14062 if (TREE_CODE (arg) == DEFERRED_PARSE)
14063 return arg;
14065 /* Shortcut {}. */
14066 if (BRACE_ENCLOSED_INITIALIZER_P (arg)
14067 && CONSTRUCTOR_NELTS (arg) == 0)
14068 return arg;
14070 tree parm = FUNCTION_FIRST_USER_PARM (fn);
14071 parm = chain_index (parmnum, parm);
14072 tree parmtype = TREE_TYPE (parm);
14073 if (DECL_BY_REFERENCE (parm))
14074 parmtype = TREE_TYPE (parmtype);
14075 if (parmtype == error_mark_node)
14076 return error_mark_node;
14078 gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, parmtype));
14080 /* Remember the location of the pointer to the vec rather than the location
14081 of the particular element, in case the vec grows in tsubst_expr. */
14082 vec<tree,va_gc> *&defs = defarg_insts_for (fn);
14083 /* Index in reverse order to avoid allocating space for initial parameters
14084 that don't have default arguments. */
14085 unsigned ridx = list_length (parm);
14086 if (vec_safe_length (defs) < ridx)
14087 vec_safe_grow_cleared (defs, ridx);
14088 else if (tree inst = (*defs)[ridx - 1])
14089 return inst;
14091 /* This default argument came from a template. Instantiate the
14092 default argument here, not in tsubst. In the case of
14093 something like:
14095 template <class T>
14096 struct S {
14097 static T t();
14098 void f(T = t());
14101 we must be careful to do name lookup in the scope of S<T>,
14102 rather than in the current class. */
14103 push_to_top_level ();
14104 push_access_scope (fn);
14105 push_deferring_access_checks (dk_no_deferred);
14106 /* So in_immediate_context knows this is a default argument. */
14107 begin_scope (sk_function_parms, fn);
14108 start_lambda_scope (parm);
14110 /* The default argument expression may cause implicitly defined
14111 member functions to be synthesized, which will result in garbage
14112 collection. We must treat this situation as if we were within
14113 the body of function so as to avoid collecting live data on the
14114 stack. */
14115 ++function_depth;
14116 arg = tsubst_expr (arg, DECL_TI_ARGS (fn), complain, NULL_TREE);
14117 --function_depth;
14119 finish_lambda_scope ();
14121 /* Make sure the default argument is reasonable. */
14122 arg = check_default_argument (type, arg, complain);
14124 if (errorcount+sorrycount > errs
14125 && (complain & tf_warning_or_error))
14126 inform (input_location,
14127 " when instantiating default argument for call to %qD", fn);
14129 leave_scope ();
14130 pop_deferring_access_checks ();
14131 pop_access_scope (fn);
14132 pop_from_top_level ();
14134 if (arg != error_mark_node && !cp_unevaluated_operand)
14135 (*defs)[ridx - 1] = arg;
14137 return arg;
14140 /* Substitute into all the default arguments for FN. */
14142 static void
14143 tsubst_default_arguments (tree fn, tsubst_flags_t complain)
14145 tree arg;
14146 tree tmpl_args;
14148 tmpl_args = DECL_TI_ARGS (fn);
14150 /* If this function is not yet instantiated, we certainly don't need
14151 its default arguments. */
14152 if (uses_template_parms (tmpl_args))
14153 return;
14154 /* Don't do this again for clones. */
14155 if (DECL_CLONED_FUNCTION_P (fn))
14156 return;
14158 int i = 0;
14159 for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
14160 arg;
14161 arg = TREE_CHAIN (arg), ++i)
14162 if (TREE_PURPOSE (arg))
14163 TREE_PURPOSE (arg) = tsubst_default_argument (fn, i,
14164 TREE_VALUE (arg),
14165 TREE_PURPOSE (arg),
14166 complain);
14169 /* Hash table mapping a FUNCTION_DECL to its dependent explicit-specifier. */
14170 static GTY((cache)) decl_tree_cache_map *explicit_specifier_map;
14172 /* Store a pair to EXPLICIT_SPECIFIER_MAP. */
14174 void
14175 store_explicit_specifier (tree v, tree t)
14177 if (!explicit_specifier_map)
14178 explicit_specifier_map = decl_tree_cache_map::create_ggc (37);
14179 DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (v) = true;
14180 explicit_specifier_map->put (v, t);
14183 /* Lookup an element in EXPLICIT_SPECIFIER_MAP. */
14185 tree
14186 lookup_explicit_specifier (tree v)
14188 return *explicit_specifier_map->get (v);
14191 /* Given T, a FUNCTION_TYPE or METHOD_TYPE, construct and return a corresponding
14192 FUNCTION_TYPE or METHOD_TYPE whose return type is RETURN_TYPE, argument types
14193 are ARG_TYPES, and exception specification is RAISES, and otherwise is
14194 identical to T. */
14196 static tree
14197 rebuild_function_or_method_type (tree t, tree return_type, tree arg_types,
14198 tree raises, tsubst_flags_t complain)
14200 gcc_assert (FUNC_OR_METHOD_TYPE_P (t));
14202 tree new_type;
14203 if (TREE_CODE (t) == FUNCTION_TYPE)
14205 new_type = build_function_type (return_type, arg_types);
14206 new_type = apply_memfn_quals (new_type, type_memfn_quals (t));
14208 else
14210 tree r = TREE_TYPE (TREE_VALUE (arg_types));
14211 /* Don't pick up extra function qualifiers from the basetype. */
14212 r = cp_build_qualified_type (r, type_memfn_quals (t), complain);
14213 if (! MAYBE_CLASS_TYPE_P (r))
14215 /* [temp.deduct]
14217 Type deduction may fail for any of the following
14218 reasons:
14220 -- Attempting to create "pointer to member of T" when T
14221 is not a class type. */
14222 if (complain & tf_error)
14223 error ("creating pointer to member function of non-class type %qT",
14225 return error_mark_node;
14228 new_type = build_method_type_directly (r, return_type,
14229 TREE_CHAIN (arg_types));
14231 new_type = cp_build_type_attribute_variant (new_type, TYPE_ATTRIBUTES (t));
14233 cp_ref_qualifier rqual = type_memfn_rqual (t);
14234 bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
14235 return build_cp_fntype_variant (new_type, rqual, raises, late_return_type_p);
14238 /* Check if the function type of DECL, a FUNCTION_DECL, agrees with the type of
14239 each of its formal parameters. If there is a disagreement then rebuild
14240 DECL's function type according to its formal parameter types, as part of a
14241 resolution for Core issues 1001/1322. */
14243 static void
14244 maybe_rebuild_function_decl_type (tree decl)
14246 bool function_type_needs_rebuilding = false;
14247 if (tree parm_list = FUNCTION_FIRST_USER_PARM (decl))
14249 tree parm_type_list = FUNCTION_FIRST_USER_PARMTYPE (decl);
14250 while (parm_type_list && parm_type_list != void_list_node)
14252 tree parm_type = TREE_VALUE (parm_type_list);
14253 tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
14254 if (!same_type_p (parm_type, formal_parm_type_unqual))
14256 function_type_needs_rebuilding = true;
14257 break;
14260 parm_list = DECL_CHAIN (parm_list);
14261 parm_type_list = TREE_CHAIN (parm_type_list);
14265 if (!function_type_needs_rebuilding)
14266 return;
14268 const tree fntype = TREE_TYPE (decl);
14269 tree parm_list = DECL_ARGUMENTS (decl);
14270 tree old_parm_type_list = TYPE_ARG_TYPES (fntype);
14271 tree new_parm_type_list = NULL_TREE;
14272 tree *q = &new_parm_type_list;
14273 for (int skip = num_artificial_parms_for (decl); skip > 0; skip--)
14275 *q = copy_node (old_parm_type_list);
14276 parm_list = DECL_CHAIN (parm_list);
14277 old_parm_type_list = TREE_CHAIN (old_parm_type_list);
14278 q = &TREE_CHAIN (*q);
14280 while (old_parm_type_list && old_parm_type_list != void_list_node)
14282 *q = copy_node (old_parm_type_list);
14283 tree *new_parm_type = &TREE_VALUE (*q);
14284 tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
14285 if (!same_type_p (*new_parm_type, formal_parm_type_unqual))
14286 *new_parm_type = formal_parm_type_unqual;
14288 parm_list = DECL_CHAIN (parm_list);
14289 old_parm_type_list = TREE_CHAIN (old_parm_type_list);
14290 q = &TREE_CHAIN (*q);
14292 if (old_parm_type_list == void_list_node)
14293 *q = void_list_node;
14295 TREE_TYPE (decl)
14296 = rebuild_function_or_method_type (fntype,
14297 TREE_TYPE (fntype), new_parm_type_list,
14298 TYPE_RAISES_EXCEPTIONS (fntype), tf_none);
14301 /* Subroutine of tsubst_decl for the case when T is a FUNCTION_DECL. */
14303 static tree
14304 tsubst_function_decl (tree t, tree args, tsubst_flags_t complain,
14305 tree lambda_fntype)
14307 tree gen_tmpl = NULL_TREE, argvec = NULL_TREE;
14308 hashval_t hash = 0;
14309 tree in_decl = t;
14311 /* Nobody should be tsubst'ing into non-template functions. */
14312 gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE
14313 || DECL_LOCAL_DECL_P (t));
14315 if (DECL_LOCAL_DECL_P (t))
14317 if (tree spec = retrieve_local_specialization (t))
14318 return spec;
14320 else if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
14322 /* If T is not dependent, just return it. */
14323 if (!uses_template_parms (DECL_TI_ARGS (t))
14324 && !LAMBDA_FUNCTION_P (t))
14325 return t;
14327 /* A non-templated friend doesn't get DECL_TEMPLATE_INFO. */
14328 if (non_templated_friend_p (t))
14329 goto friend_case;
14331 /* Calculate the most general template of which R is a
14332 specialization. */
14333 gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
14335 /* We're substituting a lambda function under tsubst_lambda_expr but not
14336 directly from it; find the matching function we're already inside.
14337 But don't do this if T is a generic lambda with a single level of
14338 template parms, as in that case we're doing a normal instantiation. */
14339 if (LAMBDA_FUNCTION_P (t) && !lambda_fntype
14340 && (!generic_lambda_fn_p (t)
14341 || TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)) > 1))
14342 return enclosing_instantiation_of (t);
14344 /* Calculate the complete set of arguments used to
14345 specialize R. */
14346 argvec = tsubst_template_args (DECL_TI_ARGS
14347 (DECL_TEMPLATE_RESULT
14348 (DECL_TI_TEMPLATE (t))),
14349 args, complain, in_decl);
14350 if (argvec == error_mark_node)
14351 return error_mark_node;
14353 /* Check to see if we already have this specialization. */
14354 if (!lambda_fntype)
14356 hash = spec_hasher::hash (gen_tmpl, argvec);
14357 if (tree spec = retrieve_specialization (gen_tmpl, argvec, hash))
14358 /* The spec for these args might be a partial instantiation of the
14359 template, but here what we want is the FUNCTION_DECL. */
14360 return STRIP_TEMPLATE (spec);
14363 else
14365 /* This special case arises when we have something like this:
14367 template <class T> struct S {
14368 friend void f<int>(int, double);
14371 Here, the DECL_TI_TEMPLATE for the friend declaration
14372 will be an IDENTIFIER_NODE. We are being called from
14373 tsubst_friend_function, and we want only to create a
14374 new decl (R) with appropriate types so that we can call
14375 determine_specialization. */
14376 friend_case:
14377 gen_tmpl = NULL_TREE;
14378 argvec = NULL_TREE;
14381 tree closure = (lambda_fntype ? TYPE_METHOD_BASETYPE (lambda_fntype)
14382 : NULL_TREE);
14383 tree ctx = closure ? closure : DECL_CONTEXT (t);
14384 bool member = ctx && TYPE_P (ctx);
14386 /* If this is a static lambda, remove the 'this' pointer added in
14387 tsubst_lambda_expr now that we know the closure type. */
14388 if (lambda_fntype && DECL_STATIC_FUNCTION_P (t))
14389 lambda_fntype = static_fn_type (lambda_fntype);
14391 if (member && !closure)
14392 ctx = tsubst_aggr_type (ctx, args,
14393 complain, t, /*entering_scope=*/1);
14395 tree type = (lambda_fntype ? lambda_fntype
14396 : tsubst (TREE_TYPE (t), args,
14397 complain | tf_fndecl_type, in_decl));
14398 if (type == error_mark_node)
14399 return error_mark_node;
14401 /* If we hit excessive deduction depth, the type is bogus even if
14402 it isn't error_mark_node, so don't build a decl. */
14403 if (excessive_deduction_depth)
14404 return error_mark_node;
14406 /* We do NOT check for matching decls pushed separately at this
14407 point, as they may not represent instantiations of this
14408 template, and in any case are considered separate under the
14409 discrete model. */
14410 tree r = copy_decl (t);
14411 DECL_USE_TEMPLATE (r) = 0;
14412 TREE_TYPE (r) = type;
14413 /* Clear out the mangled name and RTL for the instantiation. */
14414 SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
14415 SET_DECL_RTL (r, NULL);
14416 /* Leave DECL_INITIAL set on deleted instantiations. */
14417 if (!DECL_DELETED_FN (r))
14418 DECL_INITIAL (r) = NULL_TREE;
14419 DECL_CONTEXT (r) = ctx;
14420 set_instantiating_module (r);
14422 /* Handle explicit(dependent-expr). */
14423 if (DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (t))
14425 tree spec = lookup_explicit_specifier (t);
14426 spec = tsubst_copy_and_build (spec, args, complain, in_decl);
14427 spec = build_explicit_specifier (spec, complain);
14428 if (spec == error_mark_node)
14429 return error_mark_node;
14430 if (instantiation_dependent_expression_p (spec))
14431 store_explicit_specifier (r, spec);
14432 else
14434 DECL_NONCONVERTING_P (r) = (spec == boolean_true_node);
14435 DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (r) = false;
14439 /* OpenMP UDRs have the only argument a reference to the declared
14440 type. We want to diagnose if the declared type is a reference,
14441 which is invalid, but as references to references are usually
14442 quietly merged, diagnose it here. */
14443 if (DECL_OMP_DECLARE_REDUCTION_P (t))
14445 tree argtype
14446 = TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (t))));
14447 argtype = tsubst (argtype, args, complain, in_decl);
14448 if (TYPE_REF_P (argtype))
14449 error_at (DECL_SOURCE_LOCATION (t),
14450 "reference type %qT in "
14451 "%<#pragma omp declare reduction%>", argtype);
14452 if (strchr (IDENTIFIER_POINTER (DECL_NAME (t)), '~') == NULL)
14453 DECL_NAME (r) = omp_reduction_id (ERROR_MARK, DECL_NAME (t),
14454 argtype);
14457 if (member && DECL_CONV_FN_P (r))
14458 /* Type-conversion operator. Reconstruct the name, in
14459 case it's the name of one of the template's parameters. */
14460 DECL_NAME (r) = make_conv_op_name (TREE_TYPE (type));
14462 tree parms = DECL_ARGUMENTS (t);
14463 if (closure && !DECL_STATIC_FUNCTION_P (t))
14464 parms = DECL_CHAIN (parms);
14465 parms = tsubst (parms, args, complain, t);
14466 for (tree parm = parms; parm; parm = DECL_CHAIN (parm))
14467 DECL_CONTEXT (parm) = r;
14468 if (closure && !DECL_STATIC_FUNCTION_P (t))
14470 tree tparm = build_this_parm (r, closure, type_memfn_quals (type));
14471 DECL_NAME (tparm) = closure_identifier;
14472 DECL_CHAIN (tparm) = parms;
14473 parms = tparm;
14475 DECL_ARGUMENTS (r) = parms;
14476 DECL_RESULT (r) = NULL_TREE;
14478 maybe_rebuild_function_decl_type (r);
14480 TREE_STATIC (r) = 0;
14481 TREE_PUBLIC (r) = TREE_PUBLIC (t);
14482 DECL_EXTERNAL (r) = 1;
14483 /* If this is an instantiation of a function with internal
14484 linkage, we already know what object file linkage will be
14485 assigned to the instantiation. */
14486 DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
14487 DECL_DEFER_OUTPUT (r) = 0;
14488 DECL_CHAIN (r) = NULL_TREE;
14489 DECL_PENDING_INLINE_INFO (r) = 0;
14490 DECL_PENDING_INLINE_P (r) = 0;
14491 DECL_SAVED_TREE (r) = NULL_TREE;
14492 DECL_STRUCT_FUNCTION (r) = NULL;
14493 TREE_USED (r) = 0;
14494 /* We'll re-clone as appropriate in instantiate_template. */
14495 DECL_CLONED_FUNCTION (r) = NULL_TREE;
14497 /* If we aren't complaining now, return on error before we register
14498 the specialization so that we'll complain eventually. */
14499 if ((complain & tf_error) == 0
14500 && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
14501 && !grok_op_properties (r, /*complain=*/false))
14502 return error_mark_node;
14504 /* Associate the constraints directly with the instantiation. We
14505 don't substitute through the constraints; that's only done when
14506 they are checked. */
14507 if (tree ci = get_constraints (t))
14508 set_constraints (r, ci);
14510 if (DECL_FRIEND_CONTEXT (t))
14511 SET_DECL_FRIEND_CONTEXT (r,
14512 tsubst (DECL_FRIEND_CONTEXT (t),
14513 args, complain, in_decl));
14515 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14516 args, complain, in_decl))
14517 return error_mark_node;
14519 /* Set up the DECL_TEMPLATE_INFO for R. There's no need to do
14520 this in the special friend case mentioned above where
14521 GEN_TMPL is NULL. */
14522 if (gen_tmpl && !closure)
14524 DECL_TEMPLATE_INFO (r)
14525 = build_template_info (gen_tmpl, argvec);
14526 SET_DECL_IMPLICIT_INSTANTIATION (r);
14528 tree new_r
14529 = register_specialization (r, gen_tmpl, argvec, false, hash);
14530 if (new_r != r)
14531 /* We instantiated this while substituting into
14532 the type earlier (template/friend54.C). */
14533 return new_r;
14535 /* We're not supposed to instantiate default arguments
14536 until they are called, for a template. But, for a
14537 declaration like:
14539 template <class T> void f ()
14540 { extern void g(int i = T()); }
14542 we should do the substitution when the template is
14543 instantiated. We handle the member function case in
14544 instantiate_class_template since the default arguments
14545 might refer to other members of the class. */
14546 if (!member
14547 && !PRIMARY_TEMPLATE_P (gen_tmpl)
14548 && !uses_template_parms (argvec))
14549 tsubst_default_arguments (r, complain);
14551 else if (DECL_LOCAL_DECL_P (r))
14553 if (!cp_unevaluated_operand)
14554 register_local_specialization (r, t);
14556 else
14557 DECL_TEMPLATE_INFO (r) = NULL_TREE;
14559 /* Copy the list of befriending classes. */
14560 for (tree *friends = &DECL_BEFRIENDING_CLASSES (r);
14561 *friends;
14562 friends = &TREE_CHAIN (*friends))
14564 *friends = copy_node (*friends);
14565 TREE_VALUE (*friends)
14566 = tsubst (TREE_VALUE (*friends), args, complain, in_decl);
14569 if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
14571 maybe_retrofit_in_chrg (r);
14572 if (DECL_CONSTRUCTOR_P (r) && !grok_ctor_properties (ctx, r))
14573 return error_mark_node;
14574 /* If this is an instantiation of a member template, clone it.
14575 If it isn't, that'll be handled by
14576 clone_constructors_and_destructors. */
14577 if (gen_tmpl && PRIMARY_TEMPLATE_P (gen_tmpl))
14578 clone_cdtor (r, /*update_methods=*/false);
14580 else if ((complain & tf_error) != 0
14581 && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
14582 && !grok_op_properties (r, /*complain=*/true))
14583 return error_mark_node;
14585 /* Possibly limit visibility based on template args. */
14586 DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
14587 if (DECL_VISIBILITY_SPECIFIED (t))
14589 DECL_VISIBILITY_SPECIFIED (r) = 0;
14590 DECL_ATTRIBUTES (r)
14591 = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
14593 determine_visibility (r);
14594 if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
14595 && !processing_template_decl)
14596 defaulted_late_check (r);
14598 if (flag_openmp)
14599 if (tree attr = lookup_attribute ("omp declare variant base",
14600 DECL_ATTRIBUTES (r)))
14601 omp_declare_variant_finalize (r, attr);
14603 return r;
14606 /* Subroutine of tsubst_decl for the case when T is a TEMPLATE_DECL. */
14608 static tree
14609 tsubst_template_decl (tree t, tree args, tsubst_flags_t complain,
14610 tree lambda_fntype, tree lambda_tparms)
14612 /* We can get here when processing a member function template,
14613 member class template, or template template parameter. */
14614 tree decl = DECL_TEMPLATE_RESULT (t);
14615 tree in_decl = t;
14616 tree spec;
14617 tree tmpl_args;
14618 tree full_args;
14619 tree r;
14620 hashval_t hash = 0;
14622 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
14624 /* Template template parameter is treated here. */
14625 tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14626 if (new_type == error_mark_node)
14627 r = error_mark_node;
14628 /* If we get a real template back, return it. This can happen in
14629 the context of most_specialized_partial_spec. */
14630 else if (TREE_CODE (new_type) == TEMPLATE_DECL)
14631 r = new_type;
14632 else
14633 /* The new TEMPLATE_DECL was built in
14634 reduce_template_parm_level. */
14635 r = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (new_type);
14636 return r;
14639 if (!lambda_fntype)
14641 /* We might already have an instance of this template.
14642 The ARGS are for the surrounding class type, so the
14643 full args contain the tsubst'd args for the context,
14644 plus the innermost args from the template decl. */
14645 tmpl_args = DECL_CLASS_TEMPLATE_P (t)
14646 ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
14647 : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
14648 /* Because this is a template, the arguments will still be
14649 dependent, even after substitution. If
14650 PROCESSING_TEMPLATE_DECL is not set, the dependency
14651 predicates will short-circuit. */
14652 ++processing_template_decl;
14653 full_args = tsubst_template_args (tmpl_args, args,
14654 complain, in_decl);
14655 --processing_template_decl;
14656 if (full_args == error_mark_node)
14657 return error_mark_node;
14659 /* If this is a default template template argument,
14660 tsubst might not have changed anything. */
14661 if (full_args == tmpl_args)
14662 return t;
14664 hash = spec_hasher::hash (t, full_args);
14665 spec = retrieve_specialization (t, full_args, hash);
14666 if (spec != NULL_TREE)
14668 if (TYPE_P (spec))
14669 /* Type partial instantiations are stored as the type by
14670 lookup_template_class_1, not here as the template. */
14671 spec = CLASSTYPE_TI_TEMPLATE (spec);
14672 return spec;
14676 /* Make a new template decl. It will be similar to the
14677 original, but will record the current template arguments.
14678 We also create a new function declaration, which is just
14679 like the old one, but points to this new template, rather
14680 than the old one. */
14681 r = copy_decl (t);
14682 gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
14683 DECL_CHAIN (r) = NULL_TREE;
14685 // Build new template info linking to the original template decl.
14686 if (!lambda_fntype)
14688 DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
14689 SET_DECL_IMPLICIT_INSTANTIATION (r);
14691 else
14692 DECL_TEMPLATE_INFO (r) = NULL_TREE;
14694 /* The template parameters for this new template are all the
14695 template parameters for the old template, except the
14696 outermost level of parameters. */
14697 auto tparm_guard = make_temp_override (current_template_parms);
14698 DECL_TEMPLATE_PARMS (r)
14699 = current_template_parms
14700 = (lambda_tparms
14701 ? lambda_tparms
14702 : tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
14703 complain));
14705 bool class_p = false;
14706 tree inner = decl;
14707 ++processing_template_decl;
14708 if (TREE_CODE (inner) == FUNCTION_DECL)
14709 inner = tsubst_function_decl (inner, args, complain, lambda_fntype);
14710 else
14712 if (TREE_CODE (inner) == TYPE_DECL && !TYPE_DECL_ALIAS_P (inner))
14714 class_p = true;
14715 inner = TREE_TYPE (inner);
14717 if (class_p)
14718 inner = tsubst_aggr_type (inner, args, complain,
14719 in_decl, /*entering*/1);
14720 else
14721 inner = tsubst (inner, args, complain, in_decl);
14723 --processing_template_decl;
14724 if (inner == error_mark_node)
14725 return error_mark_node;
14727 if (class_p)
14729 /* For a partial specialization, we need to keep pointing to
14730 the primary template. */
14731 if (!DECL_TEMPLATE_SPECIALIZATION (t))
14733 CLASSTYPE_TI_TEMPLATE (inner) = r;
14734 CLASSTYPE_USE_TEMPLATE (inner) = 0;
14737 DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (inner);
14738 inner = TYPE_MAIN_DECL (inner);
14740 else if (lambda_fntype)
14742 tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (r));
14743 DECL_TEMPLATE_INFO (inner) = build_template_info (r, args);
14745 else
14747 DECL_TI_TEMPLATE (inner) = r;
14748 DECL_TI_ARGS (r) = DECL_TI_ARGS (inner);
14751 DECL_TEMPLATE_RESULT (r) = inner;
14752 TREE_TYPE (r) = TREE_TYPE (inner);
14753 DECL_CONTEXT (r) = DECL_CONTEXT (inner);
14755 if (modules_p ())
14757 /* Propagate module information from the decl. */
14758 DECL_MODULE_EXPORT_P (r) = DECL_MODULE_EXPORT_P (inner);
14759 if (DECL_LANG_SPECIFIC (inner))
14760 /* If this is a constrained template, the above tsubst of
14761 inner can find the unconstrained template, which may have
14762 come from an import. This is ok, because we don't
14763 register this instantiation (see below). */
14764 gcc_checking_assert (!DECL_MODULE_IMPORT_P (inner)
14765 || (TEMPLATE_PARMS_CONSTRAINTS
14766 (DECL_TEMPLATE_PARMS (t))));
14769 DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
14770 DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
14772 if (PRIMARY_TEMPLATE_P (t))
14773 DECL_PRIMARY_TEMPLATE (r) = r;
14775 if (TREE_CODE (decl) == FUNCTION_DECL && !lambda_fntype)
14776 /* Record this non-type partial instantiation. */
14777 register_specialization (r, t,
14778 DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
14779 false, hash);
14781 return r;
14784 /* True if FN is the op() for a lambda in an uninstantiated template. */
14786 bool
14787 lambda_fn_in_template_p (tree fn)
14789 if (!fn || !LAMBDA_FUNCTION_P (fn))
14790 return false;
14791 tree closure = DECL_CONTEXT (fn);
14792 return CLASSTYPE_TEMPLATE_INFO (closure) != NULL_TREE;
14795 /* True if FN is the substitution (via tsubst_lambda_expr) of a function for
14796 which the above is true. */
14798 bool
14799 regenerated_lambda_fn_p (tree fn)
14801 if (!fn || !LAMBDA_FUNCTION_P (fn))
14802 return false;
14803 tree closure = DECL_CONTEXT (fn);
14804 tree lam = CLASSTYPE_LAMBDA_EXPR (closure);
14805 return LAMBDA_EXPR_REGEN_INFO (lam) != NULL_TREE;
14808 /* Return the LAMBDA_EXPR from which T was ultimately regenerated.
14809 If T is not a regenerated LAMBDA_EXPR, return T. */
14811 tree
14812 most_general_lambda (tree t)
14814 while (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
14815 t = TI_TEMPLATE (ti);
14816 return t;
14819 /* Return the set of template arguments used to regenerate the lambda T
14820 from its most general lambda. */
14822 tree
14823 lambda_regenerating_args (tree t)
14825 if (LAMBDA_FUNCTION_P (t))
14826 t = CLASSTYPE_LAMBDA_EXPR (DECL_CONTEXT (t));
14827 gcc_assert (TREE_CODE (t) == LAMBDA_EXPR);
14828 if (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
14829 return TI_ARGS (ti);
14830 else
14831 return NULL_TREE;
14834 /* We're instantiating a variable from template function TCTX. Return the
14835 corresponding current enclosing scope. We can match them up using
14836 DECL_SOURCE_LOCATION because lambdas only ever have one source location, and
14837 the DECL_SOURCE_LOCATION for a function instantiation is updated to match
14838 the template definition in regenerate_decl_from_template. */
14840 static tree
14841 enclosing_instantiation_of (tree tctx)
14843 tree fn = current_function_decl;
14845 /* We shouldn't ever need to do this for other artificial functions. */
14846 gcc_assert (!DECL_ARTIFICIAL (tctx) || LAMBDA_FUNCTION_P (tctx));
14848 for (; fn; fn = decl_function_context (fn))
14849 if (DECL_SOURCE_LOCATION (fn) == DECL_SOURCE_LOCATION (tctx))
14850 return fn;
14851 gcc_unreachable ();
14854 /* Substitute the ARGS into the T, which is a _DECL. Return the
14855 result of the substitution. Issue error and warning messages under
14856 control of COMPLAIN. */
14858 static tree
14859 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
14861 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
14862 location_t saved_loc;
14863 tree r = NULL_TREE;
14864 tree in_decl = t;
14865 hashval_t hash = 0;
14867 /* Set the filename and linenumber to improve error-reporting. */
14868 saved_loc = input_location;
14869 input_location = DECL_SOURCE_LOCATION (t);
14871 switch (TREE_CODE (t))
14873 case TEMPLATE_DECL:
14874 r = tsubst_template_decl (t, args, complain,
14875 /*lambda_fntype=*/NULL_TREE,
14876 /*lambda_tparms=*/NULL_TREE);
14877 break;
14879 case FUNCTION_DECL:
14880 r = tsubst_function_decl (t, args, complain, /*lambda*/NULL_TREE);
14881 break;
14883 case PARM_DECL:
14885 tree type = NULL_TREE;
14886 int i, len = 1;
14887 tree expanded_types = NULL_TREE;
14888 tree prev_r = NULL_TREE;
14889 tree first_r = NULL_TREE;
14891 if (DECL_PACK_P (t))
14893 /* If there is a local specialization that isn't a
14894 parameter pack, it means that we're doing a "simple"
14895 substitution from inside tsubst_pack_expansion. Just
14896 return the local specialization (which will be a single
14897 parm). */
14898 tree spec = retrieve_local_specialization (t);
14899 if (spec
14900 && TREE_CODE (spec) == PARM_DECL
14901 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
14902 RETURN (spec);
14904 /* Expand the TYPE_PACK_EXPANSION that provides the types for
14905 the parameters in this function parameter pack. */
14906 expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
14907 complain, in_decl);
14908 if (TREE_CODE (expanded_types) == TREE_VEC)
14910 len = TREE_VEC_LENGTH (expanded_types);
14912 /* Zero-length parameter packs are boring. Just substitute
14913 into the chain. */
14914 if (len == 0 && !cp_unevaluated_operand)
14915 RETURN (tsubst (TREE_CHAIN (t), args, complain,
14916 TREE_CHAIN (t)));
14918 else
14920 /* All we did was update the type. Make a note of that. */
14921 type = expanded_types;
14922 expanded_types = NULL_TREE;
14926 /* Loop through all of the parameters we'll build. When T is
14927 a function parameter pack, LEN is the number of expanded
14928 types in EXPANDED_TYPES; otherwise, LEN is 1. */
14929 r = NULL_TREE;
14930 for (i = 0; i < len; ++i)
14932 prev_r = r;
14933 r = copy_node (t);
14934 if (DECL_TEMPLATE_PARM_P (t))
14935 SET_DECL_TEMPLATE_PARM_P (r);
14937 if (expanded_types)
14938 /* We're on the Ith parameter of the function parameter
14939 pack. */
14941 /* Get the Ith type. */
14942 type = TREE_VEC_ELT (expanded_types, i);
14944 /* Rename the parameter to include the index. */
14945 DECL_NAME (r)
14946 = make_ith_pack_parameter_name (DECL_NAME (r), i);
14948 else if (!type)
14949 /* We're dealing with a normal parameter. */
14950 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14952 type = type_decays_to (type);
14953 TREE_TYPE (r) = type;
14954 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
14956 if (DECL_INITIAL (r))
14958 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
14959 DECL_INITIAL (r) = TREE_TYPE (r);
14960 else
14961 DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
14962 complain, in_decl);
14965 DECL_CONTEXT (r) = NULL_TREE;
14967 if (!DECL_TEMPLATE_PARM_P (r))
14968 DECL_ARG_TYPE (r) = type_passed_as (type);
14970 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14971 args, complain, in_decl))
14972 return error_mark_node;
14974 /* Keep track of the first new parameter we
14975 generate. That's what will be returned to the
14976 caller. */
14977 if (!first_r)
14978 first_r = r;
14980 /* Build a proper chain of parameters when substituting
14981 into a function parameter pack. */
14982 if (prev_r)
14983 DECL_CHAIN (prev_r) = r;
14986 /* If cp_unevaluated_operand is set, we're just looking for a
14987 single dummy parameter, so don't keep going. */
14988 if (DECL_CHAIN (t) && !cp_unevaluated_operand)
14989 DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
14990 complain, DECL_CHAIN (t));
14992 /* FIRST_R contains the start of the chain we've built. */
14993 r = first_r;
14995 break;
14997 case FIELD_DECL:
14999 tree type = NULL_TREE;
15000 tree vec = NULL_TREE;
15001 tree expanded_types = NULL_TREE;
15002 int len = 1;
15004 if (PACK_EXPANSION_P (TREE_TYPE (t)))
15006 /* This field is a lambda capture pack. Return a TREE_VEC of
15007 the expanded fields to instantiate_class_template_1. */
15008 expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
15009 complain, in_decl);
15010 if (TREE_CODE (expanded_types) == TREE_VEC)
15012 len = TREE_VEC_LENGTH (expanded_types);
15013 vec = make_tree_vec (len);
15015 else
15017 /* All we did was update the type. Make a note of that. */
15018 type = expanded_types;
15019 expanded_types = NULL_TREE;
15023 for (int i = 0; i < len; ++i)
15025 r = copy_decl (t);
15026 if (expanded_types)
15028 type = TREE_VEC_ELT (expanded_types, i);
15029 DECL_NAME (r)
15030 = make_ith_pack_parameter_name (DECL_NAME (r), i);
15032 else if (!type)
15033 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15035 if (type == error_mark_node)
15036 RETURN (error_mark_node);
15037 TREE_TYPE (r) = type;
15038 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
15040 if (DECL_C_BIT_FIELD (r))
15041 /* For bit-fields, DECL_BIT_FIELD_REPRESENTATIVE gives the
15042 number of bits. */
15043 DECL_BIT_FIELD_REPRESENTATIVE (r)
15044 = tsubst_expr (DECL_BIT_FIELD_REPRESENTATIVE (t), args,
15045 complain, in_decl);
15046 if (DECL_INITIAL (t))
15048 /* Set up DECL_TEMPLATE_INFO so that we can get at the
15049 NSDMI in perform_member_init. Still set DECL_INITIAL
15050 so that we know there is one. */
15051 DECL_INITIAL (r) = void_node;
15052 gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
15053 retrofit_lang_decl (r);
15054 DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
15056 /* We don't have to set DECL_CONTEXT here; it is set by
15057 finish_member_declaration. */
15058 DECL_CHAIN (r) = NULL_TREE;
15060 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
15061 args, complain, in_decl))
15062 return error_mark_node;
15064 if (vec)
15065 TREE_VEC_ELT (vec, i) = r;
15068 if (vec)
15069 r = vec;
15071 break;
15073 case USING_DECL:
15074 /* We reach here only for member using decls. We also need to check
15075 uses_template_parms because DECL_DEPENDENT_P is not set for a
15076 using-declaration that designates a member of the current
15077 instantiation (c++/53549). */
15078 if (DECL_DEPENDENT_P (t)
15079 || uses_template_parms (USING_DECL_SCOPE (t)))
15081 /* True iff this using-decl was written as a pack expansion
15082 (and a pack appeared in its scope or name). If a pack
15083 appeared in both, we expand the packs separately and
15084 manually merge them. */
15085 bool variadic_p = false;
15087 tree scope = USING_DECL_SCOPE (t);
15088 if (PACK_EXPANSION_P (scope))
15090 scope = tsubst_pack_expansion (scope, args,
15091 complain | tf_qualifying_scope,
15092 in_decl);
15093 variadic_p = true;
15095 else
15096 scope = tsubst_scope (scope, args, complain, in_decl);
15098 tree name = DECL_NAME (t);
15099 if (IDENTIFIER_CONV_OP_P (name)
15100 && PACK_EXPANSION_P (TREE_TYPE (name)))
15102 name = tsubst_pack_expansion (TREE_TYPE (name), args,
15103 complain, in_decl);
15104 if (name == error_mark_node)
15106 r = error_mark_node;
15107 break;
15109 for (tree& elt : tree_vec_range (name))
15110 elt = make_conv_op_name (elt);
15111 variadic_p = true;
15113 else
15114 name = tsubst_copy (name, args, complain, in_decl);
15116 int len;
15117 if (!variadic_p)
15118 len = 1;
15119 else if (TREE_CODE (scope) == TREE_VEC
15120 && TREE_CODE (name) == TREE_VEC)
15122 if (TREE_VEC_LENGTH (scope) != TREE_VEC_LENGTH (name))
15124 error ("mismatched argument pack lengths (%d vs %d)",
15125 TREE_VEC_LENGTH (scope), TREE_VEC_LENGTH (name));
15126 r = error_mark_node;
15127 break;
15129 len = TREE_VEC_LENGTH (scope);
15131 else if (TREE_CODE (scope) == TREE_VEC)
15132 len = TREE_VEC_LENGTH (scope);
15133 else /* TREE_CODE (name) == TREE_VEC */
15134 len = TREE_VEC_LENGTH (name);
15136 r = make_tree_vec (len);
15137 for (int i = 0; i < len; ++i)
15139 tree escope = (TREE_CODE (scope) == TREE_VEC
15140 ? TREE_VEC_ELT (scope, i)
15141 : scope);
15142 tree ename = (TREE_CODE (name) == TREE_VEC
15143 ? TREE_VEC_ELT (name, i)
15144 : name);
15145 tree elt = do_class_using_decl (escope, ename);
15146 if (!elt)
15148 r = error_mark_node;
15149 break;
15151 TREE_PROTECTED (elt) = TREE_PROTECTED (t);
15152 TREE_PRIVATE (elt) = TREE_PRIVATE (t);
15153 TREE_VEC_ELT (r, i) = elt;
15156 if (!variadic_p && r != error_mark_node)
15157 r = TREE_VEC_ELT (r, 0);
15159 else
15161 r = copy_node (t);
15162 DECL_CHAIN (r) = NULL_TREE;
15164 break;
15166 case TYPE_DECL:
15167 case VAR_DECL:
15169 tree argvec = NULL_TREE;
15170 tree gen_tmpl = NULL_TREE;
15171 tree tmpl = NULL_TREE;
15172 tree type = NULL_TREE;
15174 if (TREE_TYPE (t) == error_mark_node)
15175 RETURN (error_mark_node);
15177 if (TREE_CODE (t) == TYPE_DECL
15178 && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
15180 /* If this is the canonical decl, we don't have to
15181 mess with instantiations, and often we can't (for
15182 typename, template type parms and such). Note that
15183 TYPE_NAME is not correct for the above test if
15184 we've copied the type for a typedef. */
15185 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15186 if (type == error_mark_node)
15187 RETURN (error_mark_node);
15188 r = TYPE_NAME (type);
15189 break;
15192 /* Check to see if we already have the specialization we
15193 need. */
15194 tree spec = NULL_TREE;
15195 bool local_p = false;
15196 tree ctx = DECL_CONTEXT (t);
15197 if (!(VAR_P (t) && DECL_LOCAL_DECL_P (t))
15198 && (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t)))
15200 local_p = false;
15201 if (DECL_CLASS_SCOPE_P (t))
15203 ctx = tsubst_aggr_type (ctx, args,
15204 complain,
15205 in_decl, /*entering_scope=*/1);
15206 if (DECL_SELF_REFERENCE_P (t))
15207 /* The context and type of an injected-class-name are
15208 the same, so we don't need to substitute both. */
15209 type = ctx;
15210 /* If CTX is unchanged, then T is in fact the
15211 specialization we want. That situation occurs when
15212 referencing a static data member within in its own
15213 class. We can use pointer equality, rather than
15214 same_type_p, because DECL_CONTEXT is always
15215 canonical... */
15216 if (ctx == DECL_CONTEXT (t)
15217 /* ... unless T is a member template; in which
15218 case our caller can be willing to create a
15219 specialization of that template represented
15220 by T. */
15221 && !(DECL_TI_TEMPLATE (t)
15222 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (t))))
15223 spec = t;
15226 if (!spec)
15228 tmpl = DECL_TI_TEMPLATE (t);
15229 gen_tmpl = most_general_template (tmpl);
15230 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
15231 if (argvec != error_mark_node
15232 && PRIMARY_TEMPLATE_P (gen_tmpl)
15233 && TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (argvec))
15234 /* We're fully specializing a template declaration, so
15235 we need to coerce the innermost arguments corresponding to
15236 the template. */
15237 argvec = (coerce_template_parms
15238 (DECL_TEMPLATE_PARMS (gen_tmpl),
15239 argvec, tmpl, complain));
15240 if (argvec == error_mark_node)
15241 RETURN (error_mark_node);
15242 hash = spec_hasher::hash (gen_tmpl, argvec);
15243 spec = retrieve_specialization (gen_tmpl, argvec, hash);
15246 else
15248 if (!(VAR_P (t) && DECL_LOCAL_DECL_P (t)))
15249 /* Subsequent calls to pushdecl will fill this in. */
15250 ctx = NULL_TREE;
15251 /* A local variable. */
15252 local_p = true;
15253 /* Unless this is a reference to a static variable from an
15254 enclosing function, in which case we need to fill it in now. */
15255 if (TREE_STATIC (t))
15257 tree fn = enclosing_instantiation_of (DECL_CONTEXT (t));
15258 if (fn != current_function_decl)
15259 ctx = fn;
15261 spec = retrieve_local_specialization (t);
15263 /* If we already have the specialization we need, there is
15264 nothing more to do. */
15265 if (spec)
15267 r = spec;
15268 break;
15271 /* Create a new node for the specialization we need. */
15272 if (type == NULL_TREE)
15274 if (is_typedef_decl (t))
15275 type = DECL_ORIGINAL_TYPE (t);
15276 else
15277 type = TREE_TYPE (t);
15278 if (VAR_P (t)
15279 && VAR_HAD_UNKNOWN_BOUND (t)
15280 && type != error_mark_node)
15281 type = strip_array_domain (type);
15282 tsubst_flags_t tcomplain = complain;
15283 if (VAR_P (t))
15284 tcomplain |= tf_tst_ok;
15285 type = tsubst (type, args, tcomplain, in_decl);
15286 /* Substituting the type might have recursively instantiated this
15287 same alias (c++/86171). */
15288 if (gen_tmpl && DECL_ALIAS_TEMPLATE_P (gen_tmpl)
15289 && (spec = retrieve_specialization (gen_tmpl, argvec, hash)))
15291 r = spec;
15292 break;
15295 r = copy_decl (t);
15296 if (VAR_P (r))
15298 DECL_INITIALIZED_P (r) = 0;
15299 DECL_TEMPLATE_INSTANTIATED (r) = 0;
15300 if (type == error_mark_node)
15301 RETURN (error_mark_node);
15302 if (TREE_CODE (type) == FUNCTION_TYPE)
15304 /* It may seem that this case cannot occur, since:
15306 typedef void f();
15307 void g() { f x; }
15309 declares a function, not a variable. However:
15311 typedef void f();
15312 template <typename T> void g() { T t; }
15313 template void g<f>();
15315 is an attempt to declare a variable with function
15316 type. */
15317 error ("variable %qD has function type",
15318 /* R is not yet sufficiently initialized, so we
15319 just use its name. */
15320 DECL_NAME (r));
15321 RETURN (error_mark_node);
15323 type = complete_type (type);
15324 /* Wait until cp_finish_decl to set this again, to handle
15325 circular dependency (template/instantiate6.C). */
15326 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
15327 type = check_var_type (DECL_NAME (r), type,
15328 DECL_SOURCE_LOCATION (r));
15329 if (DECL_HAS_VALUE_EXPR_P (t))
15331 tree ve = DECL_VALUE_EXPR (t);
15332 /* If the DECL_VALUE_EXPR is converted to the declared type,
15333 preserve the identity so that gimplify_type_sizes works. */
15334 bool nop = (TREE_CODE (ve) == NOP_EXPR);
15335 if (nop)
15336 ve = TREE_OPERAND (ve, 0);
15337 ve = tsubst_expr (ve, args, complain, in_decl);
15338 if (REFERENCE_REF_P (ve))
15340 gcc_assert (TYPE_REF_P (type));
15341 ve = TREE_OPERAND (ve, 0);
15343 if (nop)
15344 ve = build_nop (type, ve);
15345 else if (DECL_LANG_SPECIFIC (t)
15346 && DECL_OMP_PRIVATIZED_MEMBER (t)
15347 && TREE_CODE (ve) == COMPONENT_REF
15348 && TREE_CODE (TREE_OPERAND (ve, 1)) == FIELD_DECL
15349 && DECL_BIT_FIELD_TYPE (TREE_OPERAND (ve, 1)) == type)
15350 type = TREE_TYPE (ve);
15351 else
15352 gcc_checking_assert (TYPE_MAIN_VARIANT (TREE_TYPE (ve))
15353 == TYPE_MAIN_VARIANT (type));
15354 SET_DECL_VALUE_EXPR (r, ve);
15356 if (CP_DECL_THREAD_LOCAL_P (r)
15357 && !processing_template_decl)
15358 set_decl_tls_model (r, decl_default_tls_model (r));
15360 else if (DECL_SELF_REFERENCE_P (t))
15361 SET_DECL_SELF_REFERENCE_P (r);
15362 TREE_TYPE (r) = type;
15363 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
15364 DECL_CONTEXT (r) = ctx;
15365 /* Clear out the mangled name and RTL for the instantiation. */
15366 SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
15367 if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
15368 SET_DECL_RTL (r, NULL);
15369 set_instantiating_module (r);
15371 /* The initializer must not be expanded until it is required;
15372 see [temp.inst]. */
15373 DECL_INITIAL (r) = NULL_TREE;
15374 DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
15375 if (VAR_P (r))
15377 if (DECL_LANG_SPECIFIC (r))
15378 SET_DECL_DEPENDENT_INIT_P (r, false);
15380 SET_DECL_MODE (r, VOIDmode);
15382 /* Possibly limit visibility based on template args. */
15383 DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
15384 if (DECL_VISIBILITY_SPECIFIED (t))
15386 DECL_VISIBILITY_SPECIFIED (r) = 0;
15387 DECL_ATTRIBUTES (r)
15388 = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
15390 determine_visibility (r);
15393 if (!local_p)
15395 /* A static data member declaration is always marked
15396 external when it is declared in-class, even if an
15397 initializer is present. We mimic the non-template
15398 processing here. */
15399 DECL_EXTERNAL (r) = 1;
15400 if (DECL_NAMESPACE_SCOPE_P (t))
15401 DECL_NOT_REALLY_EXTERN (r) = 1;
15403 DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
15404 SET_DECL_IMPLICIT_INSTANTIATION (r);
15405 if (!error_operand_p (r) || (complain & tf_error))
15406 register_specialization (r, gen_tmpl, argvec, false, hash);
15408 else
15410 if (DECL_LANG_SPECIFIC (r))
15411 DECL_TEMPLATE_INFO (r) = NULL_TREE;
15412 if (!cp_unevaluated_operand)
15413 register_local_specialization (r, t);
15416 DECL_CHAIN (r) = NULL_TREE;
15418 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
15419 /*flags=*/0,
15420 args, complain, in_decl))
15421 return error_mark_node;
15423 /* Preserve a typedef that names a type. */
15424 if (is_typedef_decl (r) && type != error_mark_node)
15426 DECL_ORIGINAL_TYPE (r) = NULL_TREE;
15427 set_underlying_type (r);
15429 /* common_handle_aligned_attribute doesn't apply the alignment
15430 to DECL_ORIGINAL_TYPE. */
15431 if (TYPE_USER_ALIGN (TREE_TYPE (t)))
15432 TREE_TYPE (r) = build_aligned_type (TREE_TYPE (r),
15433 TYPE_ALIGN (TREE_TYPE (t)));
15436 layout_decl (r, 0);
15438 break;
15440 default:
15441 gcc_unreachable ();
15443 #undef RETURN
15445 out:
15446 /* Restore the file and line information. */
15447 input_location = saved_loc;
15449 return r;
15452 /* Substitute into the complete parameter type list PARMS. */
15454 tree
15455 tsubst_function_parms (tree parms,
15456 tree args,
15457 tsubst_flags_t complain,
15458 tree in_decl)
15460 return tsubst_arg_types (parms, args, NULL_TREE, complain, in_decl);
15463 /* Substitute into the ARG_TYPES of a function type.
15464 If END is a TREE_CHAIN, leave it and any following types
15465 un-substituted. */
15467 static tree
15468 tsubst_arg_types (tree arg_types,
15469 tree args,
15470 tree end,
15471 tsubst_flags_t complain,
15472 tree in_decl)
15474 tree type = NULL_TREE;
15475 int len = 1;
15476 tree expanded_args = NULL_TREE;
15478 if (!arg_types || arg_types == void_list_node || arg_types == end)
15479 return arg_types;
15481 if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
15483 /* For a pack expansion, perform substitution on the
15484 entire expression. Later on, we'll handle the arguments
15485 one-by-one. */
15486 expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
15487 args, complain, in_decl);
15489 if (TREE_CODE (expanded_args) == TREE_VEC)
15490 /* So that we'll spin through the parameters, one by one. */
15491 len = TREE_VEC_LENGTH (expanded_args);
15492 else
15494 /* We only partially substituted into the parameter
15495 pack. Our type is TYPE_PACK_EXPANSION. */
15496 type = expanded_args;
15497 expanded_args = NULL_TREE;
15500 else
15501 type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
15503 /* Check if a substituted type is erroneous before substituting into
15504 the rest of the chain. */
15505 for (int i = 0; i < len; i++)
15507 if (expanded_args)
15508 type = TREE_VEC_ELT (expanded_args, i);
15510 if (type == error_mark_node)
15511 return error_mark_node;
15512 if (VOID_TYPE_P (type))
15514 if (complain & tf_error)
15516 error ("invalid parameter type %qT", type);
15517 if (in_decl)
15518 error ("in declaration %q+D", in_decl);
15520 return error_mark_node;
15524 /* We do not substitute into default arguments here. The standard
15525 mandates that they be instantiated only when needed, which is
15526 done in build_over_call. */
15527 tree default_arg = TREE_PURPOSE (arg_types);
15529 /* Except that we do substitute default arguments under tsubst_lambda_expr,
15530 since the new op() won't have any associated template arguments for us
15531 to refer to later. */
15532 if (lambda_fn_in_template_p (in_decl)
15533 || (in_decl && TREE_CODE (in_decl) == FUNCTION_DECL
15534 && DECL_LOCAL_DECL_P (in_decl)))
15535 default_arg = tsubst_copy_and_build (default_arg, args, complain, in_decl);
15537 tree remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
15538 args, end, complain, in_decl);
15539 if (remaining_arg_types == error_mark_node)
15540 return error_mark_node;
15542 for (int i = len-1; i >= 0; i--)
15544 if (expanded_args)
15545 type = TREE_VEC_ELT (expanded_args, i);
15547 /* Do array-to-pointer, function-to-pointer conversion, and ignore
15548 top-level qualifiers as required. */
15549 type = cv_unqualified (type_decays_to (type));
15551 if (default_arg && TREE_CODE (default_arg) == DEFERRED_PARSE)
15553 /* We've instantiated a template before its default arguments
15554 have been parsed. This can happen for a nested template
15555 class, and is not an error unless we require the default
15556 argument in a call of this function. */
15557 remaining_arg_types
15558 = tree_cons (default_arg, type, remaining_arg_types);
15559 vec_safe_push (DEFPARSE_INSTANTIATIONS (default_arg),
15560 remaining_arg_types);
15562 else
15563 remaining_arg_types
15564 = hash_tree_cons (default_arg, type, remaining_arg_types);
15567 return remaining_arg_types;
15570 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE. This routine does
15571 *not* handle the exception-specification for FNTYPE, because the
15572 initial substitution of explicitly provided template parameters
15573 during argument deduction forbids substitution into the
15574 exception-specification:
15576 [temp.deduct]
15578 All references in the function type of the function template to the
15579 corresponding template parameters are replaced by the specified tem-
15580 plate argument values. If a substitution in a template parameter or
15581 in the function type of the function template results in an invalid
15582 type, type deduction fails. [Note: The equivalent substitution in
15583 exception specifications is done only when the function is instanti-
15584 ated, at which point a program is ill-formed if the substitution
15585 results in an invalid type.] */
15587 static tree
15588 tsubst_function_type (tree t,
15589 tree args,
15590 tsubst_flags_t complain,
15591 tree in_decl)
15593 tree return_type;
15594 tree arg_types = NULL_TREE;
15596 /* The TYPE_CONTEXT is not used for function/method types. */
15597 gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
15599 /* DR 1227: Mixing immediate and non-immediate contexts in deduction
15600 failure. */
15601 bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
15603 if (late_return_type_p)
15605 /* Substitute the argument types. */
15606 arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
15607 complain, in_decl);
15608 if (arg_types == error_mark_node)
15609 return error_mark_node;
15611 tree save_ccp = current_class_ptr;
15612 tree save_ccr = current_class_ref;
15613 tree this_type = (TREE_CODE (t) == METHOD_TYPE
15614 ? TREE_TYPE (TREE_VALUE (arg_types)) : NULL_TREE);
15615 bool do_inject = this_type && CLASS_TYPE_P (this_type);
15616 if (do_inject)
15618 /* DR 1207: 'this' is in scope in the trailing return type. */
15619 inject_this_parameter (this_type, cp_type_quals (this_type));
15622 /* Substitute the return type. */
15623 return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15625 if (do_inject)
15627 current_class_ptr = save_ccp;
15628 current_class_ref = save_ccr;
15631 else
15632 /* Substitute the return type. */
15633 return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15635 if (return_type == error_mark_node)
15636 return error_mark_node;
15637 /* DR 486 clarifies that creation of a function type with an
15638 invalid return type is a deduction failure. */
15639 if (TREE_CODE (return_type) == ARRAY_TYPE
15640 || TREE_CODE (return_type) == FUNCTION_TYPE)
15642 if (complain & tf_error)
15644 if (TREE_CODE (return_type) == ARRAY_TYPE)
15645 error ("function returning an array");
15646 else
15647 error ("function returning a function");
15649 return error_mark_node;
15652 if (!late_return_type_p)
15654 /* Substitute the argument types. */
15655 arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
15656 complain, in_decl);
15657 if (arg_types == error_mark_node)
15658 return error_mark_node;
15661 /* Construct a new type node and return it. */
15662 return rebuild_function_or_method_type (t, return_type, arg_types,
15663 /*raises=*/NULL_TREE, complain);
15666 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE. Substitute the template
15667 ARGS into that specification, and return the substituted
15668 specification. If there is no specification, return NULL_TREE. */
15670 static tree
15671 tsubst_exception_specification (tree fntype,
15672 tree args,
15673 tsubst_flags_t complain,
15674 tree in_decl,
15675 bool defer_ok)
15677 tree specs;
15678 tree new_specs;
15680 specs = TYPE_RAISES_EXCEPTIONS (fntype);
15681 new_specs = NULL_TREE;
15682 if (specs && TREE_PURPOSE (specs))
15684 /* A noexcept-specifier. */
15685 tree expr = TREE_PURPOSE (specs);
15686 if (TREE_CODE (expr) == INTEGER_CST)
15687 new_specs = expr;
15688 else if (defer_ok)
15690 /* Defer instantiation of noexcept-specifiers to avoid
15691 excessive instantiations (c++/49107). */
15692 new_specs = make_node (DEFERRED_NOEXCEPT);
15693 if (DEFERRED_NOEXCEPT_SPEC_P (specs))
15695 /* We already partially instantiated this member template,
15696 so combine the new args with the old. */
15697 DEFERRED_NOEXCEPT_PATTERN (new_specs)
15698 = DEFERRED_NOEXCEPT_PATTERN (expr);
15699 DEFERRED_NOEXCEPT_ARGS (new_specs)
15700 = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
15702 else
15704 DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
15705 DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
15708 else
15710 if (DEFERRED_NOEXCEPT_SPEC_P (specs))
15712 args = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr),
15713 args);
15714 expr = DEFERRED_NOEXCEPT_PATTERN (expr);
15716 new_specs = tsubst_copy_and_build (expr, args, complain, in_decl);
15718 new_specs = build_noexcept_spec (new_specs, complain);
15719 /* We've instantiated a template before a noexcept-specifier
15720 contained therein has been parsed. This can happen for
15721 a nested template class:
15723 struct S {
15724 template<typename> struct B { B() noexcept(...); };
15725 struct A : B<int> { ... use B() ... };
15728 where completing B<int> will trigger instantiating the
15729 noexcept, even though we only parse it at the end of S. */
15730 if (UNPARSED_NOEXCEPT_SPEC_P (specs))
15732 gcc_checking_assert (defer_ok);
15733 vec_safe_push (DEFPARSE_INSTANTIATIONS (expr), new_specs);
15736 else if (specs)
15738 if (! TREE_VALUE (specs))
15739 new_specs = specs;
15740 else
15741 while (specs)
15743 tree spec;
15744 int i, len = 1;
15745 tree expanded_specs = NULL_TREE;
15747 if (PACK_EXPANSION_P (TREE_VALUE (specs)))
15749 /* Expand the pack expansion type. */
15750 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
15751 args, complain,
15752 in_decl);
15754 if (expanded_specs == error_mark_node)
15755 return error_mark_node;
15756 else if (TREE_CODE (expanded_specs) == TREE_VEC)
15757 len = TREE_VEC_LENGTH (expanded_specs);
15758 else
15760 /* We're substituting into a member template, so
15761 we got a TYPE_PACK_EXPANSION back. Add that
15762 expansion and move on. */
15763 gcc_assert (TREE_CODE (expanded_specs)
15764 == TYPE_PACK_EXPANSION);
15765 new_specs = add_exception_specifier (new_specs,
15766 expanded_specs,
15767 complain);
15768 specs = TREE_CHAIN (specs);
15769 continue;
15773 for (i = 0; i < len; ++i)
15775 if (expanded_specs)
15776 spec = TREE_VEC_ELT (expanded_specs, i);
15777 else
15778 spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
15779 if (spec == error_mark_node)
15780 return spec;
15781 new_specs = add_exception_specifier (new_specs, spec,
15782 complain);
15785 specs = TREE_CHAIN (specs);
15788 return new_specs;
15791 /* Substitute through a TREE_LIST of types or expressions, handling pack
15792 expansions. */
15794 tree
15795 tsubst_tree_list (tree t, tree args, tsubst_flags_t complain, tree in_decl)
15797 if (t == void_list_node)
15798 return t;
15800 tree purpose = TREE_PURPOSE (t);
15801 tree purposevec = NULL_TREE;
15802 if (!purpose)
15804 else if (PACK_EXPANSION_P (purpose))
15806 purpose = tsubst_pack_expansion (purpose, args, complain, in_decl);
15807 if (TREE_CODE (purpose) == TREE_VEC)
15808 purposevec = purpose;
15810 else if (TYPE_P (purpose))
15811 purpose = tsubst (purpose, args, complain, in_decl);
15812 else
15813 purpose = tsubst_copy_and_build (purpose, args, complain, in_decl);
15814 if (purpose == error_mark_node || purposevec == error_mark_node)
15815 return error_mark_node;
15817 tree value = TREE_VALUE (t);
15818 tree valuevec = NULL_TREE;
15819 if (!value)
15821 else if (PACK_EXPANSION_P (value))
15823 value = tsubst_pack_expansion (value, args, complain, in_decl);
15824 if (TREE_CODE (value) == TREE_VEC)
15825 valuevec = value;
15827 else if (TYPE_P (value))
15828 value = tsubst (value, args, complain, in_decl);
15829 else
15830 value = tsubst_copy_and_build (value, args, complain, in_decl);
15831 if (value == error_mark_node || valuevec == error_mark_node)
15832 return error_mark_node;
15834 tree chain = TREE_CHAIN (t);
15835 if (!chain)
15837 else if (TREE_CODE (chain) == TREE_LIST)
15838 chain = tsubst_tree_list (chain, args, complain, in_decl);
15839 else if (TYPE_P (chain))
15840 chain = tsubst (chain, args, complain, in_decl);
15841 else
15842 chain = tsubst_copy_and_build (chain, args, complain, in_decl);
15843 if (chain == error_mark_node)
15844 return error_mark_node;
15846 if (purpose == TREE_PURPOSE (t)
15847 && value == TREE_VALUE (t)
15848 && chain == TREE_CHAIN (t))
15849 return t;
15851 int len;
15852 /* Determine the number of arguments. */
15853 if (purposevec)
15855 len = TREE_VEC_LENGTH (purposevec);
15856 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
15858 else if (valuevec)
15859 len = TREE_VEC_LENGTH (valuevec);
15860 else
15861 len = 1;
15863 for (int i = len; i-- > 0; )
15865 if (purposevec)
15866 purpose = TREE_VEC_ELT (purposevec, i);
15867 if (valuevec)
15868 value = TREE_VEC_ELT (valuevec, i);
15870 if (value && TYPE_P (value))
15871 chain = hash_tree_cons (purpose, value, chain);
15872 else
15873 chain = tree_cons (purpose, value, chain);
15876 return chain;
15879 /* Take the tree structure T and replace template parameters used
15880 therein with the argument vector ARGS. IN_DECL is an associated
15881 decl for diagnostics. If an error occurs, returns ERROR_MARK_NODE.
15882 Issue error and warning messages under control of COMPLAIN. Note
15883 that we must be relatively non-tolerant of extensions here, in
15884 order to preserve conformance; if we allow substitutions that
15885 should not be allowed, we may allow argument deductions that should
15886 not succeed, and therefore report ambiguous overload situations
15887 where there are none. In theory, we could allow the substitution,
15888 but indicate that it should have failed, and allow our caller to
15889 make sure that the right thing happens, but we don't try to do this
15890 yet.
15892 This function is used for dealing with types, decls and the like;
15893 for expressions, use tsubst_expr or tsubst_copy. */
15895 tree
15896 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
15898 enum tree_code code;
15899 tree type, r = NULL_TREE;
15901 if (t == NULL_TREE || t == error_mark_node
15902 || t == integer_type_node
15903 || t == void_type_node
15904 || t == char_type_node
15905 || t == unknown_type_node
15906 || TREE_CODE (t) == NAMESPACE_DECL
15907 || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
15908 return t;
15910 tsubst_flags_t tst_ok_flag = (complain & tf_tst_ok);
15911 complain &= ~tf_tst_ok;
15913 tsubst_flags_t qualifying_scope_flag = (complain & tf_qualifying_scope);
15914 complain &= ~tf_qualifying_scope;
15916 if (DECL_P (t))
15917 return tsubst_decl (t, args, complain);
15919 if (args == NULL_TREE)
15920 return t;
15922 code = TREE_CODE (t);
15924 gcc_assert (code != IDENTIFIER_NODE);
15925 type = TREE_TYPE (t);
15927 gcc_assert (type != unknown_type_node);
15929 if (tree d = maybe_dependent_member_ref (t, args, complain, in_decl))
15930 return d;
15932 /* Reuse typedefs. We need to do this to handle dependent attributes,
15933 such as attribute aligned. */
15934 if (TYPE_P (t)
15935 && typedef_variant_p (t))
15937 tree decl = TYPE_NAME (t);
15939 if (alias_template_specialization_p (t, nt_opaque))
15941 /* DECL represents an alias template and we want to
15942 instantiate it. */
15943 tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15944 tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
15945 r = instantiate_alias_template (tmpl, gen_args, complain);
15947 else if (DECL_CLASS_SCOPE_P (decl)
15948 && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
15949 && uses_template_parms (DECL_CONTEXT (decl)))
15951 tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15952 tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
15953 r = retrieve_specialization (tmpl, gen_args, 0);
15955 else if (DECL_FUNCTION_SCOPE_P (decl)
15956 && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
15957 && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
15958 r = retrieve_local_specialization (decl);
15959 else
15960 /* The typedef is from a non-template context. */
15961 return t;
15963 if (r)
15965 r = TREE_TYPE (r);
15966 r = cp_build_qualified_type
15967 (r, cp_type_quals (t) | cp_type_quals (r),
15968 complain | tf_ignore_bad_quals);
15969 return r;
15971 else
15973 /* We don't have an instantiation yet, so drop the typedef. */
15974 int quals = cp_type_quals (t);
15975 t = DECL_ORIGINAL_TYPE (decl);
15976 t = cp_build_qualified_type (t, quals,
15977 complain | tf_ignore_bad_quals);
15981 bool fndecl_type = (complain & tf_fndecl_type);
15982 complain &= ~tf_fndecl_type;
15984 if (type
15985 && code != TYPENAME_TYPE
15986 && code != TEMPLATE_TYPE_PARM
15987 && code != TEMPLATE_PARM_INDEX
15988 && code != IDENTIFIER_NODE
15989 && code != FUNCTION_TYPE
15990 && code != METHOD_TYPE)
15991 type = tsubst (type, args, complain, in_decl);
15992 if (type == error_mark_node)
15993 return error_mark_node;
15995 switch (code)
15997 case RECORD_TYPE:
15998 if (TYPE_PTRMEMFUNC_P (t))
15999 return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
16000 /* Fall through. */
16001 case UNION_TYPE:
16002 case ENUMERAL_TYPE:
16003 return tsubst_aggr_type_1 (t, args, complain, in_decl,
16004 /*entering_scope=*/0);
16006 case ERROR_MARK:
16007 case IDENTIFIER_NODE:
16008 case VOID_TYPE:
16009 case OPAQUE_TYPE:
16010 case REAL_TYPE:
16011 case COMPLEX_TYPE:
16012 case VECTOR_TYPE:
16013 case BOOLEAN_TYPE:
16014 case NULLPTR_TYPE:
16015 case LANG_TYPE:
16016 return t;
16018 case INTEGER_TYPE:
16019 if (t == integer_type_node)
16020 return t;
16022 if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
16023 && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
16024 return t;
16027 tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
16029 max = tsubst_expr (omax, args, complain, in_decl);
16031 /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
16032 needed. */
16033 if (TREE_CODE (max) == NOP_EXPR
16034 && TREE_SIDE_EFFECTS (omax)
16035 && !TREE_TYPE (max))
16036 TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
16038 /* If we're in a partial instantiation, preserve the magic NOP_EXPR
16039 with TREE_SIDE_EFFECTS that indicates this is not an integral
16040 constant expression. */
16041 if (processing_template_decl
16042 && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
16044 gcc_assert (TREE_CODE (max) == NOP_EXPR);
16045 TREE_SIDE_EFFECTS (max) = 1;
16048 return compute_array_index_type (NULL_TREE, max, complain);
16051 case TEMPLATE_TYPE_PARM:
16052 if (template_placeholder_p (t))
16054 tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (t);
16055 tmpl = tsubst_copy (tmpl, args, complain, in_decl);
16056 if (TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
16057 tmpl = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (tmpl);
16059 if (tmpl != CLASS_PLACEHOLDER_TEMPLATE (t))
16060 return make_template_placeholder (tmpl);
16061 else
16062 return t;
16064 /* Fall through. */
16065 case TEMPLATE_TEMPLATE_PARM:
16066 case BOUND_TEMPLATE_TEMPLATE_PARM:
16067 case TEMPLATE_PARM_INDEX:
16069 int idx;
16070 int level;
16071 int levels;
16072 tree arg = NULL_TREE;
16074 r = NULL_TREE;
16076 gcc_assert (TREE_VEC_LENGTH (args) > 0);
16077 template_parm_level_and_index (t, &level, &idx);
16079 levels = TMPL_ARGS_DEPTH (args);
16080 if (level <= levels
16081 && TREE_VEC_LENGTH (TMPL_ARGS_LEVEL (args, level)) > 0)
16083 arg = TMPL_ARG (args, level, idx);
16085 /* See through ARGUMENT_PACK_SELECT arguments. */
16086 if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
16087 arg = argument_pack_select_arg (arg);
16090 if (arg == error_mark_node)
16091 return error_mark_node;
16092 else if (arg != NULL_TREE)
16094 if (ARGUMENT_PACK_P (arg))
16095 /* If ARG is an argument pack, we don't actually want to
16096 perform a substitution here, because substitutions
16097 for argument packs are only done
16098 element-by-element. We can get to this point when
16099 substituting the type of a non-type template
16100 parameter pack, when that type actually contains
16101 template parameter packs from an outer template, e.g.,
16103 template<typename... Types> struct A {
16104 template<Types... Values> struct B { };
16105 }; */
16106 return t;
16108 if (code == TEMPLATE_TYPE_PARM)
16110 int quals;
16112 /* When building concept checks for the purpose of
16113 deducing placeholders, we can end up with wildcards
16114 where types are expected. Adjust this to the deduced
16115 value. */
16116 if (TREE_CODE (arg) == WILDCARD_DECL)
16117 arg = TREE_TYPE (TREE_TYPE (arg));
16119 gcc_assert (TYPE_P (arg));
16121 quals = cp_type_quals (arg) | cp_type_quals (t);
16123 return cp_build_qualified_type
16124 (arg, quals, complain | tf_ignore_bad_quals);
16126 else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
16128 /* We are processing a type constructed from a
16129 template template parameter. */
16130 tree argvec = tsubst (TYPE_TI_ARGS (t),
16131 args, complain, in_decl);
16132 if (argvec == error_mark_node)
16133 return error_mark_node;
16135 gcc_assert (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
16136 || TREE_CODE (arg) == TEMPLATE_DECL
16137 || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
16139 if (TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
16140 /* Consider this code:
16142 template <template <class> class Template>
16143 struct Internal {
16144 template <class Arg> using Bind = Template<Arg>;
16147 template <template <class> class Template, class Arg>
16148 using Instantiate = Template<Arg>; //#0
16150 template <template <class> class Template,
16151 class Argument>
16152 using Bind =
16153 Instantiate<Internal<Template>::template Bind,
16154 Argument>; //#1
16156 When #1 is parsed, the
16157 BOUND_TEMPLATE_TEMPLATE_PARM representing the
16158 parameter `Template' in #0 matches the
16159 UNBOUND_CLASS_TEMPLATE representing the argument
16160 `Internal<Template>::template Bind'; We then want
16161 to assemble the type `Bind<Argument>' that can't
16162 be fully created right now, because
16163 `Internal<Template>' not being complete, the Bind
16164 template cannot be looked up in that context. So
16165 we need to "store" `Bind<Argument>' for later
16166 when the context of Bind becomes complete. Let's
16167 store that in a TYPENAME_TYPE. */
16168 return make_typename_type (TYPE_CONTEXT (arg),
16169 build_nt (TEMPLATE_ID_EXPR,
16170 TYPE_IDENTIFIER (arg),
16171 argvec),
16172 typename_type,
16173 complain);
16175 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
16176 are resolving nested-types in the signature of a
16177 member function templates. Otherwise ARG is a
16178 TEMPLATE_DECL and is the real template to be
16179 instantiated. */
16180 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
16181 arg = TYPE_NAME (arg);
16183 r = lookup_template_class (arg,
16184 argvec, in_decl,
16185 DECL_CONTEXT (arg),
16186 /*entering_scope=*/0,
16187 complain);
16188 return cp_build_qualified_type
16189 (r, cp_type_quals (t) | cp_type_quals (r), complain);
16191 else if (code == TEMPLATE_TEMPLATE_PARM)
16192 return arg;
16193 else
16194 /* TEMPLATE_PARM_INDEX. */
16195 return convert_from_reference (unshare_expr (arg));
16198 if (level == 1)
16199 /* This can happen during the attempted tsubst'ing in
16200 unify. This means that we don't yet have any information
16201 about the template parameter in question. */
16202 return t;
16204 /* Early in template argument deduction substitution, we don't
16205 want to reduce the level of 'auto', or it will be confused
16206 with a normal template parm in subsequent deduction.
16207 Similarly, don't reduce the level of template parameters to
16208 avoid mismatches when deducing their types. */
16209 if (complain & tf_partial)
16210 return t;
16212 /* If we get here, we must have been looking at a parm for a
16213 more deeply nested template. Make a new version of this
16214 template parameter, but with a lower level. */
16215 int quals;
16216 switch (code)
16218 case TEMPLATE_TYPE_PARM:
16219 case TEMPLATE_TEMPLATE_PARM:
16220 quals = cp_type_quals (t);
16221 if (quals)
16223 gcc_checking_assert (code == TEMPLATE_TYPE_PARM);
16224 t = TYPE_MAIN_VARIANT (t);
16227 if (tree d = TEMPLATE_TYPE_DESCENDANTS (t))
16228 if (TEMPLATE_PARM_LEVEL (d) == TEMPLATE_TYPE_LEVEL (t) - levels
16229 && (code == TEMPLATE_TYPE_PARM
16230 || TEMPLATE_TEMPLATE_PARM_SIMPLE_P (t)))
16231 /* Cache lowering a type parameter or a simple template
16232 template parameter. */
16233 r = TREE_TYPE (d);
16235 if (!r)
16237 r = copy_type (t);
16238 TEMPLATE_TYPE_PARM_INDEX (r)
16239 = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
16240 r, levels, args, complain);
16241 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
16242 TYPE_MAIN_VARIANT (r) = r;
16243 TYPE_POINTER_TO (r) = NULL_TREE;
16244 TYPE_REFERENCE_TO (r) = NULL_TREE;
16246 if (code == TEMPLATE_TYPE_PARM)
16247 if (tree ci = PLACEHOLDER_TYPE_CONSTRAINTS_INFO (t))
16248 /* Propagate constraints on placeholders since they are
16249 only instantiated during satisfaction. */
16250 PLACEHOLDER_TYPE_CONSTRAINTS_INFO (r) = ci;
16252 if (TYPE_STRUCTURAL_EQUALITY_P (t))
16253 SET_TYPE_STRUCTURAL_EQUALITY (r);
16254 else
16255 TYPE_CANONICAL (r) = canonical_type_parameter (r);
16258 if (quals)
16259 r = cp_build_qualified_type (r, quals,
16260 complain | tf_ignore_bad_quals);
16261 break;
16263 case BOUND_TEMPLATE_TEMPLATE_PARM:
16265 tree tinfo = TYPE_TEMPLATE_INFO (t);
16266 /* We might need to substitute into the types of non-type
16267 template parameters. This also lowers the level of
16268 the ttp appropriately. */
16269 tree tmpl = tsubst (TI_TEMPLATE (tinfo), args,
16270 complain, in_decl);
16271 if (tmpl == error_mark_node)
16272 return error_mark_node;
16273 tree argvec = tsubst (TI_ARGS (tinfo), args,
16274 complain, in_decl);
16275 if (argvec == error_mark_node)
16276 return error_mark_node;
16277 r = lookup_template_class (tmpl, argvec, in_decl, NULL_TREE,
16278 /*entering_scope=*/false, complain);
16279 r = cp_build_qualified_type (r, cp_type_quals (t), complain);
16280 break;
16283 case TEMPLATE_PARM_INDEX:
16284 /* OK, now substitute the type of the non-type parameter. We
16285 couldn't do it earlier because it might be an auto parameter,
16286 and we wouldn't need to if we had an argument. */
16287 type = tsubst (type, args, complain, in_decl);
16288 if (type == error_mark_node)
16289 return error_mark_node;
16290 r = reduce_template_parm_level (t, type, levels, args, complain);
16291 break;
16293 default:
16294 gcc_unreachable ();
16297 return r;
16300 case TREE_LIST:
16301 return tsubst_tree_list (t, args, complain, in_decl);
16303 case TREE_BINFO:
16304 /* We should never be tsubsting a binfo. */
16305 gcc_unreachable ();
16307 case TREE_VEC:
16308 /* A vector of template arguments. */
16309 gcc_assert (!type);
16310 return tsubst_template_args (t, args, complain, in_decl);
16312 case POINTER_TYPE:
16313 case REFERENCE_TYPE:
16315 if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
16316 return t;
16318 /* [temp.deduct]
16320 Type deduction may fail for any of the following
16321 reasons:
16323 -- Attempting to create a pointer to reference type.
16324 -- Attempting to create a reference to a reference type or
16325 a reference to void.
16327 Core issue 106 says that creating a reference to a reference
16328 during instantiation is no longer a cause for failure. We
16329 only enforce this check in strict C++98 mode. */
16330 if ((TYPE_REF_P (type)
16331 && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
16332 || (code == REFERENCE_TYPE && VOID_TYPE_P (type)))
16334 static location_t last_loc;
16336 /* We keep track of the last time we issued this error
16337 message to avoid spewing a ton of messages during a
16338 single bad template instantiation. */
16339 if (complain & tf_error
16340 && last_loc != input_location)
16342 if (VOID_TYPE_P (type))
16343 error ("forming reference to void");
16344 else if (code == POINTER_TYPE)
16345 error ("forming pointer to reference type %qT", type);
16346 else
16347 error ("forming reference to reference type %qT", type);
16348 last_loc = input_location;
16351 return error_mark_node;
16353 else if (TREE_CODE (type) == FUNCTION_TYPE
16354 && (type_memfn_quals (type) != TYPE_UNQUALIFIED
16355 || type_memfn_rqual (type) != REF_QUAL_NONE))
16357 if (complain & tf_error)
16359 if (code == POINTER_TYPE)
16360 error ("forming pointer to qualified function type %qT",
16361 type);
16362 else
16363 error ("forming reference to qualified function type %qT",
16364 type);
16366 return error_mark_node;
16368 else if (code == POINTER_TYPE)
16370 r = build_pointer_type (type);
16371 if (TREE_CODE (type) == METHOD_TYPE)
16372 r = build_ptrmemfunc_type (r);
16374 else if (TYPE_REF_P (type))
16375 /* In C++0x, during template argument substitution, when there is an
16376 attempt to create a reference to a reference type, reference
16377 collapsing is applied as described in [14.3.1/4 temp.arg.type]:
16379 "If a template-argument for a template-parameter T names a type
16380 that is a reference to a type A, an attempt to create the type
16381 'lvalue reference to cv T' creates the type 'lvalue reference to
16382 A,' while an attempt to create the type type rvalue reference to
16383 cv T' creates the type T"
16385 r = cp_build_reference_type
16386 (TREE_TYPE (type),
16387 TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
16388 else
16389 r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
16390 r = cp_build_qualified_type (r, cp_type_quals (t), complain);
16392 if (r != error_mark_node)
16393 /* Will this ever be needed for TYPE_..._TO values? */
16394 layout_type (r);
16396 return r;
16398 case OFFSET_TYPE:
16400 r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
16401 if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
16403 /* [temp.deduct]
16405 Type deduction may fail for any of the following
16406 reasons:
16408 -- Attempting to create "pointer to member of T" when T
16409 is not a class type. */
16410 if (complain & tf_error)
16411 error ("creating pointer to member of non-class type %qT", r);
16412 return error_mark_node;
16414 if (TYPE_REF_P (type))
16416 if (complain & tf_error)
16417 error ("creating pointer to member reference type %qT", type);
16418 return error_mark_node;
16420 if (VOID_TYPE_P (type))
16422 if (complain & tf_error)
16423 error ("creating pointer to member of type void");
16424 return error_mark_node;
16426 gcc_assert (TREE_CODE (type) != METHOD_TYPE);
16427 if (TREE_CODE (type) == FUNCTION_TYPE)
16429 /* The type of the implicit object parameter gets its
16430 cv-qualifiers from the FUNCTION_TYPE. */
16431 tree memptr;
16432 tree method_type
16433 = build_memfn_type (type, r, type_memfn_quals (type),
16434 type_memfn_rqual (type));
16435 memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
16436 return cp_build_qualified_type (memptr, cp_type_quals (t),
16437 complain);
16439 else
16440 return cp_build_qualified_type (build_ptrmem_type (r, type),
16441 cp_type_quals (t),
16442 complain);
16444 case FUNCTION_TYPE:
16445 case METHOD_TYPE:
16447 tree fntype;
16448 tree specs;
16449 fntype = tsubst_function_type (t, args, complain, in_decl);
16450 if (fntype == error_mark_node)
16451 return error_mark_node;
16453 /* Substitute the exception specification. */
16454 specs = tsubst_exception_specification (t, args, complain, in_decl,
16455 /*defer_ok*/fndecl_type);
16456 if (specs == error_mark_node)
16457 return error_mark_node;
16458 if (specs)
16459 fntype = build_exception_variant (fntype, specs);
16460 return fntype;
16462 case ARRAY_TYPE:
16464 tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
16465 if (domain == error_mark_node)
16466 return error_mark_node;
16468 /* As an optimization, we avoid regenerating the array type if
16469 it will obviously be the same as T. */
16470 if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
16471 return t;
16473 /* These checks should match the ones in create_array_type_for_decl.
16475 [temp.deduct]
16477 The deduction may fail for any of the following reasons:
16479 -- Attempting to create an array with an element type that
16480 is void, a function type, or a reference type, or [DR337]
16481 an abstract class type. */
16482 if (VOID_TYPE_P (type)
16483 || TREE_CODE (type) == FUNCTION_TYPE
16484 || (TREE_CODE (type) == ARRAY_TYPE
16485 && TYPE_DOMAIN (type) == NULL_TREE)
16486 || TYPE_REF_P (type))
16488 if (complain & tf_error)
16489 error ("creating array of %qT", type);
16490 return error_mark_node;
16493 if (!verify_type_context (input_location, TCTX_ARRAY_ELEMENT, type,
16494 !(complain & tf_error)))
16495 return error_mark_node;
16497 r = build_cplus_array_type (type, domain);
16499 if (!valid_array_size_p (input_location, r, in_decl,
16500 (complain & tf_error)))
16501 return error_mark_node;
16503 if (TYPE_USER_ALIGN (t))
16505 SET_TYPE_ALIGN (r, TYPE_ALIGN (t));
16506 TYPE_USER_ALIGN (r) = 1;
16509 return r;
16512 case TYPENAME_TYPE:
16514 tree ctx = TYPE_CONTEXT (t);
16515 if (TREE_CODE (ctx) == TYPE_PACK_EXPANSION)
16517 ctx = tsubst_pack_expansion (ctx, args,
16518 complain | tf_qualifying_scope,
16519 in_decl);
16520 if (ctx == error_mark_node
16521 || TREE_VEC_LENGTH (ctx) > 1)
16522 return error_mark_node;
16523 if (TREE_VEC_LENGTH (ctx) == 0)
16525 if (complain & tf_error)
16526 error ("%qD is instantiated for an empty pack",
16527 TYPENAME_TYPE_FULLNAME (t));
16528 return error_mark_node;
16530 ctx = TREE_VEC_ELT (ctx, 0);
16532 else
16533 ctx = tsubst_aggr_type (ctx, args,
16534 complain | tf_qualifying_scope,
16535 in_decl, /*entering_scope=*/1);
16536 if (ctx == error_mark_node)
16537 return error_mark_node;
16539 tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
16540 complain, in_decl);
16541 if (f == error_mark_node)
16542 return error_mark_node;
16544 if (!MAYBE_CLASS_TYPE_P (ctx))
16546 if (complain & tf_error)
16547 error ("%qT is not a class, struct, or union type", ctx);
16548 return error_mark_node;
16550 else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
16552 /* Normally, make_typename_type does not require that the CTX
16553 have complete type in order to allow things like:
16555 template <class T> struct S { typename S<T>::X Y; };
16557 But, such constructs have already been resolved by this
16558 point, so here CTX really should have complete type, unless
16559 it's a partial instantiation. */
16560 if (!complete_type_or_maybe_complain (ctx, NULL_TREE, complain))
16561 return error_mark_node;
16564 /* FIXME: TYPENAME_IS_CLASS_P conflates 'class' vs 'struct' vs 'union'
16565 tags. TYPENAME_TYPE should probably remember the exact tag that
16566 was written. */
16567 enum tag_types tag_type
16568 = TYPENAME_IS_CLASS_P (t) ? class_type
16569 : TYPENAME_IS_ENUM_P (t) ? enum_type
16570 : typename_type;
16571 tsubst_flags_t tcomplain = complain | tf_keep_type_decl;
16572 tcomplain |= tst_ok_flag | qualifying_scope_flag;
16573 f = make_typename_type (ctx, f, tag_type, tcomplain);
16574 if (f == error_mark_node)
16575 return f;
16576 if (TREE_CODE (f) == TYPE_DECL)
16578 complain |= tf_ignore_bad_quals;
16579 f = TREE_TYPE (f);
16582 if (TREE_CODE (f) != TYPENAME_TYPE)
16584 if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
16586 if (complain & tf_error)
16587 error ("%qT resolves to %qT, which is not an enumeration type",
16588 t, f);
16589 else
16590 return error_mark_node;
16592 else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
16594 if (complain & tf_error)
16595 error ("%qT resolves to %qT, which is not a class type",
16596 t, f);
16597 else
16598 return error_mark_node;
16602 return cp_build_qualified_type
16603 (f, cp_type_quals (f) | cp_type_quals (t), complain);
16606 case UNBOUND_CLASS_TEMPLATE:
16608 tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
16609 in_decl, /*entering_scope=*/1);
16610 tree name = TYPE_IDENTIFIER (t);
16611 tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
16613 if (ctx == error_mark_node || name == error_mark_node)
16614 return error_mark_node;
16616 if (parm_list)
16617 parm_list = tsubst_template_parms (parm_list, args, complain);
16618 return make_unbound_class_template (ctx, name, parm_list, complain);
16621 case TYPEOF_TYPE:
16623 tree type;
16625 ++cp_unevaluated_operand;
16626 ++c_inhibit_evaluation_warnings;
16628 type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args, complain, in_decl);
16630 --cp_unevaluated_operand;
16631 --c_inhibit_evaluation_warnings;
16633 type = finish_typeof (type);
16634 return cp_build_qualified_type (type,
16635 cp_type_quals (t)
16636 | cp_type_quals (type),
16637 complain);
16640 case DECLTYPE_TYPE:
16642 tree type;
16644 ++cp_unevaluated_operand;
16645 ++c_inhibit_evaluation_warnings;
16647 type = tsubst_copy_and_build (DECLTYPE_TYPE_EXPR (t), args,
16648 complain|tf_decltype, in_decl);
16650 --cp_unevaluated_operand;
16651 --c_inhibit_evaluation_warnings;
16653 if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
16654 type = lambda_capture_field_type (type,
16655 false /*explicit_init*/,
16656 DECLTYPE_FOR_REF_CAPTURE (t));
16657 else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
16658 type = lambda_proxy_type (type);
16659 else
16661 bool id = DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t);
16662 if (id && TREE_CODE (DECLTYPE_TYPE_EXPR (t)) == BIT_NOT_EXPR
16663 && EXPR_P (type))
16664 /* In a template ~id could be either a complement expression
16665 or an unqualified-id naming a destructor; if instantiating
16666 it produces an expression, it's not an id-expression or
16667 member access. */
16668 id = false;
16669 type = finish_decltype_type (type, id, complain);
16671 return cp_build_qualified_type (type,
16672 cp_type_quals (t)
16673 | cp_type_quals (type),
16674 complain | tf_ignore_bad_quals);
16677 case TRAIT_TYPE:
16679 tree type1 = TRAIT_TYPE_TYPE1 (t);
16680 if (TYPE_P (type1))
16681 type1 = tsubst (type1, args, complain, in_decl);
16682 else
16683 type1 = tsubst_copy_and_build (type1, args, complain, in_decl);
16684 tree type2 = tsubst (TRAIT_TYPE_TYPE2 (t), args, complain, in_decl);
16685 type = finish_trait_type (TRAIT_TYPE_KIND (t), type1, type2, complain);
16686 return cp_build_qualified_type (type,
16687 cp_type_quals (t) | cp_type_quals (type),
16688 complain | tf_ignore_bad_quals);
16691 case TYPE_ARGUMENT_PACK:
16692 case NONTYPE_ARGUMENT_PACK:
16693 return tsubst_argument_pack (t, args, complain, in_decl);
16695 case VOID_CST:
16696 case INTEGER_CST:
16697 case REAL_CST:
16698 case STRING_CST:
16699 case PLUS_EXPR:
16700 case MINUS_EXPR:
16701 case NEGATE_EXPR:
16702 case NOP_EXPR:
16703 case INDIRECT_REF:
16704 case ADDR_EXPR:
16705 case CALL_EXPR:
16706 case ARRAY_REF:
16707 case SCOPE_REF:
16708 /* We should use one of the expression tsubsts for these codes. */
16709 gcc_unreachable ();
16711 default:
16712 sorry ("use of %qs in template", get_tree_code_name (code));
16713 return error_mark_node;
16717 /* Convenience wrapper over tsubst for substituting into the LHS
16718 of the :: scope resolution operator. */
16720 static tree
16721 tsubst_scope (tree t, tree args, tsubst_flags_t complain, tree in_decl)
16723 gcc_checking_assert (TYPE_P (t));
16724 return tsubst (t, args, complain | tf_qualifying_scope, in_decl);
16727 /* OLDFNS is a lookup set of member functions from some class template, and
16728 NEWFNS is a lookup set of member functions from NEWTYPE, a specialization
16729 of that class template. Return the subset of NEWFNS which are
16730 specializations of a function from OLDFNS. */
16732 static tree
16733 filter_memfn_lookup (tree oldfns, tree newfns, tree newtype)
16735 /* Record all member functions from the old lookup set OLDFNS into
16736 VISIBLE_SET. */
16737 hash_set<tree> visible_set;
16738 bool seen_dep_using = false;
16739 for (tree fn : lkp_range (oldfns))
16741 if (TREE_CODE (fn) == USING_DECL)
16743 /* Imprecisely handle dependent using-decl by keeping all members
16744 in the new lookup set that are defined in a base class, i.e.
16745 members that could plausibly have been introduced by this
16746 dependent using-decl.
16747 FIXME: Track which members are introduced by a dependent
16748 using-decl precisely, perhaps by performing another lookup
16749 from the substituted USING_DECL_SCOPE. */
16750 gcc_checking_assert (DECL_DEPENDENT_P (fn));
16751 seen_dep_using = true;
16753 else
16754 visible_set.add (fn);
16757 /* Returns true iff (a less specialized version of) FN appeared in
16758 the old lookup set OLDFNS. */
16759 auto visible_p = [newtype, seen_dep_using, &visible_set] (tree fn) {
16760 if (DECL_CONTEXT (fn) != newtype)
16761 /* FN is a member function from a base class, introduced via a
16762 using-decl; if it might have been introduced by a dependent
16763 using-decl then just conservatively keep it, otherwise look
16764 in the old lookup set for FN exactly. */
16765 return seen_dep_using || visible_set.contains (fn);
16766 else if (TREE_CODE (fn) == TEMPLATE_DECL)
16767 /* FN is a member function template from the current class;
16768 look in the old lookup set for the TEMPLATE_DECL from which
16769 it was specialized. */
16770 return visible_set.contains (DECL_TI_TEMPLATE (fn));
16771 else
16772 /* FN is a non-template member function from the current class;
16773 look in the old lookup set for the FUNCTION_DECL from which
16774 it was specialized. */
16775 return visible_set.contains (DECL_TEMPLATE_RESULT
16776 (DECL_TI_TEMPLATE (fn)));
16779 bool lookup_changed_p = false;
16780 for (tree fn : lkp_range (newfns))
16781 if (!visible_p (fn))
16783 lookup_changed_p = true;
16784 break;
16786 if (!lookup_changed_p)
16787 return newfns;
16789 /* Filter out from NEWFNS the member functions that weren't
16790 previously visible according to OLDFNS. */
16791 tree filtered_fns = NULL_TREE;
16792 unsigned filtered_size = 0;
16793 for (tree fn : lkp_range (newfns))
16794 if (visible_p (fn))
16796 filtered_fns = lookup_add (fn, filtered_fns);
16797 filtered_size++;
16799 gcc_checking_assert (seen_dep_using
16800 ? filtered_size >= visible_set.elements ()
16801 : filtered_size == visible_set.elements ());
16803 return filtered_fns;
16806 /* tsubst a BASELINK. OBJECT_TYPE, if non-NULL, is the type of the
16807 expression on the left-hand side of the "." or "->" operator. We
16808 only do the lookup if we had a dependent BASELINK. Otherwise we
16809 adjust it onto the instantiated heirarchy. */
16811 static tree
16812 tsubst_baselink (tree baselink, tree object_type,
16813 tree args, tsubst_flags_t complain, tree in_decl)
16815 bool qualified_p = BASELINK_QUALIFIED_P (baselink);
16816 tree qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
16817 qualifying_scope = tsubst (qualifying_scope, args, complain, in_decl);
16819 tree optype = BASELINK_OPTYPE (baselink);
16820 optype = tsubst (optype, args, complain, in_decl);
16822 tree template_args = NULL_TREE;
16823 bool template_id_p = false;
16824 tree fns = BASELINK_FUNCTIONS (baselink);
16825 if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
16827 template_id_p = true;
16828 template_args = TREE_OPERAND (fns, 1);
16829 fns = TREE_OPERAND (fns, 0);
16830 if (template_args)
16831 template_args = tsubst_template_args (template_args, args,
16832 complain, in_decl);
16835 tree binfo_type = BINFO_TYPE (BASELINK_BINFO (baselink));
16836 binfo_type = tsubst (binfo_type, args, complain, in_decl);
16837 bool dependent_p = (binfo_type != BINFO_TYPE (BASELINK_BINFO (baselink))
16838 || optype != BASELINK_OPTYPE (baselink));
16840 if (dependent_p)
16842 tree name = OVL_NAME (fns);
16843 if (IDENTIFIER_CONV_OP_P (name))
16844 name = make_conv_op_name (optype);
16846 /* See maybe_dependent_member_ref. */
16847 if ((complain & tf_dguide) && dependent_scope_p (qualifying_scope))
16849 if (template_id_p)
16850 name = build2 (TEMPLATE_ID_EXPR, unknown_type_node, name,
16851 template_args);
16852 return build_qualified_name (NULL_TREE, qualifying_scope, name,
16853 /* ::template */false);
16856 if (name == complete_dtor_identifier)
16857 /* Treat as-if non-dependent below. */
16858 dependent_p = false;
16860 bool maybe_incomplete = BASELINK_FUNCTIONS_MAYBE_INCOMPLETE_P (baselink);
16861 baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1,
16862 complain);
16863 if (maybe_incomplete)
16865 /* Filter out from the new lookup set those functions which didn't
16866 appear in the original lookup set (in a less specialized form).
16867 This is needed to preserve the consistency of member lookup
16868 performed in an incomplete-class context, within which
16869 later-declared members ought to remain invisible. */
16870 BASELINK_FUNCTIONS (baselink)
16871 = filter_memfn_lookup (fns, BASELINK_FUNCTIONS (baselink),
16872 binfo_type);
16873 BASELINK_FUNCTIONS_MAYBE_INCOMPLETE_P (baselink) = true;
16876 if (!baselink)
16878 if ((complain & tf_error)
16879 && constructor_name_p (name, qualifying_scope))
16880 error ("cannot call constructor %<%T::%D%> directly",
16881 qualifying_scope, name);
16882 return error_mark_node;
16885 fns = BASELINK_FUNCTIONS (baselink);
16887 else
16889 /* We're going to overwrite pieces below, make a duplicate. */
16890 baselink = copy_node (baselink);
16892 if (qualifying_scope != BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink)))
16894 /* The decl we found was from non-dependent scope, but we still need
16895 to update the binfos for the instantiated qualifying_scope. */
16896 BASELINK_ACCESS_BINFO (baselink) = TYPE_BINFO (qualifying_scope);
16897 BASELINK_BINFO (baselink) = lookup_base (qualifying_scope, binfo_type,
16898 ba_unique, nullptr, complain);
16902 /* If lookup found a single function, mark it as used at this point.
16903 (If lookup found multiple functions the one selected later by
16904 overload resolution will be marked as used at that point.) */
16905 if (!template_id_p && !really_overloaded_fn (fns))
16907 tree fn = OVL_FIRST (fns);
16908 bool ok = mark_used (fn, complain);
16909 if (!ok && !(complain & tf_error))
16910 return error_mark_node;
16911 if (ok && BASELINK_P (baselink))
16912 /* We might have instantiated an auto function. */
16913 TREE_TYPE (baselink) = TREE_TYPE (fn);
16916 if (BASELINK_P (baselink))
16918 /* Add back the template arguments, if present. */
16919 if (template_id_p)
16920 BASELINK_FUNCTIONS (baselink)
16921 = build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, template_args);
16923 /* Update the conversion operator type. */
16924 BASELINK_OPTYPE (baselink) = optype;
16927 if (!object_type)
16928 object_type = current_class_type;
16930 if (qualified_p || !dependent_p)
16932 baselink = adjust_result_of_qualified_name_lookup (baselink,
16933 qualifying_scope,
16934 object_type);
16935 if (!qualified_p)
16936 /* We need to call adjust_result_of_qualified_name_lookup in case the
16937 destructor names a base class, but we unset BASELINK_QUALIFIED_P
16938 so that we still get virtual function binding. */
16939 BASELINK_QUALIFIED_P (baselink) = false;
16942 return baselink;
16945 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID. DONE is
16946 true if the qualified-id will be a postfix-expression in-and-of
16947 itself; false if more of the postfix-expression follows the
16948 QUALIFIED_ID. ADDRESS_P is true if the qualified-id is the operand
16949 of "&". */
16951 static tree
16952 tsubst_qualified_id (tree qualified_id, tree args,
16953 tsubst_flags_t complain, tree in_decl,
16954 bool done, bool address_p)
16956 tree expr;
16957 tree scope;
16958 tree name;
16959 bool is_template;
16960 tree template_args;
16961 location_t loc = EXPR_LOCATION (qualified_id);
16963 gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
16965 /* Figure out what name to look up. */
16966 name = TREE_OPERAND (qualified_id, 1);
16967 if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
16969 is_template = true;
16970 template_args = TREE_OPERAND (name, 1);
16971 if (template_args)
16972 template_args = tsubst_template_args (template_args, args,
16973 complain, in_decl);
16974 if (template_args == error_mark_node)
16975 return error_mark_node;
16976 name = TREE_OPERAND (name, 0);
16978 else
16980 is_template = false;
16981 template_args = NULL_TREE;
16984 /* Substitute into the qualifying scope. When there are no ARGS, we
16985 are just trying to simplify a non-dependent expression. In that
16986 case the qualifying scope may be dependent, and, in any case,
16987 substituting will not help. */
16988 scope = TREE_OPERAND (qualified_id, 0);
16989 if (args)
16991 scope = tsubst_scope (scope, args, complain, in_decl);
16992 expr = tsubst_copy (name, args, complain, in_decl);
16994 else
16995 expr = name;
16997 if (dependent_scope_p (scope))
16999 if (TREE_CODE (expr) == SCOPE_REF)
17000 /* We built one in tsubst_baselink. */
17001 gcc_checking_assert (same_type_p (scope, TREE_OPERAND (expr, 0)));
17002 else
17004 if (is_template)
17005 expr = build_min_nt_loc (loc, TEMPLATE_ID_EXPR, expr,
17006 template_args);
17007 expr = build_qualified_name (NULL_TREE, scope, expr,
17008 QUALIFIED_NAME_IS_TEMPLATE
17009 (qualified_id));
17011 REF_PARENTHESIZED_P (expr) = REF_PARENTHESIZED_P (qualified_id);
17012 return expr;
17015 if (!BASELINK_P (name) && !DECL_P (expr))
17017 if (TREE_CODE (expr) == BIT_NOT_EXPR)
17019 /* A BIT_NOT_EXPR is used to represent a destructor. */
17020 if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
17022 error ("qualifying type %qT does not match destructor name ~%qT",
17023 scope, TREE_OPERAND (expr, 0));
17024 expr = error_mark_node;
17026 else
17027 expr = lookup_qualified_name (scope, complete_dtor_identifier,
17028 LOOK_want::NORMAL, false);
17030 else
17031 expr = lookup_qualified_name (scope, expr, LOOK_want::NORMAL, false);
17032 if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
17033 ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
17035 if (complain & tf_error)
17037 error ("dependent-name %qE is parsed as a non-type, but "
17038 "instantiation yields a type", qualified_id);
17039 inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
17041 return error_mark_node;
17045 if (DECL_P (expr))
17047 if (!check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
17048 scope, complain))
17049 return error_mark_node;
17050 /* Remember that there was a reference to this entity. */
17051 if (!mark_used (expr, complain) && !(complain & tf_error))
17052 return error_mark_node;
17055 if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
17057 if (complain & tf_error)
17058 qualified_name_lookup_error (scope,
17059 TREE_OPERAND (qualified_id, 1),
17060 expr, input_location);
17061 return error_mark_node;
17064 if (is_template)
17066 /* We may be repeating a check already done during parsing, but
17067 if it was well-formed and passed then, it will pass again
17068 now, and if it didn't, we wouldn't have got here. The case
17069 we want to catch is when we couldn't tell then, and can now,
17070 namely when templ prior to substitution was an
17071 identifier. */
17072 if (flag_concepts && check_auto_in_tmpl_args (expr, template_args))
17073 return error_mark_node;
17075 if (variable_template_p (expr))
17076 expr = lookup_and_finish_template_variable (expr, template_args,
17077 complain);
17078 else
17079 expr = lookup_template_function (expr, template_args);
17082 if (expr == error_mark_node && complain & tf_error)
17083 qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
17084 expr, input_location);
17085 else if (TYPE_P (scope))
17087 expr = (adjust_result_of_qualified_name_lookup
17088 (expr, scope, current_nonlambda_class_type ()));
17089 expr = (finish_qualified_id_expr
17090 (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
17091 QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
17092 /*template_arg_p=*/false, complain));
17095 /* Expressions do not generally have reference type. */
17096 if (TREE_CODE (expr) != SCOPE_REF
17097 /* However, if we're about to form a pointer-to-member, we just
17098 want the referenced member referenced. */
17099 && TREE_CODE (expr) != OFFSET_REF)
17100 expr = convert_from_reference (expr);
17102 if (REF_PARENTHESIZED_P (qualified_id))
17103 expr = force_paren_expr (expr);
17105 expr = maybe_wrap_with_location (expr, loc);
17107 return expr;
17110 /* tsubst the initializer for a VAR_DECL. INIT is the unsubstituted
17111 initializer, DECL is the substituted VAR_DECL. Other arguments are as
17112 for tsubst. */
17114 static tree
17115 tsubst_init (tree init, tree decl, tree args,
17116 tsubst_flags_t complain, tree in_decl)
17118 if (!init)
17119 return NULL_TREE;
17121 init = tsubst_expr (init, args, complain, in_decl);
17123 tree type = TREE_TYPE (decl);
17125 if (!init && type != error_mark_node)
17127 if (tree auto_node = type_uses_auto (type))
17129 if (!CLASS_PLACEHOLDER_TEMPLATE (auto_node))
17131 if (complain & tf_error)
17132 error ("initializer for %q#D expands to an empty list "
17133 "of expressions", decl);
17134 return error_mark_node;
17137 else if (!dependent_type_p (type))
17139 /* If we had an initializer but it
17140 instantiated to nothing,
17141 value-initialize the object. This will
17142 only occur when the initializer was a
17143 pack expansion where the parameter packs
17144 used in that expansion were of length
17145 zero. */
17146 init = build_value_init (type, complain);
17147 if (TREE_CODE (init) == AGGR_INIT_EXPR)
17148 init = get_target_expr (init, complain);
17149 if (TREE_CODE (init) == TARGET_EXPR)
17150 TARGET_EXPR_DIRECT_INIT_P (init) = true;
17154 return init;
17157 /* If T is a reference to a dependent member of the current instantiation C and
17158 we are trying to refer to that member in a partial instantiation of C,
17159 return a SCOPE_REF; otherwise, return NULL_TREE.
17161 This can happen when forming a C++17 deduction guide, as in PR96199. */
17163 static tree
17164 maybe_dependent_member_ref (tree t, tree args, tsubst_flags_t complain,
17165 tree in_decl)
17167 if (!(complain & tf_dguide))
17168 return NULL_TREE;
17170 tree decl = (t && TYPE_P (t)) ? TYPE_NAME (t) : t;
17171 if (!decl || !DECL_P (decl))
17172 return NULL_TREE;
17174 tree ctx = context_for_name_lookup (decl);
17175 if (!CLASS_TYPE_P (ctx))
17176 return NULL_TREE;
17178 ctx = tsubst (ctx, args, complain, in_decl);
17179 if (!dependent_scope_p (ctx))
17180 return NULL_TREE;
17182 if (TYPE_P (t))
17184 if (typedef_variant_p (t))
17185 t = strip_typedefs (t);
17186 tree decl = TYPE_NAME (t);
17187 if (decl)
17188 decl = maybe_dependent_member_ref (decl, args, complain, in_decl);
17189 if (!decl)
17190 return NULL_TREE;
17191 return cp_build_qualified_type (TREE_TYPE (decl), cp_type_quals (t),
17192 complain);
17195 tree name = DECL_NAME (t);
17196 tree fullname = name;
17197 if (instantiates_primary_template_p (t))
17199 tree tinfo = get_template_info (t);
17200 name = DECL_NAME (TI_TEMPLATE (tinfo));
17201 tree targs = INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo));
17202 targs = tsubst_template_args (targs, args, complain, in_decl);
17203 fullname = build_nt (TEMPLATE_ID_EXPR, name, targs);
17206 if (TREE_CODE (t) == TYPE_DECL)
17208 if (TREE_CODE (TREE_TYPE (t)) == TYPENAME_TYPE
17209 && TYPE_NAME (TREE_TYPE (t)) == t)
17210 /* The TYPE_DECL for a typename has DECL_CONTEXT of the typename
17211 scope, but it doesn't need to be rewritten again. */
17212 return NULL_TREE;
17213 tree type = build_typename_type (ctx, name, fullname, typename_type);
17214 return TYPE_NAME (type);
17216 else if (DECL_TYPE_TEMPLATE_P (t))
17217 return make_unbound_class_template (ctx, name,
17218 NULL_TREE, complain);
17219 else
17220 return build_qualified_name (NULL_TREE, ctx, fullname,
17221 TREE_CODE (t) == TEMPLATE_DECL);
17224 /* Like tsubst, but deals with expressions. This function just replaces
17225 template parms; to finish processing the resultant expression, use
17226 tsubst_copy_and_build or tsubst_expr. */
17228 static tree
17229 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
17231 enum tree_code code;
17232 tree r;
17234 if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
17235 return t;
17237 if (TYPE_P (t))
17238 return tsubst (t, args, complain, in_decl);
17240 if (tree d = maybe_dependent_member_ref (t, args, complain, in_decl))
17241 return d;
17243 code = TREE_CODE (t);
17245 switch (code)
17247 case PARM_DECL:
17248 r = retrieve_local_specialization (t);
17250 if (r == NULL_TREE)
17252 /* We get here for a use of 'this' in an NSDMI. */
17253 if (DECL_NAME (t) == this_identifier && current_class_ptr)
17254 return current_class_ptr;
17256 /* This can happen for a parameter name used later in a function
17257 declaration (such as in a late-specified return type). Just
17258 make a dummy decl, since it's only used for its type. */
17259 gcc_assert (cp_unevaluated_operand);
17260 r = tsubst_decl (t, args, complain);
17261 /* Give it the template pattern as its context; its true context
17262 hasn't been instantiated yet and this is good enough for
17263 mangling. */
17264 DECL_CONTEXT (r) = DECL_CONTEXT (t);
17267 if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
17268 r = argument_pack_select_arg (r);
17269 if (!mark_used (r, complain) && !(complain & tf_error))
17270 return error_mark_node;
17271 return r;
17273 case CONST_DECL:
17275 tree enum_type;
17276 tree v;
17278 if (DECL_TEMPLATE_PARM_P (t))
17279 return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
17280 if (!uses_template_parms (DECL_CONTEXT (t)))
17281 return t;
17283 /* Unfortunately, we cannot just call lookup_name here.
17284 Consider:
17286 template <int I> int f() {
17287 enum E { a = I };
17288 struct S { void g() { E e = a; } };
17291 When we instantiate f<7>::S::g(), say, lookup_name is not
17292 clever enough to find f<7>::a. */
17293 enum_type
17294 = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
17295 /*entering_scope=*/0);
17297 for (v = TYPE_VALUES (enum_type);
17298 v != NULL_TREE;
17299 v = TREE_CHAIN (v))
17300 if (TREE_PURPOSE (v) == DECL_NAME (t))
17301 return TREE_VALUE (v);
17303 /* We didn't find the name. That should never happen; if
17304 name-lookup found it during preliminary parsing, we
17305 should find it again here during instantiation. */
17306 gcc_unreachable ();
17308 return t;
17310 case FIELD_DECL:
17311 if (DECL_CONTEXT (t))
17313 tree ctx;
17315 ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
17316 /*entering_scope=*/1);
17317 if (ctx != DECL_CONTEXT (t))
17319 tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
17320 if (!r)
17322 if (complain & tf_error)
17323 error ("using invalid field %qD", t);
17324 return error_mark_node;
17326 return r;
17330 return t;
17332 case VAR_DECL:
17333 case FUNCTION_DECL:
17334 if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
17335 r = tsubst (t, args, complain, in_decl);
17336 else if (DECL_LOCAL_DECL_P (t))
17338 /* Local specialization will usually have been created when
17339 we instantiated the DECL_EXPR_DECL. */
17340 r = retrieve_local_specialization (t);
17341 if (!r)
17343 /* We're in a generic lambda referencing a local extern
17344 from an outer block-scope of a non-template. */
17345 gcc_checking_assert (LAMBDA_FUNCTION_P (current_function_decl));
17346 r = t;
17349 else if (local_variable_p (t)
17350 && uses_template_parms (DECL_CONTEXT (t)))
17352 r = retrieve_local_specialization (t);
17353 if (r == NULL_TREE)
17355 /* First try name lookup to find the instantiation. */
17356 r = lookup_name (DECL_NAME (t));
17357 if (r)
17359 if (!VAR_P (r))
17361 /* During error-recovery we may find a non-variable,
17362 even an OVERLOAD: just bail out and avoid ICEs and
17363 duplicate diagnostics (c++/62207). */
17364 gcc_assert (seen_error ());
17365 return error_mark_node;
17367 if (!is_capture_proxy (r))
17369 /* Make sure the one we found is the one we want. */
17370 tree ctx = enclosing_instantiation_of (DECL_CONTEXT (t));
17371 if (ctx != DECL_CONTEXT (r))
17372 r = NULL_TREE;
17376 if (r)
17377 /* OK */;
17378 else
17380 /* This can happen for a variable used in a
17381 late-specified return type of a local lambda, or for a
17382 local static or constant. Building a new VAR_DECL
17383 should be OK in all those cases. */
17384 r = tsubst_decl (t, args, complain);
17385 if (local_specializations)
17386 /* Avoid infinite recursion (79640). */
17387 register_local_specialization (r, t);
17388 if (decl_maybe_constant_var_p (r))
17390 /* We can't call cp_finish_decl, so handle the
17391 initializer by hand. */
17392 tree init = tsubst_init (DECL_INITIAL (t), r, args,
17393 complain, in_decl);
17394 if (!processing_template_decl)
17395 init = maybe_constant_init (init);
17396 if (processing_template_decl
17397 ? potential_constant_expression (init)
17398 : reduced_constant_expression_p (init))
17399 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
17400 = TREE_CONSTANT (r) = true;
17401 DECL_INITIAL (r) = init;
17402 if (tree auto_node = type_uses_auto (TREE_TYPE (r)))
17403 TREE_TYPE (r)
17404 = do_auto_deduction (TREE_TYPE (r), init, auto_node,
17405 complain, adc_variable_type);
17407 gcc_assert (cp_unevaluated_operand
17408 || processing_contract_condition
17409 || TREE_STATIC (r)
17410 || decl_constant_var_p (r)
17411 || seen_error ());
17412 if (!processing_template_decl
17413 && !TREE_STATIC (r))
17414 r = process_outer_var_ref (r, complain);
17416 /* Remember this for subsequent uses. */
17417 if (local_specializations)
17418 register_local_specialization (r, t);
17420 if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
17421 r = argument_pack_select_arg (r);
17423 else
17424 r = t;
17425 if (!mark_used (r, complain))
17426 return error_mark_node;
17427 return r;
17429 case NAMESPACE_DECL:
17430 return t;
17432 case OVERLOAD:
17433 return t;
17435 case BASELINK:
17436 return tsubst_baselink (t, current_nonlambda_class_type (),
17437 args, complain, in_decl);
17439 case TEMPLATE_DECL:
17440 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
17441 return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
17442 args, complain, in_decl);
17443 else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
17444 return tsubst (t, args, complain, in_decl);
17445 else if (DECL_CLASS_SCOPE_P (t)
17446 && uses_template_parms (DECL_CONTEXT (t)))
17448 /* Template template argument like the following example need
17449 special treatment:
17451 template <template <class> class TT> struct C {};
17452 template <class T> struct D {
17453 template <class U> struct E {};
17454 C<E> c; // #1
17456 D<int> d; // #2
17458 We are processing the template argument `E' in #1 for
17459 the template instantiation #2. Originally, `E' is a
17460 TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT. Now we
17461 have to substitute this with one having context `D<int>'. */
17463 tree context = tsubst_aggr_type (DECL_CONTEXT (t), args, complain,
17464 in_decl, /*entering_scope=*/true);
17465 return lookup_field (context, DECL_NAME(t), 0, false);
17467 else
17468 /* Ordinary template template argument. */
17469 return t;
17471 case NON_LVALUE_EXPR:
17472 case VIEW_CONVERT_EXPR:
17474 /* Handle location wrappers by substituting the wrapped node
17475 first, *then* reusing the resulting type. Doing the type
17476 first ensures that we handle template parameters and
17477 parameter pack expansions. */
17478 if (location_wrapper_p (t))
17480 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args,
17481 complain, in_decl);
17482 return maybe_wrap_with_location (op0, EXPR_LOCATION (t));
17484 tree op = TREE_OPERAND (t, 0);
17485 /* force_paren_expr can also create a VIEW_CONVERT_EXPR. */
17486 if (code == VIEW_CONVERT_EXPR && REF_PARENTHESIZED_P (t))
17488 op = tsubst_copy (op, args, complain, in_decl);
17489 op = build1 (code, TREE_TYPE (op), op);
17490 REF_PARENTHESIZED_P (op) = true;
17491 return op;
17493 /* We shouldn't see any other uses of these in templates
17494 (tsubst_copy_and_build handles C++20 tparm object wrappers). */
17495 gcc_unreachable ();
17498 case CAST_EXPR:
17499 case REINTERPRET_CAST_EXPR:
17500 case CONST_CAST_EXPR:
17501 case STATIC_CAST_EXPR:
17502 case DYNAMIC_CAST_EXPR:
17503 case IMPLICIT_CONV_EXPR:
17504 CASE_CONVERT:
17506 tsubst_flags_t tcomplain = complain;
17507 if (code == CAST_EXPR)
17508 tcomplain |= tf_tst_ok;
17509 tree type = tsubst (TREE_TYPE (t), args, tcomplain, in_decl);
17510 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17511 return build1 (code, type, op0);
17514 case BIT_CAST_EXPR:
17516 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17517 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17518 r = build_min (BIT_CAST_EXPR, type, op0);
17519 SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
17520 return r;
17523 case SIZEOF_EXPR:
17524 if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
17525 || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
17527 tree expanded, op = TREE_OPERAND (t, 0);
17528 int len = 0;
17530 if (SIZEOF_EXPR_TYPE_P (t))
17531 op = TREE_TYPE (op);
17533 ++cp_unevaluated_operand;
17534 ++c_inhibit_evaluation_warnings;
17535 /* We only want to compute the number of arguments. */
17536 if (PACK_EXPANSION_P (op))
17537 expanded = tsubst_pack_expansion (op, args, complain, in_decl);
17538 else
17539 expanded = tsubst_template_args (ARGUMENT_PACK_ARGS (op),
17540 args, complain, in_decl);
17541 --cp_unevaluated_operand;
17542 --c_inhibit_evaluation_warnings;
17544 if (TREE_CODE (expanded) == TREE_VEC)
17546 len = TREE_VEC_LENGTH (expanded);
17547 /* Set TREE_USED for the benefit of -Wunused. */
17548 for (int i = 0; i < len; i++)
17549 if (DECL_P (TREE_VEC_ELT (expanded, i)))
17550 TREE_USED (TREE_VEC_ELT (expanded, i)) = true;
17553 if (expanded == error_mark_node)
17554 return error_mark_node;
17555 else if (PACK_EXPANSION_P (expanded)
17556 || (TREE_CODE (expanded) == TREE_VEC
17557 && pack_expansion_args_count (expanded)))
17560 if (PACK_EXPANSION_P (expanded))
17561 /* OK. */;
17562 else if (TREE_VEC_LENGTH (expanded) == 1)
17563 expanded = TREE_VEC_ELT (expanded, 0);
17564 else
17565 expanded = make_argument_pack (expanded);
17567 if (TYPE_P (expanded))
17568 return cxx_sizeof_or_alignof_type (input_location,
17569 expanded, SIZEOF_EXPR,
17570 false,
17571 complain & tf_error);
17572 else
17573 return cxx_sizeof_or_alignof_expr (input_location,
17574 expanded, SIZEOF_EXPR,
17575 false,
17576 complain & tf_error);
17578 else
17579 return build_int_cst (size_type_node, len);
17581 if (SIZEOF_EXPR_TYPE_P (t))
17583 r = tsubst (TREE_TYPE (TREE_OPERAND (t, 0)),
17584 args, complain, in_decl);
17585 r = build1 (NOP_EXPR, r, error_mark_node);
17586 r = build1 (SIZEOF_EXPR,
17587 tsubst (TREE_TYPE (t), args, complain, in_decl), r);
17588 SIZEOF_EXPR_TYPE_P (r) = 1;
17589 return r;
17591 /* Fall through */
17593 case INDIRECT_REF:
17594 case NEGATE_EXPR:
17595 case TRUTH_NOT_EXPR:
17596 case BIT_NOT_EXPR:
17597 case ADDR_EXPR:
17598 case UNARY_PLUS_EXPR: /* Unary + */
17599 case ALIGNOF_EXPR:
17600 case AT_ENCODE_EXPR:
17601 case ARROW_EXPR:
17602 case THROW_EXPR:
17603 case TYPEID_EXPR:
17604 case REALPART_EXPR:
17605 case IMAGPART_EXPR:
17606 case PAREN_EXPR:
17608 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17609 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17610 r = build1_loc (EXPR_LOCATION (t), code, type, op0);
17611 if (code == ALIGNOF_EXPR)
17612 ALIGNOF_EXPR_STD_P (r) = ALIGNOF_EXPR_STD_P (t);
17613 /* For addresses of immediate functions ensure we have EXPR_LOCATION
17614 set for possible later diagnostics. */
17615 if (code == ADDR_EXPR
17616 && EXPR_LOCATION (r) == UNKNOWN_LOCATION
17617 && TREE_CODE (op0) == FUNCTION_DECL
17618 && DECL_IMMEDIATE_FUNCTION_P (op0))
17619 SET_EXPR_LOCATION (r, input_location);
17620 return r;
17623 case EXCESS_PRECISION_EXPR:
17625 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17626 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17627 if (TREE_CODE (op0) == EXCESS_PRECISION_EXPR)
17629 gcc_checking_assert (same_type_p (type, TREE_TYPE (op0)));
17630 return op0;
17632 return build1_loc (EXPR_LOCATION (t), code, type, op0);
17635 case COMPONENT_REF:
17637 tree object;
17638 tree name;
17640 object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17641 name = TREE_OPERAND (t, 1);
17642 if (TREE_CODE (name) == BIT_NOT_EXPR)
17644 name = tsubst_copy (TREE_OPERAND (name, 0), args,
17645 complain, in_decl);
17646 name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
17648 else if (TREE_CODE (name) == SCOPE_REF
17649 && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
17651 tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
17652 complain, in_decl);
17653 name = TREE_OPERAND (name, 1);
17654 name = tsubst_copy (TREE_OPERAND (name, 0), args,
17655 complain, in_decl);
17656 name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
17657 name = build_qualified_name (/*type=*/NULL_TREE,
17658 base, name,
17659 /*template_p=*/false);
17661 else if (BASELINK_P (name))
17662 name = tsubst_baselink (name,
17663 non_reference (TREE_TYPE (object)),
17664 args, complain,
17665 in_decl);
17666 else
17667 name = tsubst_copy (name, args, complain, in_decl);
17668 return build_nt (COMPONENT_REF, object, name, NULL_TREE);
17671 case PLUS_EXPR:
17672 case MINUS_EXPR:
17673 case MULT_EXPR:
17674 case TRUNC_DIV_EXPR:
17675 case CEIL_DIV_EXPR:
17676 case FLOOR_DIV_EXPR:
17677 case ROUND_DIV_EXPR:
17678 case EXACT_DIV_EXPR:
17679 case BIT_AND_EXPR:
17680 case BIT_IOR_EXPR:
17681 case BIT_XOR_EXPR:
17682 case TRUNC_MOD_EXPR:
17683 case FLOOR_MOD_EXPR:
17684 case TRUTH_ANDIF_EXPR:
17685 case TRUTH_ORIF_EXPR:
17686 case TRUTH_AND_EXPR:
17687 case TRUTH_OR_EXPR:
17688 case RSHIFT_EXPR:
17689 case LSHIFT_EXPR:
17690 case EQ_EXPR:
17691 case NE_EXPR:
17692 case MAX_EXPR:
17693 case MIN_EXPR:
17694 case LE_EXPR:
17695 case GE_EXPR:
17696 case LT_EXPR:
17697 case GT_EXPR:
17698 case COMPOUND_EXPR:
17699 case DOTSTAR_EXPR:
17700 case MEMBER_REF:
17701 case PREDECREMENT_EXPR:
17702 case PREINCREMENT_EXPR:
17703 case POSTDECREMENT_EXPR:
17704 case POSTINCREMENT_EXPR:
17706 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17707 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17708 return build_nt (code, op0, op1);
17711 case SCOPE_REF:
17713 tree op0 = tsubst_scope (TREE_OPERAND (t, 0), args, complain, in_decl);
17714 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17715 return build_qualified_name (/*type=*/NULL_TREE, op0, op1,
17716 QUALIFIED_NAME_IS_TEMPLATE (t));
17719 case ARRAY_REF:
17721 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17722 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17723 return build_nt (ARRAY_REF, op0, op1, NULL_TREE, NULL_TREE);
17726 case CALL_EXPR:
17728 int n = VL_EXP_OPERAND_LENGTH (t);
17729 tree result = build_vl_exp (CALL_EXPR, n);
17730 int i;
17731 for (i = 0; i < n; i++)
17732 TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
17733 complain, in_decl);
17734 return result;
17737 case COND_EXPR:
17738 case MODOP_EXPR:
17739 case PSEUDO_DTOR_EXPR:
17740 case VEC_PERM_EXPR:
17742 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17743 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17744 tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
17745 r = build_nt (code, op0, op1, op2);
17746 copy_warning (r, t);
17747 return r;
17750 case NEW_EXPR:
17752 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17753 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17754 tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
17755 r = build_nt (code, op0, op1, op2);
17756 NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
17757 return r;
17760 case DELETE_EXPR:
17762 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17763 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17764 r = build_nt (code, op0, op1);
17765 DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
17766 DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
17767 return r;
17770 case TEMPLATE_ID_EXPR:
17772 /* Substituted template arguments */
17773 tree tmpl = TREE_OPERAND (t, 0);
17774 tree targs = TREE_OPERAND (t, 1);
17776 tmpl = tsubst_copy (tmpl, args, complain, in_decl);
17777 if (targs)
17778 targs = tsubst_template_args (targs, args, complain, in_decl);
17780 if (variable_template_p (tmpl))
17781 return lookup_template_variable (tmpl, targs, complain);
17782 else
17783 return lookup_template_function (tmpl, targs);
17786 case TREE_LIST:
17788 tree purpose, value, chain;
17790 if (t == void_list_node)
17791 return t;
17793 purpose = TREE_PURPOSE (t);
17794 if (purpose)
17795 purpose = tsubst_copy (purpose, args, complain, in_decl);
17796 value = TREE_VALUE (t);
17797 if (value)
17798 value = tsubst_copy (value, args, complain, in_decl);
17799 chain = TREE_CHAIN (t);
17800 if (chain && chain != void_type_node)
17801 chain = tsubst_copy (chain, args, complain, in_decl);
17802 if (purpose == TREE_PURPOSE (t)
17803 && value == TREE_VALUE (t)
17804 && chain == TREE_CHAIN (t))
17805 return t;
17806 return tree_cons (purpose, value, chain);
17809 case TEMPLATE_PARM_INDEX:
17810 case TYPE_DECL:
17811 return tsubst (t, args, complain, in_decl);
17813 case USING_DECL:
17814 t = DECL_NAME (t);
17815 /* Fall through. */
17816 case IDENTIFIER_NODE:
17817 if (IDENTIFIER_CONV_OP_P (t))
17819 tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17820 return make_conv_op_name (new_type);
17822 else
17823 return t;
17825 case CONSTRUCTOR:
17826 /* This is handled by tsubst_copy_and_build. */
17827 gcc_unreachable ();
17829 case VA_ARG_EXPR:
17831 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17832 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17833 return build_x_va_arg (EXPR_LOCATION (t), op0, type);
17836 case CLEANUP_POINT_EXPR:
17837 /* We shouldn't have built any of these during initial template
17838 generation. Instead, they should be built during instantiation
17839 in response to the saved STMT_IS_FULL_EXPR_P setting. */
17840 gcc_unreachable ();
17842 case OFFSET_REF:
17844 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17845 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17846 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17847 r = build2 (code, type, op0, op1);
17848 PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
17849 if (!mark_used (TREE_OPERAND (r, 1), complain)
17850 && !(complain & tf_error))
17851 return error_mark_node;
17852 return r;
17855 case EXPR_PACK_EXPANSION:
17856 error ("invalid use of pack expansion expression");
17857 return error_mark_node;
17859 case NONTYPE_ARGUMENT_PACK:
17860 error ("use %<...%> to expand argument pack");
17861 return error_mark_node;
17863 case VOID_CST:
17864 gcc_checking_assert (t == void_node && VOID_TYPE_P (TREE_TYPE (t)));
17865 return t;
17867 case INTEGER_CST:
17868 case REAL_CST:
17869 case COMPLEX_CST:
17870 case VECTOR_CST:
17872 /* Instantiate any typedefs in the type. */
17873 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17874 r = fold_convert (type, t);
17875 gcc_assert (TREE_CODE (r) == code);
17876 return r;
17879 case STRING_CST:
17881 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17882 r = t;
17883 if (type != TREE_TYPE (t))
17885 r = copy_node (t);
17886 TREE_TYPE (r) = type;
17888 return r;
17891 case PTRMEM_CST:
17892 /* These can sometimes show up in a partial instantiation, but never
17893 involve template parms. */
17894 gcc_assert (!uses_template_parms (t));
17895 return t;
17897 case UNARY_LEFT_FOLD_EXPR:
17898 return tsubst_unary_left_fold (t, args, complain, in_decl);
17899 case UNARY_RIGHT_FOLD_EXPR:
17900 return tsubst_unary_right_fold (t, args, complain, in_decl);
17901 case BINARY_LEFT_FOLD_EXPR:
17902 return tsubst_binary_left_fold (t, args, complain, in_decl);
17903 case BINARY_RIGHT_FOLD_EXPR:
17904 return tsubst_binary_right_fold (t, args, complain, in_decl);
17905 case PREDICT_EXPR:
17906 return t;
17908 case DEBUG_BEGIN_STMT:
17909 /* ??? There's no point in copying it for now, but maybe some
17910 day it will contain more information, such as a pointer back
17911 to the containing function, inlined copy or so. */
17912 return t;
17914 case CO_AWAIT_EXPR:
17915 return tsubst_expr (t, args, complain, in_decl);
17917 default:
17918 /* We shouldn't get here, but keep going if !flag_checking. */
17919 if (flag_checking)
17920 gcc_unreachable ();
17921 return t;
17925 /* Helper function for tsubst_omp_clauses, used for instantiation of
17926 OMP_CLAUSE_DECL of clauses. */
17928 static tree
17929 tsubst_omp_clause_decl (tree decl, tree args, tsubst_flags_t complain,
17930 tree in_decl, tree *iterator_cache)
17932 if (decl == NULL_TREE || decl == ridpointers[RID_OMP_ALL_MEMORY])
17933 return decl;
17935 /* Handle OpenMP iterators. */
17936 if (TREE_CODE (decl) == TREE_LIST
17937 && TREE_PURPOSE (decl)
17938 && TREE_CODE (TREE_PURPOSE (decl)) == TREE_VEC)
17940 tree ret;
17941 if (iterator_cache[0] == TREE_PURPOSE (decl))
17942 ret = iterator_cache[1];
17943 else
17945 tree *tp = &ret;
17946 begin_scope (sk_omp, NULL);
17947 for (tree it = TREE_PURPOSE (decl); it; it = TREE_CHAIN (it))
17949 *tp = copy_node (it);
17950 TREE_VEC_ELT (*tp, 0)
17951 = tsubst_decl (TREE_VEC_ELT (it, 0), args, complain);
17952 DECL_CONTEXT (TREE_VEC_ELT (*tp, 0)) = current_function_decl;
17953 pushdecl (TREE_VEC_ELT (*tp, 0));
17954 TREE_VEC_ELT (*tp, 1)
17955 = tsubst_expr (TREE_VEC_ELT (it, 1), args, complain, in_decl);
17956 TREE_VEC_ELT (*tp, 2)
17957 = tsubst_expr (TREE_VEC_ELT (it, 2), args, complain, in_decl);
17958 TREE_VEC_ELT (*tp, 3)
17959 = tsubst_expr (TREE_VEC_ELT (it, 3), args, complain, in_decl);
17960 TREE_CHAIN (*tp) = NULL_TREE;
17961 tp = &TREE_CHAIN (*tp);
17963 TREE_VEC_ELT (ret, 5) = poplevel (1, 1, 0);
17964 iterator_cache[0] = TREE_PURPOSE (decl);
17965 iterator_cache[1] = ret;
17967 return build_tree_list (ret, tsubst_omp_clause_decl (TREE_VALUE (decl),
17968 args, complain,
17969 in_decl, NULL));
17972 /* Handle an OpenMP array section represented as a TREE_LIST (or
17973 OMP_CLAUSE_DOACROSS_KIND). An OMP_CLAUSE_DOACROSS (with a depend
17974 kind of OMP_CLAUSE_DOACROSS_SINK) can also be represented as a
17975 TREE_LIST. We can handle it exactly the same as an array section
17976 (purpose, value, and a chain), even though the nomenclature
17977 (low_bound, length, etc) is different. */
17978 if (TREE_CODE (decl) == TREE_LIST)
17980 tree low_bound
17981 = tsubst_expr (TREE_PURPOSE (decl), args, complain, in_decl);
17982 tree length = tsubst_expr (TREE_VALUE (decl), args, complain, in_decl);
17983 tree chain = tsubst_omp_clause_decl (TREE_CHAIN (decl), args, complain,
17984 in_decl, NULL);
17985 if (TREE_PURPOSE (decl) == low_bound
17986 && TREE_VALUE (decl) == length
17987 && TREE_CHAIN (decl) == chain)
17988 return decl;
17989 tree ret = tree_cons (low_bound, length, chain);
17990 OMP_CLAUSE_DOACROSS_SINK_NEGATIVE (ret)
17991 = OMP_CLAUSE_DOACROSS_SINK_NEGATIVE (decl);
17992 return ret;
17994 tree ret = tsubst_expr (decl, args, complain, in_decl);
17995 /* Undo convert_from_reference tsubst_expr could have called. */
17996 if (decl
17997 && REFERENCE_REF_P (ret)
17998 && !REFERENCE_REF_P (decl))
17999 ret = TREE_OPERAND (ret, 0);
18000 return ret;
18003 /* Like tsubst_copy, but specifically for OpenMP clauses. */
18005 static tree
18006 tsubst_omp_clauses (tree clauses, enum c_omp_region_type ort,
18007 tree args, tsubst_flags_t complain, tree in_decl)
18009 tree new_clauses = NULL_TREE, nc, oc;
18010 tree linear_no_step = NULL_TREE;
18011 tree iterator_cache[2] = { NULL_TREE, NULL_TREE };
18013 for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
18015 nc = copy_node (oc);
18016 OMP_CLAUSE_CHAIN (nc) = new_clauses;
18017 new_clauses = nc;
18019 switch (OMP_CLAUSE_CODE (nc))
18021 case OMP_CLAUSE_LASTPRIVATE:
18022 if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
18024 OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
18025 tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args,
18026 complain, in_decl);
18027 OMP_CLAUSE_LASTPRIVATE_STMT (nc)
18028 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
18030 /* FALLTHRU */
18031 case OMP_CLAUSE_PRIVATE:
18032 case OMP_CLAUSE_SHARED:
18033 case OMP_CLAUSE_FIRSTPRIVATE:
18034 case OMP_CLAUSE_COPYIN:
18035 case OMP_CLAUSE_COPYPRIVATE:
18036 case OMP_CLAUSE_UNIFORM:
18037 case OMP_CLAUSE_DEPEND:
18038 case OMP_CLAUSE_DOACROSS:
18039 case OMP_CLAUSE_AFFINITY:
18040 case OMP_CLAUSE_FROM:
18041 case OMP_CLAUSE_TO:
18042 case OMP_CLAUSE_MAP:
18043 case OMP_CLAUSE__CACHE_:
18044 case OMP_CLAUSE_NONTEMPORAL:
18045 case OMP_CLAUSE_USE_DEVICE_PTR:
18046 case OMP_CLAUSE_USE_DEVICE_ADDR:
18047 case OMP_CLAUSE_IS_DEVICE_PTR:
18048 case OMP_CLAUSE_HAS_DEVICE_ADDR:
18049 case OMP_CLAUSE_INCLUSIVE:
18050 case OMP_CLAUSE_EXCLUSIVE:
18051 OMP_CLAUSE_DECL (nc)
18052 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
18053 in_decl, iterator_cache);
18054 break;
18055 case OMP_CLAUSE_NUM_TEAMS:
18056 if (OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (oc))
18057 OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (nc)
18058 = tsubst_expr (OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (oc), args,
18059 complain, in_decl);
18060 /* FALLTHRU */
18061 case OMP_CLAUSE_TILE:
18062 case OMP_CLAUSE_IF:
18063 case OMP_CLAUSE_NUM_THREADS:
18064 case OMP_CLAUSE_SCHEDULE:
18065 case OMP_CLAUSE_COLLAPSE:
18066 case OMP_CLAUSE_FINAL:
18067 case OMP_CLAUSE_DEVICE:
18068 case OMP_CLAUSE_DIST_SCHEDULE:
18069 case OMP_CLAUSE_THREAD_LIMIT:
18070 case OMP_CLAUSE_SAFELEN:
18071 case OMP_CLAUSE_SIMDLEN:
18072 case OMP_CLAUSE_NUM_TASKS:
18073 case OMP_CLAUSE_GRAINSIZE:
18074 case OMP_CLAUSE_PRIORITY:
18075 case OMP_CLAUSE_ORDERED:
18076 case OMP_CLAUSE_HINT:
18077 case OMP_CLAUSE_FILTER:
18078 case OMP_CLAUSE_NUM_GANGS:
18079 case OMP_CLAUSE_NUM_WORKERS:
18080 case OMP_CLAUSE_VECTOR_LENGTH:
18081 case OMP_CLAUSE_WORKER:
18082 case OMP_CLAUSE_VECTOR:
18083 case OMP_CLAUSE_ASYNC:
18084 case OMP_CLAUSE_WAIT:
18085 case OMP_CLAUSE_DETACH:
18086 OMP_CLAUSE_OPERAND (nc, 0)
18087 = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, in_decl);
18088 break;
18089 case OMP_CLAUSE_REDUCTION:
18090 case OMP_CLAUSE_IN_REDUCTION:
18091 case OMP_CLAUSE_TASK_REDUCTION:
18092 if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc))
18094 tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc);
18095 if (TREE_CODE (placeholder) == SCOPE_REF)
18097 tree scope = tsubst (TREE_OPERAND (placeholder, 0), args,
18098 complain, in_decl);
18099 OMP_CLAUSE_REDUCTION_PLACEHOLDER (nc)
18100 = build_qualified_name (NULL_TREE, scope,
18101 TREE_OPERAND (placeholder, 1),
18102 false);
18104 else
18105 gcc_assert (identifier_p (placeholder));
18107 OMP_CLAUSE_DECL (nc)
18108 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
18109 in_decl, NULL);
18110 break;
18111 case OMP_CLAUSE_GANG:
18112 case OMP_CLAUSE_ALIGNED:
18113 OMP_CLAUSE_DECL (nc)
18114 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
18115 in_decl, NULL);
18116 OMP_CLAUSE_OPERAND (nc, 1)
18117 = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 1), args, complain, in_decl);
18118 break;
18119 case OMP_CLAUSE_ALLOCATE:
18120 OMP_CLAUSE_DECL (nc)
18121 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
18122 in_decl, NULL);
18123 OMP_CLAUSE_OPERAND (nc, 1)
18124 = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 1), args, complain, in_decl);
18125 OMP_CLAUSE_OPERAND (nc, 2)
18126 = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 2), args, complain, in_decl);
18127 break;
18128 case OMP_CLAUSE_LINEAR:
18129 OMP_CLAUSE_DECL (nc)
18130 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
18131 in_decl, NULL);
18132 if (OMP_CLAUSE_LINEAR_STEP (oc) == NULL_TREE)
18134 gcc_assert (!linear_no_step);
18135 linear_no_step = nc;
18137 else if (OMP_CLAUSE_LINEAR_VARIABLE_STRIDE (oc))
18138 OMP_CLAUSE_LINEAR_STEP (nc)
18139 = tsubst_omp_clause_decl (OMP_CLAUSE_LINEAR_STEP (oc), args,
18140 complain, in_decl, NULL);
18141 else
18142 OMP_CLAUSE_LINEAR_STEP (nc)
18143 = tsubst_expr (OMP_CLAUSE_LINEAR_STEP (oc), args,
18144 complain, in_decl);
18145 break;
18146 case OMP_CLAUSE_NOWAIT:
18147 case OMP_CLAUSE_DEFAULT:
18148 case OMP_CLAUSE_UNTIED:
18149 case OMP_CLAUSE_MERGEABLE:
18150 case OMP_CLAUSE_INBRANCH:
18151 case OMP_CLAUSE_NOTINBRANCH:
18152 case OMP_CLAUSE_PROC_BIND:
18153 case OMP_CLAUSE_FOR:
18154 case OMP_CLAUSE_PARALLEL:
18155 case OMP_CLAUSE_SECTIONS:
18156 case OMP_CLAUSE_TASKGROUP:
18157 case OMP_CLAUSE_NOGROUP:
18158 case OMP_CLAUSE_THREADS:
18159 case OMP_CLAUSE_SIMD:
18160 case OMP_CLAUSE_DEFAULTMAP:
18161 case OMP_CLAUSE_ORDER:
18162 case OMP_CLAUSE_BIND:
18163 case OMP_CLAUSE_INDEPENDENT:
18164 case OMP_CLAUSE_AUTO:
18165 case OMP_CLAUSE_SEQ:
18166 case OMP_CLAUSE_IF_PRESENT:
18167 case OMP_CLAUSE_FINALIZE:
18168 case OMP_CLAUSE_NOHOST:
18169 break;
18170 default:
18171 gcc_unreachable ();
18173 if ((ort & C_ORT_OMP_DECLARE_SIMD) == C_ORT_OMP)
18174 switch (OMP_CLAUSE_CODE (nc))
18176 case OMP_CLAUSE_SHARED:
18177 case OMP_CLAUSE_PRIVATE:
18178 case OMP_CLAUSE_FIRSTPRIVATE:
18179 case OMP_CLAUSE_LASTPRIVATE:
18180 case OMP_CLAUSE_COPYPRIVATE:
18181 case OMP_CLAUSE_LINEAR:
18182 case OMP_CLAUSE_REDUCTION:
18183 case OMP_CLAUSE_IN_REDUCTION:
18184 case OMP_CLAUSE_TASK_REDUCTION:
18185 case OMP_CLAUSE_USE_DEVICE_PTR:
18186 case OMP_CLAUSE_USE_DEVICE_ADDR:
18187 case OMP_CLAUSE_IS_DEVICE_PTR:
18188 case OMP_CLAUSE_HAS_DEVICE_ADDR:
18189 case OMP_CLAUSE_INCLUSIVE:
18190 case OMP_CLAUSE_EXCLUSIVE:
18191 case OMP_CLAUSE_ALLOCATE:
18192 /* tsubst_expr on SCOPE_REF results in returning
18193 finish_non_static_data_member result. Undo that here. */
18194 if (TREE_CODE (OMP_CLAUSE_DECL (oc)) == SCOPE_REF
18195 && (TREE_CODE (TREE_OPERAND (OMP_CLAUSE_DECL (oc), 1))
18196 == IDENTIFIER_NODE))
18198 tree t = OMP_CLAUSE_DECL (nc);
18199 tree v = t;
18200 while (v)
18201 switch (TREE_CODE (v))
18203 case COMPONENT_REF:
18204 case MEM_REF:
18205 case INDIRECT_REF:
18206 CASE_CONVERT:
18207 case POINTER_PLUS_EXPR:
18208 v = TREE_OPERAND (v, 0);
18209 continue;
18210 case PARM_DECL:
18211 if (DECL_CONTEXT (v) == current_function_decl
18212 && DECL_ARTIFICIAL (v)
18213 && DECL_NAME (v) == this_identifier)
18214 OMP_CLAUSE_DECL (nc) = TREE_OPERAND (t, 1);
18215 /* FALLTHRU */
18216 default:
18217 v = NULL_TREE;
18218 break;
18221 else if (VAR_P (OMP_CLAUSE_DECL (oc))
18222 && DECL_HAS_VALUE_EXPR_P (OMP_CLAUSE_DECL (oc))
18223 && DECL_ARTIFICIAL (OMP_CLAUSE_DECL (oc))
18224 && DECL_LANG_SPECIFIC (OMP_CLAUSE_DECL (oc))
18225 && DECL_OMP_PRIVATIZED_MEMBER (OMP_CLAUSE_DECL (oc)))
18227 tree decl = OMP_CLAUSE_DECL (nc);
18228 if (VAR_P (decl))
18230 retrofit_lang_decl (decl);
18231 DECL_OMP_PRIVATIZED_MEMBER (decl) = 1;
18234 break;
18235 default:
18236 break;
18240 new_clauses = nreverse (new_clauses);
18241 if (ort != C_ORT_OMP_DECLARE_SIMD)
18243 new_clauses = finish_omp_clauses (new_clauses, ort);
18244 if (linear_no_step)
18245 for (nc = new_clauses; nc; nc = OMP_CLAUSE_CHAIN (nc))
18246 if (nc == linear_no_step)
18248 OMP_CLAUSE_LINEAR_STEP (nc) = NULL_TREE;
18249 break;
18252 return new_clauses;
18255 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes. */
18257 static tree
18258 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
18259 tree in_decl)
18261 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
18263 tree purpose, value, chain;
18265 if (t == NULL)
18266 return t;
18268 if (TREE_CODE (t) != TREE_LIST)
18269 return tsubst_copy_and_build (t, args, complain, in_decl);
18271 if (t == void_list_node)
18272 return t;
18274 purpose = TREE_PURPOSE (t);
18275 if (purpose)
18276 purpose = RECUR (purpose);
18277 value = TREE_VALUE (t);
18278 if (value)
18280 if (TREE_CODE (value) != LABEL_DECL)
18281 value = RECUR (value);
18282 else
18284 value = lookup_label (DECL_NAME (value));
18285 gcc_assert (TREE_CODE (value) == LABEL_DECL);
18286 TREE_USED (value) = 1;
18289 chain = TREE_CHAIN (t);
18290 if (chain && chain != void_type_node)
18291 chain = RECUR (chain);
18292 return tree_cons (purpose, value, chain);
18293 #undef RECUR
18296 /* Used to temporarily communicate the list of #pragma omp parallel
18297 clauses to #pragma omp for instantiation if they are combined
18298 together. */
18300 static tree *omp_parallel_combined_clauses;
18302 static tree tsubst_decomp_names (tree, tree, tree, tsubst_flags_t, tree,
18303 tree *, unsigned int *);
18305 /* Substitute one OMP_FOR iterator. */
18307 static bool
18308 tsubst_omp_for_iterator (tree t, int i, tree declv, tree &orig_declv,
18309 tree initv, tree condv, tree incrv, tree *clauses,
18310 tree args, tsubst_flags_t complain, tree in_decl)
18312 #define RECUR(NODE) \
18313 tsubst_expr ((NODE), args, complain, in_decl)
18314 tree decl, init, cond = NULL_TREE, incr = NULL_TREE;
18315 bool ret = false;
18317 init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
18318 gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
18320 decl = TREE_OPERAND (init, 0);
18321 init = TREE_OPERAND (init, 1);
18322 tree decl_expr = NULL_TREE;
18323 bool range_for = TREE_VEC_ELT (OMP_FOR_COND (t), i) == global_namespace;
18324 if (range_for)
18326 bool decomp = false;
18327 if (decl != error_mark_node && DECL_HAS_VALUE_EXPR_P (decl))
18329 tree v = DECL_VALUE_EXPR (decl);
18330 if (TREE_CODE (v) == ARRAY_REF
18331 && VAR_P (TREE_OPERAND (v, 0))
18332 && DECL_DECOMPOSITION_P (TREE_OPERAND (v, 0)))
18334 tree decomp_first = NULL_TREE;
18335 unsigned decomp_cnt = 0;
18336 tree d = tsubst_decl (TREE_OPERAND (v, 0), args, complain);
18337 maybe_push_decl (d);
18338 d = tsubst_decomp_names (d, TREE_OPERAND (v, 0), args, complain,
18339 in_decl, &decomp_first, &decomp_cnt);
18340 decomp = true;
18341 if (d == error_mark_node)
18342 decl = error_mark_node;
18343 else
18344 for (unsigned int i = 0; i < decomp_cnt; i++)
18346 if (!DECL_HAS_VALUE_EXPR_P (decomp_first))
18348 tree v = build_nt (ARRAY_REF, d,
18349 size_int (decomp_cnt - i - 1),
18350 NULL_TREE, NULL_TREE);
18351 SET_DECL_VALUE_EXPR (decomp_first, v);
18352 DECL_HAS_VALUE_EXPR_P (decomp_first) = 1;
18354 fit_decomposition_lang_decl (decomp_first, d);
18355 decomp_first = DECL_CHAIN (decomp_first);
18359 decl = tsubst_decl (decl, args, complain);
18360 if (!decomp)
18361 maybe_push_decl (decl);
18363 else if (init && TREE_CODE (init) == DECL_EXPR)
18365 /* We need to jump through some hoops to handle declarations in the
18366 init-statement, since we might need to handle auto deduction,
18367 but we need to keep control of initialization. */
18368 decl_expr = init;
18369 init = DECL_INITIAL (DECL_EXPR_DECL (init));
18370 decl = tsubst_decl (decl, args, complain);
18372 else
18374 if (TREE_CODE (decl) == SCOPE_REF)
18376 decl = RECUR (decl);
18377 if (TREE_CODE (decl) == COMPONENT_REF)
18379 tree v = decl;
18380 while (v)
18381 switch (TREE_CODE (v))
18383 case COMPONENT_REF:
18384 case MEM_REF:
18385 case INDIRECT_REF:
18386 CASE_CONVERT:
18387 case POINTER_PLUS_EXPR:
18388 v = TREE_OPERAND (v, 0);
18389 continue;
18390 case PARM_DECL:
18391 if (DECL_CONTEXT (v) == current_function_decl
18392 && DECL_ARTIFICIAL (v)
18393 && DECL_NAME (v) == this_identifier)
18395 decl = TREE_OPERAND (decl, 1);
18396 decl = omp_privatize_field (decl, false);
18398 /* FALLTHRU */
18399 default:
18400 v = NULL_TREE;
18401 break;
18405 else
18406 decl = RECUR (decl);
18408 if (init && TREE_CODE (init) == TREE_VEC)
18410 init = copy_node (init);
18411 TREE_VEC_ELT (init, 0)
18412 = tsubst_decl (TREE_VEC_ELT (init, 0), args, complain);
18413 TREE_VEC_ELT (init, 1) = RECUR (TREE_VEC_ELT (init, 1));
18414 TREE_VEC_ELT (init, 2) = RECUR (TREE_VEC_ELT (init, 2));
18416 else
18417 init = RECUR (init);
18419 if (orig_declv && OMP_FOR_ORIG_DECLS (t))
18421 tree o = TREE_VEC_ELT (OMP_FOR_ORIG_DECLS (t), i);
18422 if (TREE_CODE (o) == TREE_LIST)
18423 TREE_VEC_ELT (orig_declv, i)
18424 = tree_cons (RECUR (TREE_PURPOSE (o)),
18425 RECUR (TREE_VALUE (o)),
18426 NULL_TREE);
18427 else
18428 TREE_VEC_ELT (orig_declv, i) = RECUR (o);
18431 if (range_for)
18433 tree this_pre_body = NULL_TREE;
18434 tree orig_init = NULL_TREE;
18435 tree orig_decl = NULL_TREE;
18436 cp_convert_omp_range_for (this_pre_body, NULL, decl, orig_decl, init,
18437 orig_init, cond, incr);
18438 if (orig_decl)
18440 if (orig_declv == NULL_TREE)
18441 orig_declv = copy_node (declv);
18442 TREE_VEC_ELT (orig_declv, i) = orig_decl;
18443 ret = true;
18445 else if (orig_declv)
18446 TREE_VEC_ELT (orig_declv, i) = decl;
18449 tree auto_node = type_uses_auto (TREE_TYPE (decl));
18450 if (!range_for && auto_node && init)
18451 TREE_TYPE (decl)
18452 = do_auto_deduction (TREE_TYPE (decl), init, auto_node, complain);
18454 gcc_assert (!type_dependent_expression_p (decl));
18456 if (!CLASS_TYPE_P (TREE_TYPE (decl)) || range_for)
18458 if (decl_expr)
18460 /* Declare the variable, but don't let that initialize it. */
18461 tree init_sav = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
18462 DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL_TREE;
18463 RECUR (decl_expr);
18464 DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init_sav;
18467 if (!range_for)
18469 cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
18470 if (COMPARISON_CLASS_P (cond)
18471 && TREE_CODE (TREE_OPERAND (cond, 1)) == TREE_VEC)
18473 tree lhs = RECUR (TREE_OPERAND (cond, 0));
18474 tree rhs = copy_node (TREE_OPERAND (cond, 1));
18475 TREE_VEC_ELT (rhs, 0)
18476 = tsubst_decl (TREE_VEC_ELT (rhs, 0), args, complain);
18477 TREE_VEC_ELT (rhs, 1) = RECUR (TREE_VEC_ELT (rhs, 1));
18478 TREE_VEC_ELT (rhs, 2) = RECUR (TREE_VEC_ELT (rhs, 2));
18479 cond = build2 (TREE_CODE (cond), TREE_TYPE (cond),
18480 lhs, rhs);
18482 else
18483 cond = RECUR (cond);
18484 incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
18485 if (TREE_CODE (incr) == MODIFY_EXPR)
18487 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18488 tree rhs = RECUR (TREE_OPERAND (incr, 1));
18489 incr = build_x_modify_expr (EXPR_LOCATION (incr), lhs,
18490 NOP_EXPR, rhs, NULL_TREE, complain);
18492 else
18493 incr = RECUR (incr);
18494 if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
18495 TREE_VEC_ELT (orig_declv, i) = decl;
18497 TREE_VEC_ELT (declv, i) = decl;
18498 TREE_VEC_ELT (initv, i) = init;
18499 TREE_VEC_ELT (condv, i) = cond;
18500 TREE_VEC_ELT (incrv, i) = incr;
18501 return ret;
18504 if (decl_expr)
18506 /* Declare and initialize the variable. */
18507 RECUR (decl_expr);
18508 init = NULL_TREE;
18510 else if (init)
18512 tree *pc;
18513 int j;
18514 for (j = ((omp_parallel_combined_clauses == NULL
18515 || TREE_CODE (t) == OMP_LOOP) ? 1 : 0); j < 2; j++)
18517 for (pc = j ? clauses : omp_parallel_combined_clauses; *pc; )
18519 if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_PRIVATE
18520 && OMP_CLAUSE_DECL (*pc) == decl)
18521 break;
18522 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_LASTPRIVATE
18523 && OMP_CLAUSE_DECL (*pc) == decl)
18525 if (j)
18526 break;
18527 /* Move lastprivate (decl) clause to OMP_FOR_CLAUSES. */
18528 tree c = *pc;
18529 *pc = OMP_CLAUSE_CHAIN (c);
18530 OMP_CLAUSE_CHAIN (c) = *clauses;
18531 *clauses = c;
18533 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_FIRSTPRIVATE
18534 && OMP_CLAUSE_DECL (*pc) == decl)
18536 error ("iteration variable %qD should not be firstprivate",
18537 decl);
18538 *pc = OMP_CLAUSE_CHAIN (*pc);
18540 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_REDUCTION
18541 && OMP_CLAUSE_DECL (*pc) == decl)
18543 error ("iteration variable %qD should not be reduction",
18544 decl);
18545 *pc = OMP_CLAUSE_CHAIN (*pc);
18547 else
18548 pc = &OMP_CLAUSE_CHAIN (*pc);
18550 if (*pc)
18551 break;
18553 if (*pc == NULL_TREE)
18555 tree c = build_omp_clause (input_location,
18556 TREE_CODE (t) == OMP_LOOP
18557 ? OMP_CLAUSE_LASTPRIVATE
18558 : OMP_CLAUSE_PRIVATE);
18559 OMP_CLAUSE_DECL (c) = decl;
18560 c = finish_omp_clauses (c, C_ORT_OMP);
18561 if (c)
18563 OMP_CLAUSE_CHAIN (c) = *clauses;
18564 *clauses = c;
18568 cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
18569 if (COMPARISON_CLASS_P (cond))
18571 tree op0 = RECUR (TREE_OPERAND (cond, 0));
18572 tree op1 = RECUR (TREE_OPERAND (cond, 1));
18573 cond = build2 (TREE_CODE (cond), boolean_type_node, op0, op1);
18575 else
18576 cond = RECUR (cond);
18577 incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
18578 switch (TREE_CODE (incr))
18580 case PREINCREMENT_EXPR:
18581 case PREDECREMENT_EXPR:
18582 case POSTINCREMENT_EXPR:
18583 case POSTDECREMENT_EXPR:
18584 incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
18585 RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
18586 break;
18587 case MODIFY_EXPR:
18588 if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
18589 || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
18591 tree rhs = TREE_OPERAND (incr, 1);
18592 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18593 tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
18594 tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
18595 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18596 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
18597 rhs0, rhs1));
18599 else
18600 incr = RECUR (incr);
18601 break;
18602 case MODOP_EXPR:
18603 if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
18604 || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
18606 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18607 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18608 build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
18609 TREE_TYPE (decl), lhs,
18610 RECUR (TREE_OPERAND (incr, 2))));
18612 else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
18613 && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
18614 || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
18616 tree rhs = TREE_OPERAND (incr, 2);
18617 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18618 tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
18619 tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
18620 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18621 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
18622 rhs0, rhs1));
18624 else
18625 incr = RECUR (incr);
18626 break;
18627 default:
18628 incr = RECUR (incr);
18629 break;
18632 if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
18633 TREE_VEC_ELT (orig_declv, i) = decl;
18634 TREE_VEC_ELT (declv, i) = decl;
18635 TREE_VEC_ELT (initv, i) = init;
18636 TREE_VEC_ELT (condv, i) = cond;
18637 TREE_VEC_ELT (incrv, i) = incr;
18638 return false;
18639 #undef RECUR
18642 /* Helper function of tsubst_expr, find OMP_TEAMS inside
18643 of OMP_TARGET's body. */
18645 static tree
18646 tsubst_find_omp_teams (tree *tp, int *walk_subtrees, void *)
18648 *walk_subtrees = 0;
18649 switch (TREE_CODE (*tp))
18651 case OMP_TEAMS:
18652 return *tp;
18653 case BIND_EXPR:
18654 case STATEMENT_LIST:
18655 *walk_subtrees = 1;
18656 break;
18657 default:
18658 break;
18660 return NULL_TREE;
18663 /* Helper function for tsubst_expr. For decomposition declaration
18664 artificial base DECL, which is tsubsted PATTERN_DECL, tsubst
18665 also the corresponding decls representing the identifiers
18666 of the decomposition declaration. Return DECL if successful
18667 or error_mark_node otherwise, set *FIRST to the first decl
18668 in the list chained through DECL_CHAIN and *CNT to the number
18669 of such decls. */
18671 static tree
18672 tsubst_decomp_names (tree decl, tree pattern_decl, tree args,
18673 tsubst_flags_t complain, tree in_decl, tree *first,
18674 unsigned int *cnt)
18676 tree decl2, decl3, prev = decl;
18677 *cnt = 0;
18678 gcc_assert (DECL_NAME (decl) == NULL_TREE);
18679 for (decl2 = DECL_CHAIN (pattern_decl);
18680 decl2
18681 && VAR_P (decl2)
18682 && DECL_DECOMPOSITION_P (decl2)
18683 && DECL_NAME (decl2);
18684 decl2 = DECL_CHAIN (decl2))
18686 if (TREE_TYPE (decl2) == error_mark_node && *cnt == 0)
18688 gcc_assert (errorcount);
18689 return error_mark_node;
18691 (*cnt)++;
18692 gcc_assert (DECL_DECOMP_BASE (decl2) == pattern_decl);
18693 gcc_assert (DECL_HAS_VALUE_EXPR_P (decl2));
18694 tree v = DECL_VALUE_EXPR (decl2);
18695 DECL_HAS_VALUE_EXPR_P (decl2) = 0;
18696 SET_DECL_VALUE_EXPR (decl2, NULL_TREE);
18697 decl3 = tsubst (decl2, args, complain, in_decl);
18698 SET_DECL_VALUE_EXPR (decl2, v);
18699 DECL_HAS_VALUE_EXPR_P (decl2) = 1;
18700 if (VAR_P (decl3))
18701 DECL_TEMPLATE_INSTANTIATED (decl3) = 1;
18702 else
18704 gcc_assert (errorcount);
18705 decl = error_mark_node;
18706 continue;
18708 maybe_push_decl (decl3);
18709 if (error_operand_p (decl3))
18710 decl = error_mark_node;
18711 else if (decl != error_mark_node
18712 && DECL_CHAIN (decl3) != prev
18713 && decl != prev)
18715 gcc_assert (errorcount);
18716 decl = error_mark_node;
18718 else
18719 prev = decl3;
18721 *first = prev;
18722 return decl;
18725 /* Return the proper local_specialization for init-capture pack DECL. */
18727 static tree
18728 lookup_init_capture_pack (tree decl)
18730 /* We handle normal pack captures by forwarding to the specialization of the
18731 captured parameter. We can't do that for pack init-captures; we need them
18732 to have their own local_specialization. We created the individual
18733 VAR_DECLs (if any) under build_capture_proxy, and we need to collect them
18734 when we process the DECL_EXPR for the pack init-capture in the template.
18735 So, how do we find them? We don't know the capture proxy pack when
18736 building the individual resulting proxies, and we don't know the
18737 individual proxies when instantiating the pack. What we have in common is
18738 the FIELD_DECL.
18740 So...when we instantiate the FIELD_DECL, we stick the result in
18741 local_specializations. Then at the DECL_EXPR we look up that result, see
18742 how many elements it has, synthesize the names, and look them up. */
18744 tree cname = DECL_NAME (decl);
18745 tree val = DECL_VALUE_EXPR (decl);
18746 tree field = TREE_OPERAND (val, 1);
18747 gcc_assert (TREE_CODE (field) == FIELD_DECL);
18748 tree fpack = retrieve_local_specialization (field);
18749 if (fpack == error_mark_node)
18750 return error_mark_node;
18752 int len = 1;
18753 tree vec = NULL_TREE;
18754 tree r = NULL_TREE;
18755 if (TREE_CODE (fpack) == TREE_VEC)
18757 len = TREE_VEC_LENGTH (fpack);
18758 vec = make_tree_vec (len);
18759 r = make_node (NONTYPE_ARGUMENT_PACK);
18760 ARGUMENT_PACK_ARGS (r) = vec;
18762 for (int i = 0; i < len; ++i)
18764 tree ename = vec ? make_ith_pack_parameter_name (cname, i) : cname;
18765 tree elt = lookup_name (ename);
18766 if (vec)
18767 TREE_VEC_ELT (vec, i) = elt;
18768 else
18769 r = elt;
18771 return r;
18774 /* T is an operand of a template tree being substituted. Return whether
18775 T is dependent such that we should suppress some warnings that would
18776 make sense if the substituted expression were written directly, like
18777 template <int I> bool f() { return I == 2; }
18778 We don't want to warn when instantiating f that comparing two constants
18779 always has the same value.
18781 This is a more limited concept of dependence than instantiation-dependent;
18782 here we don't care whether substitution could fail. */
18784 static bool
18785 dependent_operand_p (tree t)
18787 while (TREE_CODE (t) == IMPLICIT_CONV_EXPR)
18788 t = TREE_OPERAND (t, 0);
18789 ++processing_template_decl;
18790 bool r = (potential_constant_expression (t)
18791 ? value_dependent_expression_p (t)
18792 : type_dependent_expression_p (t));
18793 --processing_template_decl;
18794 return r;
18797 /* Like tsubst_copy for expressions, etc. but also does semantic
18798 processing. */
18800 tree
18801 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
18803 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
18804 #define RECUR(NODE) \
18805 tsubst_expr ((NODE), args, complain, in_decl)
18807 tree stmt, tmp;
18808 tree r;
18809 location_t loc;
18811 if (t == NULL_TREE || t == error_mark_node)
18812 return t;
18814 loc = input_location;
18815 if (location_t eloc = cp_expr_location (t))
18816 input_location = eloc;
18817 if (STATEMENT_CODE_P (TREE_CODE (t)))
18818 current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
18820 switch (TREE_CODE (t))
18822 case STATEMENT_LIST:
18824 for (tree stmt : tsi_range (t))
18825 RECUR (stmt);
18826 break;
18829 case CTOR_INITIALIZER:
18830 finish_mem_initializers (tsubst_initializer_list
18831 (TREE_OPERAND (t, 0), args));
18832 break;
18834 case RETURN_EXPR:
18835 finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
18836 break;
18838 case CO_RETURN_EXPR:
18839 finish_co_return_stmt (input_location, RECUR (TREE_OPERAND (t, 0)));
18840 break;
18842 case CO_YIELD_EXPR:
18843 stmt = finish_co_yield_expr (input_location,
18844 RECUR (TREE_OPERAND (t, 0)));
18845 RETURN (stmt);
18847 case CO_AWAIT_EXPR:
18848 stmt = finish_co_await_expr (input_location,
18849 RECUR (TREE_OPERAND (t, 0)));
18850 RETURN (stmt);
18852 case EXPR_STMT:
18853 tmp = RECUR (EXPR_STMT_EXPR (t));
18854 if (EXPR_STMT_STMT_EXPR_RESULT (t))
18855 finish_stmt_expr_expr (tmp, cur_stmt_expr);
18856 else
18857 finish_expr_stmt (tmp);
18858 break;
18860 case USING_STMT:
18861 finish_using_directive (USING_STMT_NAMESPACE (t), /*attribs=*/NULL_TREE);
18862 break;
18864 case PRECONDITION_STMT:
18865 case POSTCONDITION_STMT:
18866 gcc_unreachable ();
18868 case ASSERTION_STMT:
18870 r = tsubst_contract (NULL_TREE, t, args, complain, in_decl);
18871 if (r != error_mark_node)
18872 add_stmt (r);
18873 RETURN (r);
18875 break;
18877 case DECL_EXPR:
18879 tree decl, pattern_decl;
18880 tree init;
18882 pattern_decl = decl = DECL_EXPR_DECL (t);
18883 if (TREE_CODE (decl) == LABEL_DECL)
18884 finish_label_decl (DECL_NAME (decl));
18885 else if (TREE_CODE (decl) == USING_DECL)
18887 tree scope = USING_DECL_SCOPE (decl);
18888 if (DECL_DEPENDENT_P (decl))
18890 scope = tsubst (scope, args, complain, in_decl);
18891 if (!MAYBE_CLASS_TYPE_P (scope)
18892 && TREE_CODE (scope) != ENUMERAL_TYPE)
18894 if (complain & tf_error)
18895 error_at (DECL_SOURCE_LOCATION (decl), "%qT is not a "
18896 "class, namespace, or enumeration", scope);
18897 return error_mark_node;
18899 finish_nonmember_using_decl (scope, DECL_NAME (decl));
18901 else
18903 /* This is a non-dependent using-decl, and we'll have
18904 used the names it found during template parsing. We do
18905 not want to do the lookup again, because we might not
18906 find the things we found then. */
18907 gcc_checking_assert (scope == tsubst (scope, args,
18908 complain, in_decl));
18909 /* We still need to push the bindings so that we can look up
18910 this name later. */
18911 push_using_decl_bindings (DECL_NAME (decl),
18912 USING_DECL_DECLS (decl));
18915 else if (is_capture_proxy (decl)
18916 && !DECL_TEMPLATE_INSTANTIATION (current_function_decl))
18918 /* We're in tsubst_lambda_expr, we've already inserted a new
18919 capture proxy, so look it up and register it. */
18920 tree inst;
18921 if (!DECL_PACK_P (decl))
18923 inst = lookup_name (DECL_NAME (decl), LOOK_where::BLOCK,
18924 LOOK_want::HIDDEN_LAMBDA);
18925 gcc_assert (inst != decl && is_capture_proxy (inst));
18927 else if (is_normal_capture_proxy (decl))
18929 inst = (retrieve_local_specialization
18930 (DECL_CAPTURED_VARIABLE (decl)));
18931 gcc_assert (TREE_CODE (inst) == NONTYPE_ARGUMENT_PACK
18932 || DECL_PACK_P (inst));
18934 else
18935 inst = lookup_init_capture_pack (decl);
18937 register_local_specialization (inst, decl);
18938 break;
18940 else if (DECL_PRETTY_FUNCTION_P (decl))
18941 decl = make_fname_decl (DECL_SOURCE_LOCATION (decl),
18942 DECL_NAME (decl),
18943 true/*DECL_PRETTY_FUNCTION_P (decl)*/);
18944 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
18945 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
18946 /* Don't copy the old closure; we'll create a new one in
18947 tsubst_lambda_expr. */
18948 break;
18949 else
18951 init = DECL_INITIAL (decl);
18952 decl = tsubst (decl, args, complain, in_decl);
18953 if (decl != error_mark_node)
18955 /* By marking the declaration as instantiated, we avoid
18956 trying to instantiate it. Since instantiate_decl can't
18957 handle local variables, and since we've already done
18958 all that needs to be done, that's the right thing to
18959 do. */
18960 if (VAR_P (decl))
18961 DECL_TEMPLATE_INSTANTIATED (decl) = 1;
18962 if (VAR_P (decl) && !DECL_NAME (decl)
18963 && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
18964 /* Anonymous aggregates are a special case. */
18965 finish_anon_union (decl);
18966 else if (is_capture_proxy (DECL_EXPR_DECL (t)))
18968 DECL_CONTEXT (decl) = current_function_decl;
18969 if (DECL_NAME (decl) == this_identifier)
18971 tree lam = DECL_CONTEXT (current_function_decl);
18972 lam = CLASSTYPE_LAMBDA_EXPR (lam);
18973 LAMBDA_EXPR_THIS_CAPTURE (lam) = decl;
18975 insert_capture_proxy (decl);
18977 else if (DECL_IMPLICIT_TYPEDEF_P (t))
18978 /* We already did a pushtag. */;
18979 else if (VAR_OR_FUNCTION_DECL_P (decl)
18980 && DECL_LOCAL_DECL_P (decl))
18982 if (TREE_CODE (DECL_CONTEXT (decl)) == FUNCTION_DECL)
18983 DECL_CONTEXT (decl) = NULL_TREE;
18984 decl = pushdecl (decl);
18985 if (TREE_CODE (decl) == FUNCTION_DECL
18986 && DECL_OMP_DECLARE_REDUCTION_P (decl)
18987 && cp_check_omp_declare_reduction (decl))
18988 instantiate_body (pattern_decl, args, decl, true);
18990 else
18992 bool const_init = false;
18993 unsigned int cnt = 0;
18994 tree first = NULL_TREE, ndecl = error_mark_node;
18995 tree asmspec_tree = NULL_TREE;
18996 maybe_push_decl (decl);
18998 if (VAR_P (decl)
18999 && DECL_LANG_SPECIFIC (decl)
19000 && DECL_OMP_PRIVATIZED_MEMBER (decl))
19001 break;
19003 if (VAR_P (decl)
19004 && DECL_DECOMPOSITION_P (decl)
19005 && TREE_TYPE (pattern_decl) != error_mark_node)
19006 ndecl = tsubst_decomp_names (decl, pattern_decl, args,
19007 complain, in_decl, &first,
19008 &cnt);
19010 init = tsubst_init (init, decl, args, complain, in_decl);
19012 if (VAR_P (decl))
19013 const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
19014 (pattern_decl));
19016 if (ndecl != error_mark_node)
19017 cp_maybe_mangle_decomp (ndecl, first, cnt);
19019 /* In a non-template function, VLA type declarations are
19020 handled in grokdeclarator; for templates, handle them
19021 now. */
19022 predeclare_vla (decl);
19024 if (VAR_P (decl) && DECL_HARD_REGISTER (pattern_decl))
19026 tree id = DECL_ASSEMBLER_NAME (pattern_decl);
19027 const char *asmspec = IDENTIFIER_POINTER (id);
19028 gcc_assert (asmspec[0] == '*');
19029 asmspec_tree
19030 = build_string (IDENTIFIER_LENGTH (id) - 1,
19031 asmspec + 1);
19032 TREE_TYPE (asmspec_tree) = char_array_type_node;
19035 cp_finish_decl (decl, init, const_init, asmspec_tree, 0);
19037 if (ndecl != error_mark_node)
19038 cp_finish_decomp (ndecl, first, cnt);
19043 break;
19046 case FOR_STMT:
19047 stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
19048 RECUR (FOR_INIT_STMT (t));
19049 finish_init_stmt (stmt);
19050 tmp = RECUR (FOR_COND (t));
19051 finish_for_cond (tmp, stmt, false, 0);
19052 tmp = RECUR (FOR_EXPR (t));
19053 finish_for_expr (tmp, stmt);
19055 bool prev = note_iteration_stmt_body_start ();
19056 RECUR (FOR_BODY (t));
19057 note_iteration_stmt_body_end (prev);
19059 finish_for_stmt (stmt);
19060 break;
19062 case RANGE_FOR_STMT:
19064 /* Construct another range_for, if this is not a final
19065 substitution (for inside a generic lambda of a
19066 template). Otherwise convert to a regular for. */
19067 tree decl, expr;
19068 stmt = (processing_template_decl
19069 ? begin_range_for_stmt (NULL_TREE, NULL_TREE)
19070 : begin_for_stmt (NULL_TREE, NULL_TREE));
19071 RECUR (RANGE_FOR_INIT_STMT (t));
19072 decl = RANGE_FOR_DECL (t);
19073 decl = tsubst (decl, args, complain, in_decl);
19074 maybe_push_decl (decl);
19075 expr = RECUR (RANGE_FOR_EXPR (t));
19077 tree decomp_first = NULL_TREE;
19078 unsigned decomp_cnt = 0;
19079 if (VAR_P (decl) && DECL_DECOMPOSITION_P (decl))
19080 decl = tsubst_decomp_names (decl, RANGE_FOR_DECL (t), args,
19081 complain, in_decl,
19082 &decomp_first, &decomp_cnt);
19084 if (processing_template_decl)
19086 RANGE_FOR_IVDEP (stmt) = RANGE_FOR_IVDEP (t);
19087 RANGE_FOR_UNROLL (stmt) = RANGE_FOR_UNROLL (t);
19088 finish_range_for_decl (stmt, decl, expr);
19089 if (decomp_first && decl != error_mark_node)
19090 cp_finish_decomp (decl, decomp_first, decomp_cnt);
19092 else
19094 unsigned short unroll = (RANGE_FOR_UNROLL (t)
19095 ? tree_to_uhwi (RANGE_FOR_UNROLL (t)) : 0);
19096 stmt = cp_convert_range_for (stmt, decl, expr,
19097 decomp_first, decomp_cnt,
19098 RANGE_FOR_IVDEP (t), unroll);
19101 bool prev = note_iteration_stmt_body_start ();
19102 RECUR (RANGE_FOR_BODY (t));
19103 note_iteration_stmt_body_end (prev);
19104 finish_for_stmt (stmt);
19106 break;
19108 case WHILE_STMT:
19109 stmt = begin_while_stmt ();
19110 tmp = RECUR (WHILE_COND (t));
19111 finish_while_stmt_cond (tmp, stmt, false, 0);
19113 bool prev = note_iteration_stmt_body_start ();
19114 RECUR (WHILE_BODY (t));
19115 note_iteration_stmt_body_end (prev);
19117 finish_while_stmt (stmt);
19118 break;
19120 case DO_STMT:
19121 stmt = begin_do_stmt ();
19123 bool prev = note_iteration_stmt_body_start ();
19124 RECUR (DO_BODY (t));
19125 note_iteration_stmt_body_end (prev);
19127 finish_do_body (stmt);
19128 tmp = RECUR (DO_COND (t));
19129 finish_do_stmt (tmp, stmt, false, 0);
19130 break;
19132 case IF_STMT:
19133 stmt = begin_if_stmt ();
19134 IF_STMT_CONSTEXPR_P (stmt) = IF_STMT_CONSTEXPR_P (t);
19135 IF_STMT_CONSTEVAL_P (stmt) = IF_STMT_CONSTEVAL_P (t);
19136 if (IF_STMT_CONSTEXPR_P (t))
19137 args = add_extra_args (IF_STMT_EXTRA_ARGS (t), args, complain, in_decl);
19139 tree cond = IF_COND (t);
19140 bool was_dep = dependent_operand_p (cond);
19141 cond = RECUR (cond);
19142 warning_sentinel s1(warn_address, was_dep);
19143 tmp = finish_if_stmt_cond (cond, stmt);
19145 if (IF_STMT_CONSTEXPR_P (t)
19146 && instantiation_dependent_expression_p (tmp))
19148 /* We're partially instantiating a generic lambda, but the condition
19149 of the constexpr if is still dependent. Don't substitute into the
19150 branches now, just remember the template arguments. */
19151 do_poplevel (IF_SCOPE (stmt));
19152 IF_COND (stmt) = IF_COND (t);
19153 THEN_CLAUSE (stmt) = THEN_CLAUSE (t);
19154 ELSE_CLAUSE (stmt) = ELSE_CLAUSE (t);
19155 IF_STMT_EXTRA_ARGS (stmt) = build_extra_args (t, args, complain);
19156 add_stmt (stmt);
19157 break;
19159 if (IF_STMT_CONSTEXPR_P (t) && integer_zerop (tmp))
19160 /* Don't instantiate the THEN_CLAUSE. */;
19161 else if (IF_STMT_CONSTEVAL_P (t))
19163 bool save_in_consteval_if_p = in_consteval_if_p;
19164 in_consteval_if_p = true;
19165 RECUR (THEN_CLAUSE (t));
19166 in_consteval_if_p = save_in_consteval_if_p;
19168 else
19170 tree folded = fold_non_dependent_expr (tmp, complain);
19171 bool inhibit = integer_zerop (folded);
19172 if (inhibit)
19173 ++c_inhibit_evaluation_warnings;
19174 RECUR (THEN_CLAUSE (t));
19175 if (inhibit)
19176 --c_inhibit_evaluation_warnings;
19178 finish_then_clause (stmt);
19180 if (IF_STMT_CONSTEXPR_P (t) && integer_nonzerop (tmp))
19181 /* Don't instantiate the ELSE_CLAUSE. */;
19182 else if (ELSE_CLAUSE (t))
19184 tree folded = fold_non_dependent_expr (tmp, complain);
19185 bool inhibit = integer_nonzerop (folded);
19186 begin_else_clause (stmt);
19187 if (inhibit)
19188 ++c_inhibit_evaluation_warnings;
19189 RECUR (ELSE_CLAUSE (t));
19190 if (inhibit)
19191 --c_inhibit_evaluation_warnings;
19192 finish_else_clause (stmt);
19195 finish_if_stmt (stmt);
19196 break;
19198 case BIND_EXPR:
19199 if (BIND_EXPR_BODY_BLOCK (t))
19200 stmt = begin_function_body ();
19201 else
19202 stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
19203 ? BCS_TRY_BLOCK : 0);
19205 RECUR (BIND_EXPR_BODY (t));
19207 if (BIND_EXPR_BODY_BLOCK (t))
19208 finish_function_body (stmt);
19209 else
19210 finish_compound_stmt (stmt);
19211 break;
19213 case BREAK_STMT:
19214 finish_break_stmt ();
19215 break;
19217 case CONTINUE_STMT:
19218 finish_continue_stmt ();
19219 break;
19221 case SWITCH_STMT:
19222 stmt = begin_switch_stmt ();
19223 tmp = RECUR (SWITCH_STMT_COND (t));
19224 finish_switch_cond (tmp, stmt);
19225 RECUR (SWITCH_STMT_BODY (t));
19226 finish_switch_stmt (stmt);
19227 break;
19229 case CASE_LABEL_EXPR:
19231 tree decl = CASE_LABEL (t);
19232 tree low = RECUR (CASE_LOW (t));
19233 tree high = RECUR (CASE_HIGH (t));
19234 tree l = finish_case_label (EXPR_LOCATION (t), low, high);
19235 if (l && TREE_CODE (l) == CASE_LABEL_EXPR)
19237 tree label = CASE_LABEL (l);
19238 FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
19239 if (DECL_ATTRIBUTES (decl) != NULL_TREE)
19240 cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
19243 break;
19245 case LABEL_EXPR:
19247 tree decl = LABEL_EXPR_LABEL (t);
19248 tree label;
19250 label = finish_label_stmt (DECL_NAME (decl));
19251 if (TREE_CODE (label) == LABEL_DECL)
19252 FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
19253 if (DECL_ATTRIBUTES (decl) != NULL_TREE)
19254 cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
19256 break;
19258 case GOTO_EXPR:
19259 tmp = GOTO_DESTINATION (t);
19260 if (TREE_CODE (tmp) != LABEL_DECL)
19261 /* Computed goto's must be tsubst'd into. On the other hand,
19262 non-computed gotos must not be; the identifier in question
19263 will have no binding. */
19264 tmp = RECUR (tmp);
19265 else
19266 tmp = DECL_NAME (tmp);
19267 finish_goto_stmt (tmp);
19268 break;
19270 case ASM_EXPR:
19272 tree string = RECUR (ASM_STRING (t));
19273 tree outputs = tsubst_copy_asm_operands (ASM_OUTPUTS (t), args,
19274 complain, in_decl);
19275 tree inputs = tsubst_copy_asm_operands (ASM_INPUTS (t), args,
19276 complain, in_decl);
19277 tree clobbers = tsubst_copy_asm_operands (ASM_CLOBBERS (t), args,
19278 complain, in_decl);
19279 tree labels = tsubst_copy_asm_operands (ASM_LABELS (t), args,
19280 complain, in_decl);
19281 tmp = finish_asm_stmt (EXPR_LOCATION (t), ASM_VOLATILE_P (t), string,
19282 outputs, inputs, clobbers, labels,
19283 ASM_INLINE_P (t));
19284 tree asm_expr = tmp;
19285 if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
19286 asm_expr = TREE_OPERAND (asm_expr, 0);
19287 ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
19289 break;
19291 case TRY_BLOCK:
19292 if (CLEANUP_P (t))
19294 stmt = begin_try_block ();
19295 RECUR (TRY_STMTS (t));
19296 finish_cleanup_try_block (stmt);
19297 finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
19299 else
19301 tree compound_stmt = NULL_TREE;
19303 if (FN_TRY_BLOCK_P (t))
19304 stmt = begin_function_try_block (&compound_stmt);
19305 else
19306 stmt = begin_try_block ();
19308 RECUR (TRY_STMTS (t));
19310 if (FN_TRY_BLOCK_P (t))
19311 finish_function_try_block (stmt);
19312 else
19313 finish_try_block (stmt);
19315 RECUR (TRY_HANDLERS (t));
19316 if (FN_TRY_BLOCK_P (t))
19317 finish_function_handler_sequence (stmt, compound_stmt);
19318 else
19319 finish_handler_sequence (stmt);
19321 break;
19323 case HANDLER:
19325 tree decl = HANDLER_PARMS (t);
19327 if (decl)
19329 decl = tsubst (decl, args, complain, in_decl);
19330 /* Prevent instantiate_decl from trying to instantiate
19331 this variable. We've already done all that needs to be
19332 done. */
19333 if (decl != error_mark_node)
19334 DECL_TEMPLATE_INSTANTIATED (decl) = 1;
19336 stmt = begin_handler ();
19337 finish_handler_parms (decl, stmt);
19338 RECUR (HANDLER_BODY (t));
19339 finish_handler (stmt);
19341 break;
19343 case TAG_DEFN:
19344 tmp = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
19345 if (CLASS_TYPE_P (tmp))
19347 /* Local classes are not independent templates; they are
19348 instantiated along with their containing function. And this
19349 way we don't have to deal with pushing out of one local class
19350 to instantiate a member of another local class. */
19351 /* Closures are handled by the LAMBDA_EXPR. */
19352 gcc_assert (!LAMBDA_TYPE_P (TREE_TYPE (t)));
19353 complete_type (tmp);
19354 if (dependent_type_p (tmp))
19356 /* This is a partial instantiation, try again when full. */
19357 add_stmt (build_min (TAG_DEFN, tmp));
19358 break;
19360 tree save_ccp = current_class_ptr;
19361 tree save_ccr = current_class_ref;
19362 for (tree fld = TYPE_FIELDS (tmp); fld; fld = DECL_CHAIN (fld))
19363 if ((VAR_P (fld)
19364 || (TREE_CODE (fld) == FUNCTION_DECL
19365 && !DECL_ARTIFICIAL (fld)))
19366 && DECL_TEMPLATE_INSTANTIATION (fld))
19367 instantiate_decl (fld, /*defer_ok=*/false,
19368 /*expl_inst_class=*/false);
19369 else if (TREE_CODE (fld) == FIELD_DECL)
19370 maybe_instantiate_nsdmi_init (fld, tf_warning_or_error);
19371 current_class_ptr = save_ccp;
19372 current_class_ref = save_ccr;
19374 break;
19376 case STATIC_ASSERT:
19378 tree condition;
19380 ++c_inhibit_evaluation_warnings;
19381 condition = tsubst_expr (STATIC_ASSERT_CONDITION (t), args,
19382 complain, in_decl);
19383 --c_inhibit_evaluation_warnings;
19385 finish_static_assert (condition,
19386 STATIC_ASSERT_MESSAGE (t),
19387 STATIC_ASSERT_SOURCE_LOCATION (t),
19388 /*member_p=*/false, /*show_expr_p=*/true);
19390 break;
19392 case OACC_KERNELS:
19393 case OACC_PARALLEL:
19394 case OACC_SERIAL:
19395 tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_ACC, args, complain,
19396 in_decl);
19397 stmt = begin_omp_parallel ();
19398 RECUR (OMP_BODY (t));
19399 finish_omp_construct (TREE_CODE (t), stmt, tmp);
19400 break;
19402 case OMP_PARALLEL:
19403 r = push_omp_privatization_clauses (OMP_PARALLEL_COMBINED (t));
19404 tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t), C_ORT_OMP, args,
19405 complain, in_decl);
19406 if (OMP_PARALLEL_COMBINED (t))
19407 omp_parallel_combined_clauses = &tmp;
19408 stmt = begin_omp_parallel ();
19409 RECUR (OMP_PARALLEL_BODY (t));
19410 gcc_assert (omp_parallel_combined_clauses == NULL);
19411 OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
19412 = OMP_PARALLEL_COMBINED (t);
19413 pop_omp_privatization_clauses (r);
19414 break;
19416 case OMP_TASK:
19417 if (OMP_TASK_BODY (t) == NULL_TREE)
19419 tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
19420 complain, in_decl);
19421 t = copy_node (t);
19422 OMP_TASK_CLAUSES (t) = tmp;
19423 add_stmt (t);
19424 break;
19426 r = push_omp_privatization_clauses (false);
19427 tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
19428 complain, in_decl);
19429 stmt = begin_omp_task ();
19430 RECUR (OMP_TASK_BODY (t));
19431 finish_omp_task (tmp, stmt);
19432 pop_omp_privatization_clauses (r);
19433 break;
19435 case OMP_FOR:
19436 case OMP_LOOP:
19437 case OMP_SIMD:
19438 case OMP_DISTRIBUTE:
19439 case OMP_TASKLOOP:
19440 case OACC_LOOP:
19442 tree clauses, body, pre_body;
19443 tree declv = NULL_TREE, initv = NULL_TREE, condv = NULL_TREE;
19444 tree orig_declv = NULL_TREE;
19445 tree incrv = NULL_TREE;
19446 enum c_omp_region_type ort = C_ORT_OMP;
19447 bool any_range_for = false;
19448 int i;
19450 if (TREE_CODE (t) == OACC_LOOP)
19451 ort = C_ORT_ACC;
19453 r = push_omp_privatization_clauses (OMP_FOR_INIT (t) == NULL_TREE);
19454 clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t), ort, args, complain,
19455 in_decl);
19456 if (OMP_FOR_INIT (t) != NULL_TREE)
19458 declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19459 if (OMP_FOR_ORIG_DECLS (t))
19460 orig_declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19461 initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19462 condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19463 incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19466 keep_next_level (true);
19467 stmt = begin_omp_structured_block ();
19469 pre_body = push_stmt_list ();
19470 RECUR (OMP_FOR_PRE_BODY (t));
19471 pre_body = pop_stmt_list (pre_body);
19473 if (OMP_FOR_INIT (t) != NULL_TREE)
19474 for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
19475 any_range_for
19476 |= tsubst_omp_for_iterator (t, i, declv, orig_declv, initv,
19477 condv, incrv, &clauses, args,
19478 complain, in_decl);
19479 omp_parallel_combined_clauses = NULL;
19481 if (any_range_for)
19483 gcc_assert (orig_declv);
19484 body = begin_omp_structured_block ();
19485 for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
19486 if (TREE_VEC_ELT (orig_declv, i) != TREE_VEC_ELT (declv, i)
19487 && TREE_CODE (TREE_VEC_ELT (orig_declv, i)) == TREE_LIST
19488 && TREE_CHAIN (TREE_VEC_ELT (orig_declv, i)))
19489 cp_finish_omp_range_for (TREE_VEC_ELT (orig_declv, i),
19490 TREE_VEC_ELT (declv, i));
19492 else
19493 body = push_stmt_list ();
19494 RECUR (OMP_FOR_BODY (t));
19495 if (any_range_for)
19496 body = finish_omp_structured_block (body);
19497 else
19498 body = pop_stmt_list (body);
19500 if (OMP_FOR_INIT (t) != NULL_TREE)
19501 t = finish_omp_for (EXPR_LOCATION (t), TREE_CODE (t), declv,
19502 orig_declv, initv, condv, incrv, body, pre_body,
19503 NULL, clauses);
19504 else
19506 t = make_node (TREE_CODE (t));
19507 TREE_TYPE (t) = void_type_node;
19508 OMP_FOR_BODY (t) = body;
19509 OMP_FOR_PRE_BODY (t) = pre_body;
19510 OMP_FOR_CLAUSES (t) = clauses;
19511 SET_EXPR_LOCATION (t, EXPR_LOCATION (t));
19512 add_stmt (t);
19515 add_stmt (finish_omp_for_block (finish_omp_structured_block (stmt),
19516 t));
19517 pop_omp_privatization_clauses (r);
19519 break;
19521 case OMP_SECTIONS:
19522 case OMP_MASKED:
19523 omp_parallel_combined_clauses = NULL;
19524 /* FALLTHRU */
19525 case OMP_SINGLE:
19526 case OMP_SCOPE:
19527 case OMP_TEAMS:
19528 case OMP_CRITICAL:
19529 case OMP_TASKGROUP:
19530 case OMP_SCAN:
19531 r = push_omp_privatization_clauses (TREE_CODE (t) == OMP_TEAMS
19532 && OMP_TEAMS_COMBINED (t));
19533 tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_OMP, args, complain,
19534 in_decl);
19535 if (TREE_CODE (t) == OMP_TEAMS)
19537 keep_next_level (true);
19538 stmt = begin_omp_structured_block ();
19539 RECUR (OMP_BODY (t));
19540 stmt = finish_omp_structured_block (stmt);
19542 else
19544 stmt = push_stmt_list ();
19545 RECUR (OMP_BODY (t));
19546 stmt = pop_stmt_list (stmt);
19549 if (TREE_CODE (t) == OMP_CRITICAL
19550 && tmp != NULL_TREE
19551 && integer_nonzerop (OMP_CLAUSE_HINT_EXPR (tmp)))
19553 error_at (OMP_CLAUSE_LOCATION (tmp),
19554 "%<#pragma omp critical%> with %<hint%> clause requires "
19555 "a name, except when %<omp_sync_hint_none%> is used");
19556 RETURN (error_mark_node);
19558 t = copy_node (t);
19559 OMP_BODY (t) = stmt;
19560 OMP_CLAUSES (t) = tmp;
19561 add_stmt (t);
19562 pop_omp_privatization_clauses (r);
19563 break;
19565 case OMP_DEPOBJ:
19566 r = RECUR (OMP_DEPOBJ_DEPOBJ (t));
19567 if (OMP_DEPOBJ_CLAUSES (t) && OMP_DEPOBJ_CLAUSES (t) != error_mark_node)
19569 enum omp_clause_depend_kind kind = OMP_CLAUSE_DEPEND_INVALID;
19570 if (TREE_CODE (OMP_DEPOBJ_CLAUSES (t)) == OMP_CLAUSE)
19572 tmp = tsubst_omp_clauses (OMP_DEPOBJ_CLAUSES (t), C_ORT_OMP,
19573 args, complain, in_decl);
19574 if (tmp == NULL_TREE)
19575 tmp = error_mark_node;
19577 else
19579 kind = (enum omp_clause_depend_kind)
19580 tree_to_uhwi (OMP_DEPOBJ_CLAUSES (t));
19581 tmp = NULL_TREE;
19583 finish_omp_depobj (EXPR_LOCATION (t), r, kind, tmp);
19585 else
19586 finish_omp_depobj (EXPR_LOCATION (t), r,
19587 OMP_CLAUSE_DEPEND_INVALID,
19588 OMP_DEPOBJ_CLAUSES (t));
19589 break;
19591 case OACC_DATA:
19592 case OMP_TARGET_DATA:
19593 case OMP_TARGET:
19594 tmp = tsubst_omp_clauses (OMP_CLAUSES (t),
19595 TREE_CODE (t) == OACC_DATA
19596 ? C_ORT_ACC
19597 : TREE_CODE (t) == OMP_TARGET
19598 ? C_ORT_OMP_TARGET : C_ORT_OMP,
19599 args, complain, in_decl);
19600 keep_next_level (true);
19601 stmt = begin_omp_structured_block ();
19603 RECUR (OMP_BODY (t));
19604 stmt = finish_omp_structured_block (stmt);
19606 t = copy_node (t);
19607 OMP_BODY (t) = stmt;
19608 OMP_CLAUSES (t) = tmp;
19610 if (TREE_CODE (t) == OMP_TARGET)
19611 finish_omp_target_clauses (EXPR_LOCATION (t), OMP_BODY (t),
19612 &OMP_CLAUSES (t));
19614 if (TREE_CODE (t) == OMP_TARGET && OMP_TARGET_COMBINED (t))
19616 tree teams = cp_walk_tree (&stmt, tsubst_find_omp_teams, NULL, NULL);
19617 if (teams)
19618 /* For combined target teams, ensure the num_teams and
19619 thread_limit clause expressions are evaluated on the host,
19620 before entering the target construct. */
19621 for (tree c = OMP_TEAMS_CLAUSES (teams);
19622 c; c = OMP_CLAUSE_CHAIN (c))
19623 if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS
19624 || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_THREAD_LIMIT)
19625 for (int i = 0;
19626 i <= (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS); ++i)
19627 if (OMP_CLAUSE_OPERAND (c, i)
19628 && TREE_CODE (OMP_CLAUSE_OPERAND (c, i)) != INTEGER_CST)
19630 tree expr = OMP_CLAUSE_OPERAND (c, i);
19631 expr = force_target_expr (TREE_TYPE (expr), expr,
19632 tf_none);
19633 if (expr == error_mark_node)
19634 continue;
19635 tmp = TARGET_EXPR_SLOT (expr);
19636 add_stmt (expr);
19637 OMP_CLAUSE_OPERAND (c, i) = expr;
19638 tree tc = build_omp_clause (OMP_CLAUSE_LOCATION (c),
19639 OMP_CLAUSE_FIRSTPRIVATE);
19640 OMP_CLAUSE_DECL (tc) = tmp;
19641 OMP_CLAUSE_CHAIN (tc) = OMP_TARGET_CLAUSES (t);
19642 OMP_TARGET_CLAUSES (t) = tc;
19645 add_stmt (t);
19646 break;
19648 case OACC_DECLARE:
19649 t = copy_node (t);
19650 tmp = tsubst_omp_clauses (OACC_DECLARE_CLAUSES (t), C_ORT_ACC, args,
19651 complain, in_decl);
19652 OACC_DECLARE_CLAUSES (t) = tmp;
19653 add_stmt (t);
19654 break;
19656 case OMP_TARGET_UPDATE:
19657 case OMP_TARGET_ENTER_DATA:
19658 case OMP_TARGET_EXIT_DATA:
19659 tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_OMP, args,
19660 complain, in_decl);
19661 t = copy_node (t);
19662 OMP_STANDALONE_CLAUSES (t) = tmp;
19663 add_stmt (t);
19664 break;
19666 case OACC_CACHE:
19667 case OACC_ENTER_DATA:
19668 case OACC_EXIT_DATA:
19669 case OACC_UPDATE:
19670 tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_ACC, args,
19671 complain, in_decl);
19672 t = copy_node (t);
19673 OMP_STANDALONE_CLAUSES (t) = tmp;
19674 add_stmt (t);
19675 break;
19677 case OMP_ORDERED:
19678 tmp = tsubst_omp_clauses (OMP_ORDERED_CLAUSES (t), C_ORT_OMP, args,
19679 complain, in_decl);
19680 if (OMP_BODY (t))
19682 stmt = push_stmt_list ();
19683 RECUR (OMP_BODY (t));
19684 stmt = pop_stmt_list (stmt);
19686 else
19687 stmt = NULL_TREE;
19689 t = copy_node (t);
19690 OMP_BODY (t) = stmt;
19691 OMP_ORDERED_CLAUSES (t) = tmp;
19692 add_stmt (t);
19693 break;
19695 case OMP_MASTER:
19696 omp_parallel_combined_clauses = NULL;
19697 /* FALLTHRU */
19698 case OMP_SECTION:
19699 stmt = push_stmt_list ();
19700 RECUR (OMP_BODY (t));
19701 stmt = pop_stmt_list (stmt);
19703 t = copy_node (t);
19704 OMP_BODY (t) = stmt;
19705 add_stmt (t);
19706 break;
19708 case OMP_ATOMIC:
19709 gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
19710 tmp = NULL_TREE;
19711 if (TREE_CODE (TREE_OPERAND (t, 0)) == OMP_CLAUSE)
19712 tmp = tsubst_omp_clauses (TREE_OPERAND (t, 0), C_ORT_OMP, args,
19713 complain, in_decl);
19714 if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
19716 tree op1 = TREE_OPERAND (t, 1);
19717 tree rhs1 = NULL_TREE;
19718 tree r = NULL_TREE;
19719 tree lhs, rhs;
19720 if (TREE_CODE (op1) == COMPOUND_EXPR)
19722 rhs1 = RECUR (TREE_OPERAND (op1, 0));
19723 op1 = TREE_OPERAND (op1, 1);
19725 if (TREE_CODE (op1) == COND_EXPR)
19727 gcc_assert (rhs1 == NULL_TREE);
19728 tree c = TREE_OPERAND (op1, 0);
19729 if (TREE_CODE (c) == MODIFY_EXPR)
19731 r = RECUR (TREE_OPERAND (c, 0));
19732 c = TREE_OPERAND (c, 1);
19734 gcc_assert (TREE_CODE (c) == EQ_EXPR);
19735 rhs = RECUR (TREE_OPERAND (c, 1));
19736 lhs = RECUR (TREE_OPERAND (op1, 2));
19737 rhs1 = RECUR (TREE_OPERAND (op1, 1));
19739 else
19741 lhs = RECUR (TREE_OPERAND (op1, 0));
19742 rhs = RECUR (TREE_OPERAND (op1, 1));
19744 finish_omp_atomic (EXPR_LOCATION (t), OMP_ATOMIC, TREE_CODE (op1),
19745 lhs, rhs, NULL_TREE, NULL_TREE, rhs1, r,
19746 tmp, OMP_ATOMIC_MEMORY_ORDER (t),
19747 OMP_ATOMIC_WEAK (t));
19749 else
19751 tree op1 = TREE_OPERAND (t, 1);
19752 tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
19753 tree rhs1 = NULL_TREE, r = NULL_TREE;
19754 enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
19755 enum tree_code opcode = NOP_EXPR;
19756 if (code == OMP_ATOMIC_READ)
19758 v = RECUR (TREE_OPERAND (op1, 0));
19759 lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
19761 else if (code == OMP_ATOMIC_CAPTURE_OLD
19762 || code == OMP_ATOMIC_CAPTURE_NEW)
19764 tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
19765 v = RECUR (TREE_OPERAND (op1, 0));
19766 lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
19767 if (TREE_CODE (op11) == COMPOUND_EXPR)
19769 rhs1 = RECUR (TREE_OPERAND (op11, 0));
19770 op11 = TREE_OPERAND (op11, 1);
19772 if (TREE_CODE (op11) == COND_EXPR)
19774 gcc_assert (rhs1 == NULL_TREE);
19775 tree c = TREE_OPERAND (op11, 0);
19776 if (TREE_CODE (c) == MODIFY_EXPR)
19778 r = RECUR (TREE_OPERAND (c, 0));
19779 c = TREE_OPERAND (c, 1);
19781 gcc_assert (TREE_CODE (c) == EQ_EXPR);
19782 rhs = RECUR (TREE_OPERAND (c, 1));
19783 lhs = RECUR (TREE_OPERAND (op11, 2));
19784 rhs1 = RECUR (TREE_OPERAND (op11, 1));
19786 else
19788 lhs = RECUR (TREE_OPERAND (op11, 0));
19789 rhs = RECUR (TREE_OPERAND (op11, 1));
19791 opcode = TREE_CODE (op11);
19792 if (opcode == MODIFY_EXPR)
19793 opcode = NOP_EXPR;
19795 else
19797 code = OMP_ATOMIC;
19798 lhs = RECUR (TREE_OPERAND (op1, 0));
19799 rhs = RECUR (TREE_OPERAND (op1, 1));
19801 finish_omp_atomic (EXPR_LOCATION (t), code, opcode, lhs, rhs, v,
19802 lhs1, rhs1, r, tmp,
19803 OMP_ATOMIC_MEMORY_ORDER (t), OMP_ATOMIC_WEAK (t));
19805 break;
19807 case TRANSACTION_EXPR:
19809 int flags = 0;
19810 flags |= (TRANSACTION_EXPR_OUTER (t) ? TM_STMT_ATTR_OUTER : 0);
19811 flags |= (TRANSACTION_EXPR_RELAXED (t) ? TM_STMT_ATTR_RELAXED : 0);
19813 if (TRANSACTION_EXPR_IS_STMT (t))
19815 tree body = TRANSACTION_EXPR_BODY (t);
19816 tree noex = NULL_TREE;
19817 if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
19819 noex = MUST_NOT_THROW_COND (body);
19820 if (noex == NULL_TREE)
19821 noex = boolean_true_node;
19822 body = TREE_OPERAND (body, 0);
19824 stmt = begin_transaction_stmt (input_location, NULL, flags);
19825 RECUR (body);
19826 finish_transaction_stmt (stmt, NULL, flags, RECUR (noex));
19828 else
19830 stmt = build_transaction_expr (EXPR_LOCATION (t),
19831 RECUR (TRANSACTION_EXPR_BODY (t)),
19832 flags, NULL_TREE);
19833 RETURN (stmt);
19836 break;
19838 case MUST_NOT_THROW_EXPR:
19840 tree op0 = RECUR (TREE_OPERAND (t, 0));
19841 tree cond = RECUR (MUST_NOT_THROW_COND (t));
19842 RETURN (build_must_not_throw_expr (op0, cond));
19845 case EXPR_PACK_EXPANSION:
19846 error ("invalid use of pack expansion expression");
19847 RETURN (error_mark_node);
19849 case NONTYPE_ARGUMENT_PACK:
19850 error ("use %<...%> to expand argument pack");
19851 RETURN (error_mark_node);
19853 case COMPOUND_EXPR:
19854 tmp = RECUR (TREE_OPERAND (t, 0));
19855 if (tmp == NULL_TREE)
19856 /* If the first operand was a statement, we're done with it. */
19857 RETURN (RECUR (TREE_OPERAND (t, 1)));
19858 RETURN (build_x_compound_expr (EXPR_LOCATION (t), tmp,
19859 RECUR (TREE_OPERAND (t, 1)),
19860 templated_operator_saved_lookups (t),
19861 complain));
19863 case ANNOTATE_EXPR:
19864 tmp = RECUR (TREE_OPERAND (t, 0));
19865 RETURN (build3_loc (EXPR_LOCATION (t), ANNOTATE_EXPR,
19866 TREE_TYPE (tmp), tmp,
19867 RECUR (TREE_OPERAND (t, 1)),
19868 RECUR (TREE_OPERAND (t, 2))));
19870 case PREDICT_EXPR:
19871 RETURN (add_stmt (copy_node (t)));
19873 default:
19874 gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
19876 RETURN (tsubst_copy_and_build (t, args, complain, in_decl));
19879 RETURN (NULL_TREE);
19880 out:
19881 input_location = loc;
19882 return r;
19883 #undef RECUR
19884 #undef RETURN
19887 /* Instantiate the special body of the artificial DECL_OMP_DECLARE_REDUCTION
19888 function. For description of the body see comment above
19889 cp_parser_omp_declare_reduction_exprs. */
19891 static void
19892 tsubst_omp_udr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
19894 if (t == NULL_TREE || t == error_mark_node)
19895 return;
19897 gcc_assert (TREE_CODE (t) == STATEMENT_LIST && current_function_decl);
19899 tree_stmt_iterator tsi;
19900 int i;
19901 tree stmts[7];
19902 memset (stmts, 0, sizeof stmts);
19903 for (i = 0, tsi = tsi_start (t);
19904 i < 7 && !tsi_end_p (tsi);
19905 i++, tsi_next (&tsi))
19906 stmts[i] = tsi_stmt (tsi);
19907 gcc_assert (tsi_end_p (tsi));
19909 if (i >= 3)
19911 gcc_assert (TREE_CODE (stmts[0]) == DECL_EXPR
19912 && TREE_CODE (stmts[1]) == DECL_EXPR);
19913 tree omp_out = tsubst (DECL_EXPR_DECL (stmts[0]),
19914 args, complain, in_decl);
19915 tree omp_in = tsubst (DECL_EXPR_DECL (stmts[1]),
19916 args, complain, in_decl);
19917 /* tsubsting a local var_decl leaves DECL_CONTEXT null, as we
19918 expect to be pushing it. */
19919 DECL_CONTEXT (omp_out) = current_function_decl;
19920 DECL_CONTEXT (omp_in) = current_function_decl;
19921 keep_next_level (true);
19922 tree block = begin_omp_structured_block ();
19923 tsubst_expr (stmts[2], args, complain, in_decl);
19924 block = finish_omp_structured_block (block);
19925 block = maybe_cleanup_point_expr_void (block);
19926 add_decl_expr (omp_out);
19927 copy_warning (omp_out, DECL_EXPR_DECL (stmts[0]));
19928 add_decl_expr (omp_in);
19929 finish_expr_stmt (block);
19931 if (i >= 6)
19933 gcc_assert (TREE_CODE (stmts[3]) == DECL_EXPR
19934 && TREE_CODE (stmts[4]) == DECL_EXPR);
19935 tree omp_priv = tsubst (DECL_EXPR_DECL (stmts[3]),
19936 args, complain, in_decl);
19937 tree omp_orig = tsubst (DECL_EXPR_DECL (stmts[4]),
19938 args, complain, in_decl);
19939 DECL_CONTEXT (omp_priv) = current_function_decl;
19940 DECL_CONTEXT (omp_orig) = current_function_decl;
19941 keep_next_level (true);
19942 tree block = begin_omp_structured_block ();
19943 tsubst_expr (stmts[5], args, complain, in_decl);
19944 block = finish_omp_structured_block (block);
19945 block = maybe_cleanup_point_expr_void (block);
19946 cp_walk_tree (&block, cp_remove_omp_priv_cleanup_stmt, omp_priv, NULL);
19947 add_decl_expr (omp_priv);
19948 add_decl_expr (omp_orig);
19949 finish_expr_stmt (block);
19950 if (i == 7)
19951 add_decl_expr (omp_orig);
19955 /* T is a postfix-expression that is not being used in a function
19956 call. Return the substituted version of T. */
19958 static tree
19959 tsubst_non_call_postfix_expression (tree t, tree args,
19960 tsubst_flags_t complain,
19961 tree in_decl)
19963 if (TREE_CODE (t) == SCOPE_REF)
19964 t = tsubst_qualified_id (t, args, complain, in_decl,
19965 /*done=*/false, /*address_p=*/false);
19966 else
19967 t = tsubst_copy_and_build (t, args, complain, in_decl);
19969 return t;
19972 /* Subroutine of tsubst_lambda_expr: add the FIELD/INIT capture pair to the
19973 LAMBDA_EXPR_CAPTURE_LIST passed in LIST. Do deduction for a previously
19974 dependent init-capture. EXPLICIT_P is true if the original list had
19975 explicit captures. */
19977 static void
19978 prepend_one_capture (tree field, tree init, tree &list, bool explicit_p,
19979 tsubst_flags_t complain)
19981 if (tree auto_node = type_uses_auto (TREE_TYPE (field)))
19983 tree type = NULL_TREE;
19984 if (!init)
19986 if (complain & tf_error)
19987 error ("empty initializer in lambda init-capture");
19988 init = error_mark_node;
19990 else if (TREE_CODE (init) == TREE_LIST)
19991 init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
19992 if (!type)
19993 type = do_auto_deduction (TREE_TYPE (field), init, auto_node, complain);
19994 TREE_TYPE (field) = type;
19995 cp_apply_type_quals_to_decl (cp_type_quals (type), field);
19997 list = tree_cons (field, init, list);
19998 LAMBDA_CAPTURE_EXPLICIT_P (list) = explicit_p;
20001 /* T is a LAMBDA_EXPR. Generate a new LAMBDA_EXPR for the current
20002 instantiation context. Instantiating a pack expansion containing a lambda
20003 might result in multiple lambdas all based on the same lambda in the
20004 template. */
20006 tree
20007 tsubst_lambda_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
20009 tree oldfn = lambda_function (t);
20010 in_decl = oldfn;
20012 tree r = build_lambda_expr ();
20014 LAMBDA_EXPR_LOCATION (r)
20015 = LAMBDA_EXPR_LOCATION (t);
20016 LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
20017 = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
20018 LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
20019 if (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
20020 LAMBDA_EXPR_REGEN_INFO (r)
20021 = build_template_info (t, add_to_template_args (TI_ARGS (ti),
20022 preserve_args (args)));
20023 else
20024 LAMBDA_EXPR_REGEN_INFO (r)
20025 = build_template_info (t, preserve_args (args));
20027 gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
20028 && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
20030 vec<tree,va_gc>* field_packs = NULL;
20032 for (tree cap = LAMBDA_EXPR_CAPTURE_LIST (t); cap;
20033 cap = TREE_CHAIN (cap))
20035 tree ofield = TREE_PURPOSE (cap);
20036 tree init = TREE_VALUE (cap);
20037 if (PACK_EXPANSION_P (init))
20038 init = tsubst_pack_expansion (init, args, complain, in_decl);
20039 else
20040 init = tsubst_copy_and_build (init, args, complain, in_decl);
20042 if (init == error_mark_node)
20043 return error_mark_node;
20045 if (init && TREE_CODE (init) == TREE_LIST)
20046 init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
20048 if (!processing_template_decl
20049 && init && TREE_CODE (init) != TREE_VEC
20050 && variably_modified_type_p (TREE_TYPE (init), NULL_TREE))
20052 /* For a VLA, simply tsubsting the field type won't work, we need to
20053 go through add_capture again. XXX do we want to do this for all
20054 captures? */
20055 tree name = (get_identifier
20056 (IDENTIFIER_POINTER (DECL_NAME (ofield)) + 2));
20057 tree ftype = TREE_TYPE (ofield);
20058 bool by_ref = (TYPE_REF_P (ftype)
20059 || (TREE_CODE (ftype) == DECLTYPE_TYPE
20060 && DECLTYPE_FOR_REF_CAPTURE (ftype)));
20061 add_capture (r, name, init, by_ref, !DECL_NORMAL_CAPTURE_P (ofield));
20062 continue;
20065 if (PACK_EXPANSION_P (ofield))
20066 ofield = PACK_EXPANSION_PATTERN (ofield);
20067 tree field = tsubst_decl (ofield, args, complain);
20069 if (DECL_PACK_P (ofield) && !DECL_NORMAL_CAPTURE_P (ofield))
20071 /* Remember these for when we've pushed local_specializations. */
20072 vec_safe_push (field_packs, ofield);
20073 vec_safe_push (field_packs, field);
20076 if (field == error_mark_node)
20077 return error_mark_node;
20079 if (TREE_CODE (field) == TREE_VEC)
20081 int len = TREE_VEC_LENGTH (field);
20082 gcc_assert (TREE_CODE (init) == TREE_VEC
20083 && TREE_VEC_LENGTH (init) == len);
20084 for (int i = 0; i < len; ++i)
20085 prepend_one_capture (TREE_VEC_ELT (field, i),
20086 TREE_VEC_ELT (init, i),
20087 LAMBDA_EXPR_CAPTURE_LIST (r),
20088 LAMBDA_CAPTURE_EXPLICIT_P (cap),
20089 complain);
20091 else
20093 prepend_one_capture (field, init, LAMBDA_EXPR_CAPTURE_LIST (r),
20094 LAMBDA_CAPTURE_EXPLICIT_P (cap), complain);
20096 if (id_equal (DECL_NAME (field), "__this"))
20097 LAMBDA_EXPR_THIS_CAPTURE (r) = field;
20101 tree type = begin_lambda_type (r);
20102 if (type == error_mark_node)
20103 return error_mark_node;
20105 if (LAMBDA_EXPR_EXTRA_SCOPE (t))
20106 record_lambda_scope (r);
20107 else if (TYPE_NAMESPACE_SCOPE_P (TREE_TYPE (t)))
20108 /* If we're pushed into another scope (PR105652), fix it. */
20109 TYPE_CONTEXT (type) = DECL_CONTEXT (TYPE_NAME (type))
20110 = TYPE_CONTEXT (TREE_TYPE (t));
20111 record_lambda_scope_discriminator (r);
20113 /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set. */
20114 determine_visibility (TYPE_NAME (type));
20116 register_capture_members (LAMBDA_EXPR_CAPTURE_LIST (r));
20118 tree oldtmpl = (generic_lambda_fn_p (oldfn)
20119 ? DECL_TI_TEMPLATE (oldfn)
20120 : NULL_TREE);
20122 tree tparms = NULL_TREE;
20123 if (oldtmpl)
20124 tparms = tsubst_template_parms (DECL_TEMPLATE_PARMS (oldtmpl), args, complain);
20126 tree fntype = static_fn_type (oldfn);
20128 tree saved_ctp = current_template_parms;
20129 if (oldtmpl)
20131 ++processing_template_decl;
20132 current_template_parms = tparms;
20134 fntype = tsubst (fntype, args, complain, in_decl);
20135 if (oldtmpl)
20137 current_template_parms = saved_ctp;
20138 --processing_template_decl;
20141 if (fntype == error_mark_node)
20142 r = error_mark_node;
20143 else
20145 /* The body of a lambda-expression is not a subexpression of the
20146 enclosing expression. Parms are to have DECL_CHAIN tsubsted,
20147 which would be skipped if cp_unevaluated_operand. */
20148 cp_evaluated ev;
20150 /* Fix the type of 'this'. */
20151 fntype = build_memfn_type (fntype, type,
20152 type_memfn_quals (fntype),
20153 type_memfn_rqual (fntype));
20154 tree inst = (oldtmpl
20155 ? tsubst_template_decl (oldtmpl, args, complain,
20156 fntype, tparms)
20157 : tsubst_function_decl (oldfn, args, complain, fntype));
20158 if (inst == error_mark_node)
20160 r = error_mark_node;
20161 goto out;
20163 finish_member_declaration (inst);
20164 record_lambda_scope_sig_discriminator (r, inst);
20166 tree fn = oldtmpl ? DECL_TEMPLATE_RESULT (inst) : inst;
20168 /* Let finish_function set this. */
20169 DECL_DECLARED_CONSTEXPR_P (fn) = false;
20171 bool nested = cfun;
20172 if (nested)
20173 push_function_context ();
20174 else
20175 /* Still increment function_depth so that we don't GC in the
20176 middle of an expression. */
20177 ++function_depth;
20179 local_specialization_stack s (lss_copy);
20181 bool save_in_consteval_if_p = in_consteval_if_p;
20182 in_consteval_if_p = false;
20184 tree body = start_lambda_function (fn, r);
20186 /* Now record them for lookup_init_capture_pack. */
20187 int fplen = vec_safe_length (field_packs);
20188 for (int i = 0; i < fplen; )
20190 tree pack = (*field_packs)[i++];
20191 tree inst = (*field_packs)[i++];
20192 register_local_specialization (inst, pack);
20194 release_tree_vector (field_packs);
20196 register_parameter_specializations (oldfn, fn);
20198 if (oldtmpl)
20200 /* We might not partially instantiate some parts of the function, so
20201 copy these flags from the original template. */
20202 language_function *ol = DECL_STRUCT_FUNCTION (oldfn)->language;
20203 current_function_returns_value = ol->returns_value;
20204 current_function_returns_null = ol->returns_null;
20205 current_function_returns_abnormally = ol->returns_abnormally;
20206 current_function_infinite_loop = ol->infinite_loop;
20209 /* [temp.deduct] A lambda-expression appearing in a function type or a
20210 template parameter is not considered part of the immediate context for
20211 the purposes of template argument deduction. */
20212 complain = tf_warning_or_error;
20214 tree saved = DECL_SAVED_TREE (oldfn);
20215 if (TREE_CODE (saved) == BIND_EXPR && BIND_EXPR_BODY_BLOCK (saved))
20216 /* We already have a body block from start_lambda_function, we don't
20217 need another to confuse NRV (91217). */
20218 saved = BIND_EXPR_BODY (saved);
20220 tsubst_expr (saved, args, complain, r);
20222 finish_lambda_function (body);
20224 in_consteval_if_p = save_in_consteval_if_p;
20226 if (nested)
20227 pop_function_context ();
20228 else
20229 --function_depth;
20231 /* The capture list was built up in reverse order; fix that now. */
20232 LAMBDA_EXPR_CAPTURE_LIST (r)
20233 = nreverse (LAMBDA_EXPR_CAPTURE_LIST (r));
20235 LAMBDA_EXPR_THIS_CAPTURE (r) = NULL_TREE;
20237 maybe_add_lambda_conv_op (type);
20240 out:
20241 finish_struct (type, /*attr*/NULL_TREE);
20243 insert_pending_capture_proxies ();
20245 return r;
20248 /* Subroutine of maybe_fold_fn_template_args. */
20250 static bool
20251 fold_targs_r (tree targs, tsubst_flags_t complain)
20253 int len = TREE_VEC_LENGTH (targs);
20254 for (int i = 0; i < len; ++i)
20256 tree &elt = TREE_VEC_ELT (targs, i);
20257 if (!elt || TYPE_P (elt)
20258 || TREE_CODE (elt) == TEMPLATE_DECL)
20259 continue;
20260 if (TREE_CODE (elt) == NONTYPE_ARGUMENT_PACK)
20262 if (!fold_targs_r (ARGUMENT_PACK_ARGS (elt), complain))
20263 return false;
20265 else if (/* We can only safely preevaluate scalar prvalues. */
20266 SCALAR_TYPE_P (TREE_TYPE (elt))
20267 && !glvalue_p (elt)
20268 && !TREE_CONSTANT (elt))
20270 elt = cxx_constant_value (elt, complain);
20271 if (elt == error_mark_node)
20272 return false;
20276 return true;
20279 /* Try to do constant evaluation of any explicit template arguments in FN
20280 before overload resolution, to get any errors only once. Return true iff
20281 we didn't have any problems folding. */
20283 static bool
20284 maybe_fold_fn_template_args (tree fn, tsubst_flags_t complain)
20286 if (processing_template_decl || fn == NULL_TREE)
20287 return true;
20288 if (fn == error_mark_node)
20289 return false;
20290 if (TREE_CODE (fn) == OFFSET_REF
20291 || TREE_CODE (fn) == COMPONENT_REF)
20292 fn = TREE_OPERAND (fn, 1);
20293 if (BASELINK_P (fn))
20294 fn = BASELINK_FUNCTIONS (fn);
20295 if (TREE_CODE (fn) != TEMPLATE_ID_EXPR)
20296 return true;
20297 tree targs = TREE_OPERAND (fn, 1);
20298 if (targs == NULL_TREE)
20299 return true;
20300 if (targs == error_mark_node)
20301 return false;
20302 return fold_targs_r (targs, complain);
20305 /* Helper function for tsubst_copy_and_build CALL_EXPR and ARRAY_REF
20306 handling. */
20308 static void
20309 tsubst_copy_and_build_call_args (tree t, tree args, tsubst_flags_t complain,
20310 tree in_decl, releasing_vec &call_args)
20312 unsigned int nargs = call_expr_nargs (t);
20313 for (unsigned int i = 0; i < nargs; ++i)
20315 tree arg = CALL_EXPR_ARG (t, i);
20317 if (!PACK_EXPANSION_P (arg))
20318 vec_safe_push (call_args,
20319 tsubst_copy_and_build (arg, args, complain, in_decl));
20320 else
20322 /* Expand the pack expansion and push each entry onto CALL_ARGS. */
20323 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
20324 if (TREE_CODE (arg) == TREE_VEC)
20326 unsigned int len, j;
20328 len = TREE_VEC_LENGTH (arg);
20329 for (j = 0; j < len; ++j)
20331 tree value = TREE_VEC_ELT (arg, j);
20332 if (value != NULL_TREE)
20333 value = convert_from_reference (value);
20334 vec_safe_push (call_args, value);
20337 else
20338 /* A partial substitution. Add one entry. */
20339 vec_safe_push (call_args, arg);
20344 /* Like tsubst but deals with expressions and performs semantic
20345 analysis. */
20347 tree
20348 tsubst_copy_and_build (tree t,
20349 tree args,
20350 tsubst_flags_t complain,
20351 tree in_decl)
20353 #define RETURN(EXP) do { retval = (EXP); goto out; } while(0)
20354 #define RECUR(NODE) \
20355 tsubst_copy_and_build (NODE, args, complain, in_decl)
20357 tree retval, op1;
20358 location_t save_loc;
20360 if (t == NULL_TREE || t == error_mark_node)
20361 return t;
20363 save_loc = input_location;
20364 if (location_t eloc = cp_expr_location (t))
20365 input_location = eloc;
20367 /* N3276 decltype magic only applies to calls at the top level or on the
20368 right side of a comma. */
20369 tsubst_flags_t decltype_flag = (complain & tf_decltype);
20370 complain &= ~tf_decltype;
20372 switch (TREE_CODE (t))
20374 case USING_DECL:
20375 t = DECL_NAME (t);
20376 /* Fall through. */
20377 case IDENTIFIER_NODE:
20379 tree decl;
20380 cp_id_kind idk;
20381 const char *error_msg;
20383 if (IDENTIFIER_CONV_OP_P (t))
20385 tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20386 t = make_conv_op_name (new_type);
20389 /* Look up the name. */
20390 decl = lookup_name (t);
20392 /* By convention, expressions use ERROR_MARK_NODE to indicate
20393 failure, not NULL_TREE. */
20394 if (decl == NULL_TREE)
20395 decl = error_mark_node;
20397 decl = finish_id_expression (t, decl, NULL_TREE,
20398 &idk,
20399 /*i_c_e_p=*/false,
20400 /*allow_i_c_e_p=*/true,
20401 /*non_i_c_e_p=*/nullptr,
20402 /*template_p=*/false,
20403 /*done=*/true,
20404 /*address_p=*/false,
20405 /*template_arg_p=*/false,
20406 &error_msg,
20407 input_location);
20408 if (error_msg)
20409 error (error_msg);
20410 if (identifier_p (decl))
20412 if (complain & tf_error)
20413 unqualified_name_lookup_error (decl);
20414 decl = error_mark_node;
20416 RETURN (decl);
20419 case TEMPLATE_ID_EXPR:
20421 tree object;
20422 tree templ = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
20423 complain, in_decl);
20424 tree targs = TREE_OPERAND (t, 1);
20426 if (targs)
20427 targs = tsubst_template_args (targs, args, complain, in_decl);
20428 if (targs == error_mark_node)
20429 RETURN (error_mark_node);
20431 if (TREE_CODE (templ) == SCOPE_REF)
20433 tree name = TREE_OPERAND (templ, 1);
20434 tree tid = lookup_template_function (name, targs);
20435 TREE_OPERAND (templ, 1) = tid;
20436 RETURN (templ);
20439 if (concept_definition_p (templ))
20441 tree check = build_concept_check (templ, targs, complain);
20442 if (check == error_mark_node)
20443 RETURN (error_mark_node);
20445 tree id = unpack_concept_check (check);
20447 /* If we built a function concept check, return the underlying
20448 template-id. So we can evaluate it as a function call. */
20449 if (function_concept_p (TREE_OPERAND (id, 0)))
20450 RETURN (id);
20452 RETURN (check);
20455 if (variable_template_p (templ))
20457 tree r = lookup_and_finish_template_variable (templ, targs,
20458 complain);
20459 r = convert_from_reference (r);
20460 r = maybe_wrap_with_location (r, EXPR_LOCATION (t));
20461 RETURN (r);
20464 if (TREE_CODE (templ) == COMPONENT_REF)
20466 object = TREE_OPERAND (templ, 0);
20467 templ = TREE_OPERAND (templ, 1);
20469 else
20470 object = NULL_TREE;
20472 tree tid = lookup_template_function (templ, targs);
20473 protected_set_expr_location (tid, EXPR_LOCATION (t));
20475 if (object)
20476 RETURN (build3 (COMPONENT_REF, TREE_TYPE (tid),
20477 object, tid, NULL_TREE));
20478 else if (identifier_p (templ))
20480 /* C++20 P0846: we can encounter an IDENTIFIER_NODE here when
20481 name lookup found nothing when parsing the template name. */
20482 gcc_assert (cxx_dialect >= cxx20 || seen_error ());
20483 RETURN (tid);
20485 else
20486 RETURN (baselink_for_fns (tid));
20489 case INDIRECT_REF:
20491 tree r = RECUR (TREE_OPERAND (t, 0));
20493 if (REFERENCE_REF_P (t))
20495 /* A type conversion to reference type will be enclosed in
20496 such an indirect ref, but the substitution of the cast
20497 will have also added such an indirect ref. */
20498 r = convert_from_reference (r);
20500 else
20501 r = build_x_indirect_ref (input_location, r, RO_UNARY_STAR,
20502 templated_operator_saved_lookups (t),
20503 complain|decltype_flag);
20505 if (REF_PARENTHESIZED_P (t))
20506 r = force_paren_expr (r);
20508 RETURN (r);
20511 case NOP_EXPR:
20513 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20514 tree op0 = RECUR (TREE_OPERAND (t, 0));
20515 RETURN (build_nop (type, op0));
20518 case IMPLICIT_CONV_EXPR:
20520 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20521 tree expr = RECUR (TREE_OPERAND (t, 0));
20522 if (dependent_type_p (type) || type_dependent_expression_p (expr))
20524 retval = copy_node (t);
20525 TREE_TYPE (retval) = type;
20526 TREE_OPERAND (retval, 0) = expr;
20527 RETURN (retval);
20529 if (IMPLICIT_CONV_EXPR_NONTYPE_ARG (t))
20530 /* We'll pass this to convert_nontype_argument again, we don't need
20531 to actually perform any conversion here. */
20532 RETURN (expr);
20533 int flags = LOOKUP_IMPLICIT;
20534 if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
20535 flags = LOOKUP_NORMAL;
20536 if (IMPLICIT_CONV_EXPR_BRACED_INIT (t))
20537 flags |= LOOKUP_NO_NARROWING;
20538 RETURN (perform_implicit_conversion_flags (type, expr, complain,
20539 flags));
20542 case CONVERT_EXPR:
20544 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20545 tree op0 = RECUR (TREE_OPERAND (t, 0));
20546 if (op0 == error_mark_node)
20547 RETURN (error_mark_node);
20548 RETURN (build1 (CONVERT_EXPR, type, op0));
20551 case CAST_EXPR:
20552 case REINTERPRET_CAST_EXPR:
20553 case CONST_CAST_EXPR:
20554 case DYNAMIC_CAST_EXPR:
20555 case STATIC_CAST_EXPR:
20557 tree type;
20558 tree op, r = NULL_TREE;
20560 tsubst_flags_t tcomplain = complain;
20561 if (TREE_CODE (t) == CAST_EXPR)
20562 tcomplain |= tf_tst_ok;
20563 type = tsubst (TREE_TYPE (t), args, tcomplain, in_decl);
20565 op = RECUR (TREE_OPERAND (t, 0));
20567 warning_sentinel s(warn_useless_cast);
20568 warning_sentinel s2(warn_ignored_qualifiers);
20569 warning_sentinel s3(warn_int_in_bool_context);
20570 switch (TREE_CODE (t))
20572 case CAST_EXPR:
20573 r = build_functional_cast (input_location, type, op, complain);
20574 break;
20575 case REINTERPRET_CAST_EXPR:
20576 r = build_reinterpret_cast (input_location, type, op, complain);
20577 break;
20578 case CONST_CAST_EXPR:
20579 r = build_const_cast (input_location, type, op, complain);
20580 break;
20581 case DYNAMIC_CAST_EXPR:
20582 r = build_dynamic_cast (input_location, type, op, complain);
20583 break;
20584 case STATIC_CAST_EXPR:
20585 r = build_static_cast (input_location, type, op, complain);
20586 if (IMPLICIT_RVALUE_P (t))
20587 set_implicit_rvalue_p (r);
20588 break;
20589 default:
20590 gcc_unreachable ();
20593 RETURN (r);
20596 case BIT_CAST_EXPR:
20598 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20599 tree op0 = RECUR (TREE_OPERAND (t, 0));
20600 RETURN (cp_build_bit_cast (EXPR_LOCATION (t), type, op0, complain));
20603 case POSTDECREMENT_EXPR:
20604 case POSTINCREMENT_EXPR:
20605 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20606 args, complain, in_decl);
20607 RETURN (build_x_unary_op (input_location, TREE_CODE (t), op1,
20608 templated_operator_saved_lookups (t),
20609 complain|decltype_flag));
20611 case PREDECREMENT_EXPR:
20612 case PREINCREMENT_EXPR:
20613 case NEGATE_EXPR:
20614 case BIT_NOT_EXPR:
20615 case ABS_EXPR:
20616 case TRUTH_NOT_EXPR:
20617 case UNARY_PLUS_EXPR: /* Unary + */
20618 case REALPART_EXPR:
20619 case IMAGPART_EXPR:
20620 RETURN (build_x_unary_op (input_location, TREE_CODE (t),
20621 RECUR (TREE_OPERAND (t, 0)),
20622 templated_operator_saved_lookups (t),
20623 complain|decltype_flag));
20625 case EXCESS_PRECISION_EXPR:
20627 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20628 tree op0 = RECUR (TREE_OPERAND (t, 0));
20629 if (TREE_CODE (op0) == EXCESS_PRECISION_EXPR)
20630 RETURN (op0);
20631 RETURN (build1_loc (EXPR_LOCATION (t), EXCESS_PRECISION_EXPR,
20632 type, op0));
20635 case FIX_TRUNC_EXPR:
20636 /* convert_like should have created an IMPLICIT_CONV_EXPR. */
20637 gcc_unreachable ();
20639 case ADDR_EXPR:
20640 op1 = TREE_OPERAND (t, 0);
20641 if (TREE_CODE (op1) == LABEL_DECL)
20642 RETURN (finish_label_address_expr (DECL_NAME (op1),
20643 EXPR_LOCATION (op1)));
20644 if (TREE_CODE (op1) == SCOPE_REF)
20645 op1 = tsubst_qualified_id (op1, args, complain, in_decl,
20646 /*done=*/true, /*address_p=*/true);
20647 else
20648 op1 = tsubst_non_call_postfix_expression (op1, args, complain,
20649 in_decl);
20650 RETURN (build_x_unary_op (input_location, ADDR_EXPR, op1,
20651 templated_operator_saved_lookups (t),
20652 complain|decltype_flag));
20654 case PLUS_EXPR:
20655 case MINUS_EXPR:
20656 case MULT_EXPR:
20657 case TRUNC_DIV_EXPR:
20658 case CEIL_DIV_EXPR:
20659 case FLOOR_DIV_EXPR:
20660 case ROUND_DIV_EXPR:
20661 case EXACT_DIV_EXPR:
20662 case BIT_AND_EXPR:
20663 case BIT_IOR_EXPR:
20664 case BIT_XOR_EXPR:
20665 case TRUNC_MOD_EXPR:
20666 case FLOOR_MOD_EXPR:
20667 case TRUTH_ANDIF_EXPR:
20668 case TRUTH_ORIF_EXPR:
20669 case TRUTH_AND_EXPR:
20670 case TRUTH_OR_EXPR:
20671 case RSHIFT_EXPR:
20672 case LSHIFT_EXPR:
20673 case EQ_EXPR:
20674 case NE_EXPR:
20675 case MAX_EXPR:
20676 case MIN_EXPR:
20677 case LE_EXPR:
20678 case GE_EXPR:
20679 case LT_EXPR:
20680 case GT_EXPR:
20681 case SPACESHIP_EXPR:
20682 case MEMBER_REF:
20683 case DOTSTAR_EXPR:
20685 /* If either OP0 or OP1 was value- or type-dependent, suppress
20686 warnings that depend on the range of the types involved. */
20687 tree op0 = TREE_OPERAND (t, 0);
20688 tree op1 = TREE_OPERAND (t, 1);
20689 const bool was_dep = (dependent_operand_p (op0)
20690 || dependent_operand_p (op1));
20691 op0 = RECUR (op0);
20692 op1 = RECUR (op1);
20694 warning_sentinel s1(warn_type_limits, was_dep);
20695 warning_sentinel s2(warn_div_by_zero, was_dep);
20696 warning_sentinel s3(warn_logical_op, was_dep);
20697 warning_sentinel s4(warn_tautological_compare, was_dep);
20698 warning_sentinel s5(warn_address, was_dep);
20700 tree r = build_x_binary_op
20701 (input_location, TREE_CODE (t),
20702 op0,
20703 (warning_suppressed_p (TREE_OPERAND (t, 0))
20704 ? ERROR_MARK
20705 : TREE_CODE (TREE_OPERAND (t, 0))),
20706 op1,
20707 (warning_suppressed_p (TREE_OPERAND (t, 1))
20708 ? ERROR_MARK
20709 : TREE_CODE (TREE_OPERAND (t, 1))),
20710 templated_operator_saved_lookups (t),
20711 /*overload=*/NULL,
20712 complain|decltype_flag);
20713 if (EXPR_P (r))
20714 copy_warning (r, t);
20716 RETURN (r);
20719 case POINTER_PLUS_EXPR:
20721 tree op0 = RECUR (TREE_OPERAND (t, 0));
20722 if (op0 == error_mark_node)
20723 RETURN (error_mark_node);
20724 tree op1 = RECUR (TREE_OPERAND (t, 1));
20725 if (op1 == error_mark_node)
20726 RETURN (error_mark_node);
20727 RETURN (fold_build_pointer_plus (op0, op1));
20730 case SCOPE_REF:
20731 RETURN (tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
20732 /*address_p=*/false));
20734 case BASELINK:
20735 RETURN (tsubst_baselink (t, current_nonlambda_class_type (),
20736 args, complain, in_decl));
20738 case ARRAY_REF:
20739 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20740 args, complain, in_decl);
20741 if (TREE_CODE (TREE_OPERAND (t, 1)) == CALL_EXPR
20742 && (CALL_EXPR_FN (TREE_OPERAND (t, 1))
20743 == ovl_op_identifier (ARRAY_REF)))
20745 tree c = TREE_OPERAND (t, 1);
20746 releasing_vec index_exp_list;
20747 tsubst_copy_and_build_call_args (c, args, complain, in_decl,
20748 index_exp_list);
20750 tree r;
20751 if (vec_safe_length (index_exp_list) == 1
20752 && !PACK_EXPANSION_P (index_exp_list[0]))
20753 r = grok_array_decl (EXPR_LOCATION (t), op1,
20754 index_exp_list[0], NULL,
20755 complain | decltype_flag);
20756 else
20757 r = grok_array_decl (EXPR_LOCATION (t), op1,
20758 NULL_TREE, &index_exp_list,
20759 complain | decltype_flag);
20760 RETURN (r);
20762 RETURN (build_x_array_ref (EXPR_LOCATION (t), op1,
20763 RECUR (TREE_OPERAND (t, 1)),
20764 complain|decltype_flag));
20766 case SIZEOF_EXPR:
20767 if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
20768 || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
20769 RETURN (tsubst_copy (t, args, complain, in_decl));
20770 /* Fall through */
20772 case ALIGNOF_EXPR:
20774 tree r;
20776 op1 = TREE_OPERAND (t, 0);
20777 if (TREE_CODE (t) == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (t))
20778 op1 = TREE_TYPE (op1);
20779 bool std_alignof = (TREE_CODE (t) == ALIGNOF_EXPR
20780 && ALIGNOF_EXPR_STD_P (t));
20781 if (!args)
20783 /* When there are no ARGS, we are trying to evaluate a
20784 non-dependent expression from the parser. Trying to do
20785 the substitutions may not work. */
20786 if (!TYPE_P (op1))
20787 op1 = TREE_TYPE (op1);
20789 else
20791 ++cp_unevaluated_operand;
20792 ++c_inhibit_evaluation_warnings;
20793 if (TYPE_P (op1))
20794 op1 = tsubst (op1, args, complain, in_decl);
20795 else
20796 op1 = tsubst_copy_and_build (op1, args, complain, in_decl);
20797 --cp_unevaluated_operand;
20798 --c_inhibit_evaluation_warnings;
20800 if (TYPE_P (op1))
20801 r = cxx_sizeof_or_alignof_type (input_location,
20802 op1, TREE_CODE (t), std_alignof,
20803 complain & tf_error);
20804 else
20805 r = cxx_sizeof_or_alignof_expr (input_location,
20806 op1, TREE_CODE (t), std_alignof,
20807 complain & tf_error);
20808 if (TREE_CODE (t) == SIZEOF_EXPR && r != error_mark_node)
20810 if (TREE_CODE (r) != SIZEOF_EXPR || TYPE_P (op1))
20812 if (!processing_template_decl && TYPE_P (op1))
20814 r = build_min (SIZEOF_EXPR, size_type_node,
20815 build1 (NOP_EXPR, op1, error_mark_node));
20816 SIZEOF_EXPR_TYPE_P (r) = 1;
20818 else
20819 r = build_min (SIZEOF_EXPR, size_type_node, op1);
20820 TREE_SIDE_EFFECTS (r) = 0;
20821 TREE_READONLY (r) = 1;
20823 SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
20825 RETURN (r);
20828 case AT_ENCODE_EXPR:
20830 op1 = TREE_OPERAND (t, 0);
20831 ++cp_unevaluated_operand;
20832 ++c_inhibit_evaluation_warnings;
20833 op1 = tsubst_copy_and_build (op1, args, complain, in_decl);
20834 --cp_unevaluated_operand;
20835 --c_inhibit_evaluation_warnings;
20836 RETURN (objc_build_encode_expr (op1));
20839 case NOEXCEPT_EXPR:
20840 op1 = TREE_OPERAND (t, 0);
20841 ++cp_unevaluated_operand;
20842 ++c_inhibit_evaluation_warnings;
20843 ++cp_noexcept_operand;
20844 op1 = tsubst_copy_and_build (op1, args, complain, in_decl);
20845 --cp_unevaluated_operand;
20846 --c_inhibit_evaluation_warnings;
20847 --cp_noexcept_operand;
20848 RETURN (finish_noexcept_expr (op1, complain));
20850 case MODOP_EXPR:
20852 warning_sentinel s(warn_div_by_zero);
20853 tree lhs = RECUR (TREE_OPERAND (t, 0));
20854 tree rhs = RECUR (TREE_OPERAND (t, 2));
20856 tree r = build_x_modify_expr
20857 (EXPR_LOCATION (t), lhs, TREE_CODE (TREE_OPERAND (t, 1)), rhs,
20858 templated_operator_saved_lookups (t),
20859 complain|decltype_flag);
20860 /* TREE_NO_WARNING must be set if either the expression was
20861 parenthesized or it uses an operator such as >>= rather
20862 than plain assignment. In the former case, it was already
20863 set and must be copied. In the latter case,
20864 build_x_modify_expr sets it and it must not be reset
20865 here. */
20866 if (warning_suppressed_p (t, OPT_Wparentheses))
20867 suppress_warning (r, OPT_Wparentheses);
20869 RETURN (r);
20872 case ARROW_EXPR:
20873 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20874 args, complain, in_decl);
20875 /* Remember that there was a reference to this entity. */
20876 if (DECL_P (op1)
20877 && !mark_used (op1, complain) && !(complain & tf_error))
20878 RETURN (error_mark_node);
20879 RETURN (build_x_arrow (input_location, op1, complain));
20881 case NEW_EXPR:
20883 tree placement = RECUR (TREE_OPERAND (t, 0));
20884 tree init = RECUR (TREE_OPERAND (t, 3));
20885 vec<tree, va_gc> *placement_vec;
20886 vec<tree, va_gc> *init_vec;
20887 tree ret;
20888 location_t loc = EXPR_LOCATION (t);
20890 if (placement == NULL_TREE)
20891 placement_vec = NULL;
20892 else if (placement == error_mark_node)
20893 RETURN (error_mark_node);
20894 else
20896 placement_vec = make_tree_vector ();
20897 for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
20898 vec_safe_push (placement_vec, TREE_VALUE (placement));
20901 /* If there was an initializer in the original tree, but it
20902 instantiated to an empty list, then we should pass a
20903 non-NULL empty vector to tell build_new that it was an
20904 empty initializer() rather than no initializer. This can
20905 only happen when the initializer is a pack expansion whose
20906 parameter packs are of length zero. */
20907 if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
20908 init_vec = NULL;
20909 else if (init == error_mark_node)
20910 RETURN (error_mark_node);
20911 else
20913 init_vec = make_tree_vector ();
20914 if (init == void_node)
20915 gcc_assert (init_vec != NULL);
20916 else
20918 for (; init != NULL_TREE; init = TREE_CHAIN (init))
20919 vec_safe_push (init_vec, TREE_VALUE (init));
20923 /* Avoid passing an enclosing decl to valid_array_size_p. */
20924 in_decl = NULL_TREE;
20926 tree op1 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
20927 tree op2 = RECUR (TREE_OPERAND (t, 2));
20928 ret = build_new (loc, &placement_vec, op1, op2,
20929 &init_vec, NEW_EXPR_USE_GLOBAL (t),
20930 complain);
20932 if (placement_vec != NULL)
20933 release_tree_vector (placement_vec);
20934 if (init_vec != NULL)
20935 release_tree_vector (init_vec);
20937 RETURN (ret);
20940 case DELETE_EXPR:
20942 tree op0 = RECUR (TREE_OPERAND (t, 0));
20943 tree op1 = RECUR (TREE_OPERAND (t, 1));
20944 RETURN (delete_sanity (input_location, op0, op1,
20945 DELETE_EXPR_USE_VEC (t),
20946 DELETE_EXPR_USE_GLOBAL (t),
20947 complain));
20950 case COMPOUND_EXPR:
20952 tree op0 = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
20953 complain & ~tf_decltype, in_decl);
20954 RETURN (build_x_compound_expr (EXPR_LOCATION (t),
20955 op0,
20956 RECUR (TREE_OPERAND (t, 1)),
20957 templated_operator_saved_lookups (t),
20958 complain|decltype_flag));
20961 case CALL_EXPR:
20963 tree function;
20964 unsigned int nargs;
20965 bool qualified_p;
20966 bool koenig_p;
20967 tree ret;
20969 function = CALL_EXPR_FN (t);
20970 /* Internal function with no arguments. */
20971 if (function == NULL_TREE && call_expr_nargs (t) == 0)
20972 RETURN (t);
20974 /* When we parsed the expression, we determined whether or
20975 not Koenig lookup should be performed. */
20976 koenig_p = KOENIG_LOOKUP_P (t);
20977 if (function == NULL_TREE)
20979 koenig_p = false;
20980 qualified_p = false;
20982 else if (TREE_CODE (function) == SCOPE_REF)
20984 qualified_p = true;
20985 function = tsubst_qualified_id (function, args, complain, in_decl,
20986 /*done=*/false,
20987 /*address_p=*/false);
20989 else if (koenig_p
20990 && (identifier_p (function)
20991 || (TREE_CODE (function) == TEMPLATE_ID_EXPR
20992 && identifier_p (TREE_OPERAND (function, 0)))))
20994 /* Do nothing; calling tsubst_copy_and_build on an identifier
20995 would incorrectly perform unqualified lookup again.
20997 Note that we can also have an IDENTIFIER_NODE if the earlier
20998 unqualified lookup found a dependent local extern declaration
20999 (as per finish_call_expr); in that case koenig_p will be false
21000 and we do want to do the lookup again to find the substituted
21001 declaration. */
21002 qualified_p = false;
21004 if (TREE_CODE (function) == TEMPLATE_ID_EXPR)
21005 /* Use tsubst_copy to substitute through the template arguments
21006 of the template-id without performing unqualified lookup of
21007 the template name. */
21008 function = tsubst_copy (function, args, complain, in_decl);
21010 else
21012 if (TREE_CODE (function) == COMPONENT_REF)
21014 tree op = TREE_OPERAND (function, 1);
21016 qualified_p = (TREE_CODE (op) == SCOPE_REF
21017 || (BASELINK_P (op)
21018 && BASELINK_QUALIFIED_P (op)));
21020 else
21021 qualified_p = false;
21023 if (TREE_CODE (function) == ADDR_EXPR
21024 && TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL)
21025 /* Avoid error about taking the address of a constructor. */
21026 function = TREE_OPERAND (function, 0);
21028 tsubst_flags_t subcomplain = complain;
21029 if (koenig_p && TREE_CODE (function) == FUNCTION_DECL)
21030 /* When KOENIG_P, we don't want to mark_used the callee before
21031 augmenting the overload set via ADL, so during this initial
21032 substitution we disable mark_used by setting tf_conv (68942). */
21033 subcomplain |= tf_conv;
21034 function = tsubst_copy_and_build (function, args, subcomplain, in_decl);
21036 if (BASELINK_P (function))
21037 qualified_p = true;
21040 nargs = call_expr_nargs (t);
21041 releasing_vec call_args;
21042 tsubst_copy_and_build_call_args (t, args, complain, in_decl,
21043 call_args);
21045 /* Stripped-down processing for a call in a thunk. Specifically, in
21046 the thunk template for a generic lambda. */
21047 if (call_from_lambda_thunk_p (t))
21049 /* Now that we've expanded any packs, the number of call args
21050 might be different. */
21051 unsigned int cargs = call_args->length ();
21052 tree thisarg = NULL_TREE;
21053 if (TREE_CODE (function) == COMPONENT_REF)
21055 thisarg = TREE_OPERAND (function, 0);
21056 if (TREE_CODE (thisarg) == INDIRECT_REF)
21057 thisarg = TREE_OPERAND (thisarg, 0);
21058 function = TREE_OPERAND (function, 1);
21059 if (TREE_CODE (function) == BASELINK)
21060 function = BASELINK_FUNCTIONS (function);
21062 /* We aren't going to do normal overload resolution, so force the
21063 template-id to resolve. */
21064 function = resolve_nondeduced_context (function, complain);
21065 for (unsigned i = 0; i < cargs; ++i)
21067 /* In a thunk, pass through args directly, without any
21068 conversions. */
21069 tree arg = (*call_args)[i];
21070 while (TREE_CODE (arg) != PARM_DECL)
21071 arg = TREE_OPERAND (arg, 0);
21072 (*call_args)[i] = arg;
21074 if (thisarg)
21076 /* If there are no other args, just push 'this'. */
21077 if (cargs == 0)
21078 vec_safe_push (call_args, thisarg);
21079 else
21081 /* Otherwise, shift the other args over to make room. */
21082 tree last = (*call_args)[cargs - 1];
21083 vec_safe_push (call_args, last);
21084 for (int i = cargs - 1; i > 0; --i)
21085 (*call_args)[i] = (*call_args)[i - 1];
21086 (*call_args)[0] = thisarg;
21089 ret = build_call_a (function, call_args->length (),
21090 call_args->address ());
21091 /* The thunk location is not interesting. */
21092 SET_EXPR_LOCATION (ret, UNKNOWN_LOCATION);
21093 CALL_FROM_THUNK_P (ret) = true;
21094 if (CLASS_TYPE_P (TREE_TYPE (ret)))
21095 CALL_EXPR_RETURN_SLOT_OPT (ret) = true;
21097 RETURN (ret);
21100 /* We do not perform argument-dependent lookup if normal
21101 lookup finds a non-function, in accordance with the
21102 resolution of DR 218. */
21103 if (koenig_p
21104 && ((is_overloaded_fn (function)
21105 /* If lookup found a member function, the Koenig lookup is
21106 not appropriate, even if an unqualified-name was used
21107 to denote the function. */
21108 && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
21109 || identifier_p (function)
21110 /* C++20 P0846: Lookup found nothing. */
21111 || (TREE_CODE (function) == TEMPLATE_ID_EXPR
21112 && identifier_p (TREE_OPERAND (function, 0))))
21113 /* Only do this when substitution turns a dependent call
21114 into a non-dependent call. */
21115 && type_dependent_expression_p_push (t)
21116 && !any_type_dependent_arguments_p (call_args))
21117 function = perform_koenig_lookup (function, call_args, tf_none);
21119 if (function != NULL_TREE
21120 && (identifier_p (function)
21121 || (TREE_CODE (function) == TEMPLATE_ID_EXPR
21122 && identifier_p (TREE_OPERAND (function, 0))
21123 && !any_dependent_template_arguments_p (TREE_OPERAND
21124 (function, 1))))
21125 && !any_type_dependent_arguments_p (call_args))
21127 bool template_id_p = (TREE_CODE (function) == TEMPLATE_ID_EXPR);
21128 if (template_id_p)
21129 function = TREE_OPERAND (function, 0);
21130 if (koenig_p && (complain & tf_warning_or_error))
21132 /* For backwards compatibility and good diagnostics, try
21133 the unqualified lookup again if we aren't in SFINAE
21134 context. */
21135 tree unq = tsubst_copy_and_build (function, args,
21136 complain, in_decl);
21137 if (unq == error_mark_node)
21138 RETURN (error_mark_node);
21140 if (unq != function)
21142 char const *const msg
21143 = G_("%qD was not declared in this scope, "
21144 "and no declarations were found by "
21145 "argument-dependent lookup at the point "
21146 "of instantiation");
21148 bool in_lambda = (current_class_type
21149 && LAMBDA_TYPE_P (current_class_type));
21150 /* In a lambda fn, we have to be careful to not
21151 introduce new this captures. Legacy code can't
21152 be using lambdas anyway, so it's ok to be
21153 stricter. Be strict with C++20 template-id ADL too.
21154 And be strict if we're already failing anyway. */
21155 bool strict = in_lambda || template_id_p || seen_error();
21156 bool diag = true;
21157 if (strict)
21158 error_at (cp_expr_loc_or_input_loc (t),
21159 msg, function);
21160 else
21161 diag = permerror (cp_expr_loc_or_input_loc (t),
21162 msg, function);
21163 if (diag)
21165 tree fn = unq;
21167 if (INDIRECT_REF_P (fn))
21168 fn = TREE_OPERAND (fn, 0);
21169 if (is_overloaded_fn (fn))
21170 fn = get_first_fn (fn);
21172 if (!DECL_P (fn))
21173 /* Can't say anything more. */;
21174 else if (DECL_CLASS_SCOPE_P (fn))
21176 location_t loc = cp_expr_loc_or_input_loc (t);
21177 inform (loc,
21178 "declarations in dependent base %qT are "
21179 "not found by unqualified lookup",
21180 DECL_CLASS_CONTEXT (fn));
21181 if (current_class_ptr)
21182 inform (loc,
21183 "use %<this->%D%> instead", function);
21184 else
21185 inform (loc,
21186 "use %<%T::%D%> instead",
21187 current_class_name, function);
21189 else
21190 inform (DECL_SOURCE_LOCATION (fn),
21191 "%qD declared here, later in the "
21192 "translation unit", fn);
21193 if (strict)
21194 RETURN (error_mark_node);
21197 function = unq;
21200 if (identifier_p (function))
21202 if (complain & tf_error)
21203 unqualified_name_lookup_error (function);
21204 RETURN (error_mark_node);
21208 /* Remember that there was a reference to this entity. */
21209 if (function != NULL_TREE
21210 && DECL_P (function)
21211 && !mark_used (function, complain) && !(complain & tf_error))
21212 RETURN (error_mark_node);
21214 if (!maybe_fold_fn_template_args (function, complain))
21215 return error_mark_node;
21217 /* Put back tf_decltype for the actual call. */
21218 complain |= decltype_flag;
21220 if (function == NULL_TREE)
21221 switch (CALL_EXPR_IFN (t))
21223 case IFN_LAUNDER:
21224 gcc_assert (nargs == 1);
21225 if (vec_safe_length (call_args) != 1)
21227 error_at (cp_expr_loc_or_input_loc (t),
21228 "wrong number of arguments to "
21229 "%<__builtin_launder%>");
21230 ret = error_mark_node;
21232 else
21233 ret = finish_builtin_launder (cp_expr_loc_or_input_loc (t),
21234 (*call_args)[0], complain);
21235 break;
21237 case IFN_VEC_CONVERT:
21238 gcc_assert (nargs == 1);
21239 if (vec_safe_length (call_args) != 1)
21241 error_at (cp_expr_loc_or_input_loc (t),
21242 "wrong number of arguments to "
21243 "%<__builtin_convertvector%>");
21244 ret = error_mark_node;
21245 break;
21247 ret = cp_build_vec_convert ((*call_args)[0], input_location,
21248 tsubst (TREE_TYPE (t), args,
21249 complain, in_decl),
21250 complain);
21251 if (TREE_CODE (ret) == VIEW_CONVERT_EXPR)
21252 RETURN (ret);
21253 break;
21255 case IFN_SHUFFLEVECTOR:
21257 ret = build_x_shufflevector (input_location, call_args,
21258 complain);
21259 if (ret != error_mark_node)
21260 RETURN (ret);
21261 break;
21264 case IFN_ASSUME:
21265 gcc_assert (nargs == 1);
21266 if (vec_safe_length (call_args) != 1)
21268 error_at (cp_expr_loc_or_input_loc (t),
21269 "wrong number of arguments to "
21270 "%<assume%> attribute");
21271 ret = error_mark_node;
21273 else
21275 tree &arg = (*call_args)[0];
21276 if (!type_dependent_expression_p (arg))
21277 arg = contextual_conv_bool (arg, tf_warning_or_error);
21278 if (error_operand_p (arg))
21280 ret = error_mark_node;
21281 break;
21283 ret = build_assume_call (EXPR_LOCATION (t), arg);
21284 RETURN (ret);
21286 break;
21288 default:
21289 /* Unsupported internal function with arguments. */
21290 gcc_unreachable ();
21292 else if (TREE_CODE (function) == OFFSET_REF
21293 || TREE_CODE (function) == DOTSTAR_EXPR
21294 || TREE_CODE (function) == MEMBER_REF)
21295 ret = build_offset_ref_call_from_tree (function, &call_args,
21296 complain);
21297 else if (TREE_CODE (function) == COMPONENT_REF)
21299 tree instance = TREE_OPERAND (function, 0);
21300 tree fn = TREE_OPERAND (function, 1);
21302 if (processing_template_decl
21303 && (type_dependent_expression_p (instance)
21304 || (!BASELINK_P (fn)
21305 && TREE_CODE (fn) != FIELD_DECL)
21306 || type_dependent_expression_p (fn)
21307 || any_type_dependent_arguments_p (call_args)))
21308 ret = build_min_nt_call_vec (function, call_args);
21309 else if (!BASELINK_P (fn))
21310 ret = finish_call_expr (function, &call_args,
21311 /*disallow_virtual=*/false,
21312 /*koenig_p=*/false,
21313 complain);
21314 else
21315 ret = (build_new_method_call
21316 (instance, fn,
21317 &call_args, NULL_TREE,
21318 qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
21319 /*fn_p=*/NULL,
21320 complain));
21322 else if (concept_check_p (function))
21324 /* FUNCTION is a template-id referring to a concept definition. */
21325 tree id = unpack_concept_check (function);
21326 tree tmpl = TREE_OPERAND (id, 0);
21327 tree args = TREE_OPERAND (id, 1);
21329 /* Calls to standard and variable concepts should have been
21330 previously diagnosed. */
21331 gcc_assert (function_concept_p (tmpl));
21333 /* Ensure the result is wrapped as a call expression. */
21334 ret = build_concept_check (tmpl, args, tf_warning_or_error);
21336 else
21337 ret = finish_call_expr (function, &call_args,
21338 /*disallow_virtual=*/qualified_p,
21339 koenig_p,
21340 complain);
21342 if (ret != error_mark_node)
21344 bool op = CALL_EXPR_OPERATOR_SYNTAX (t);
21345 bool ord = CALL_EXPR_ORDERED_ARGS (t);
21346 bool rev = CALL_EXPR_REVERSE_ARGS (t);
21347 if (op || ord || rev)
21348 if (tree call = extract_call_expr (ret))
21350 CALL_EXPR_OPERATOR_SYNTAX (call) = op;
21351 CALL_EXPR_ORDERED_ARGS (call) = ord;
21352 CALL_EXPR_REVERSE_ARGS (call) = rev;
21354 if (warning_suppressed_p (t, OPT_Wpessimizing_move))
21355 /* This also suppresses -Wredundant-move. */
21356 suppress_warning (ret, OPT_Wpessimizing_move);
21359 RETURN (ret);
21362 case COND_EXPR:
21364 tree cond = RECUR (TREE_OPERAND (t, 0));
21365 cond = mark_rvalue_use (cond);
21366 tree folded_cond = fold_non_dependent_expr (cond, complain);
21367 tree exp1, exp2;
21369 if (TREE_CODE (folded_cond) == INTEGER_CST)
21371 if (integer_zerop (folded_cond))
21373 ++c_inhibit_evaluation_warnings;
21374 exp1 = RECUR (TREE_OPERAND (t, 1));
21375 --c_inhibit_evaluation_warnings;
21376 exp2 = RECUR (TREE_OPERAND (t, 2));
21378 else
21380 exp1 = RECUR (TREE_OPERAND (t, 1));
21381 ++c_inhibit_evaluation_warnings;
21382 exp2 = RECUR (TREE_OPERAND (t, 2));
21383 --c_inhibit_evaluation_warnings;
21385 cond = folded_cond;
21387 else
21389 exp1 = RECUR (TREE_OPERAND (t, 1));
21390 exp2 = RECUR (TREE_OPERAND (t, 2));
21393 warning_sentinel s(warn_duplicated_branches);
21394 RETURN (build_x_conditional_expr (EXPR_LOCATION (t),
21395 cond, exp1, exp2, complain));
21398 case PSEUDO_DTOR_EXPR:
21400 tree op0 = RECUR (TREE_OPERAND (t, 0));
21401 tree op1 = RECUR (TREE_OPERAND (t, 1));
21402 tree op2 = tsubst (TREE_OPERAND (t, 2), args, complain, in_decl);
21403 RETURN (finish_pseudo_destructor_expr (op0, op1, op2,
21404 input_location));
21407 case TREE_LIST:
21408 RETURN (tsubst_tree_list (t, args, complain, in_decl));
21410 case COMPONENT_REF:
21412 tree object;
21413 tree object_type;
21414 tree member;
21415 tree r;
21417 object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
21418 args, complain, in_decl);
21419 /* Remember that there was a reference to this entity. */
21420 if (DECL_P (object)
21421 && !mark_used (object, complain) && !(complain & tf_error))
21422 RETURN (error_mark_node);
21423 object_type = TREE_TYPE (object);
21425 member = TREE_OPERAND (t, 1);
21426 if (BASELINK_P (member))
21427 member = tsubst_baselink (member,
21428 non_reference (TREE_TYPE (object)),
21429 args, complain, in_decl);
21430 else
21431 member = tsubst_copy (member, args, complain, in_decl);
21432 if (member == error_mark_node)
21433 RETURN (error_mark_node);
21435 if (object_type && TYPE_PTRMEMFUNC_P (object_type)
21436 && TREE_CODE (member) == FIELD_DECL)
21438 r = build_ptrmemfunc_access_expr (object, DECL_NAME (member));
21439 RETURN (r);
21441 else if (TREE_CODE (member) == FIELD_DECL)
21443 r = finish_non_static_data_member (member, object, NULL_TREE,
21444 complain);
21445 if (TREE_CODE (r) == COMPONENT_REF)
21446 REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
21447 RETURN (r);
21449 else if (type_dependent_expression_p (object))
21450 /* We can't do much here. */;
21451 else if (!CLASS_TYPE_P (object_type))
21453 if (scalarish_type_p (object_type))
21455 tree s = NULL_TREE;
21456 tree dtor = member;
21458 if (TREE_CODE (dtor) == SCOPE_REF)
21460 s = TREE_OPERAND (dtor, 0);
21461 dtor = TREE_OPERAND (dtor, 1);
21463 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
21465 dtor = TREE_OPERAND (dtor, 0);
21466 if (TYPE_P (dtor))
21467 RETURN (finish_pseudo_destructor_expr
21468 (object, s, dtor, input_location));
21472 else if (TREE_CODE (member) == SCOPE_REF
21473 && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
21475 /* Lookup the template functions now that we know what the
21476 scope is. */
21477 tree scope = TREE_OPERAND (member, 0);
21478 tree tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
21479 tree args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
21480 member = lookup_qualified_name (scope, tmpl, LOOK_want::NORMAL,
21481 /*complain=*/false);
21482 if (BASELINK_P (member))
21484 BASELINK_FUNCTIONS (member)
21485 = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
21486 args);
21487 member = (adjust_result_of_qualified_name_lookup
21488 (member, BINFO_TYPE (BASELINK_BINFO (member)),
21489 object_type));
21491 else
21493 qualified_name_lookup_error (scope, tmpl, member,
21494 input_location);
21495 RETURN (error_mark_node);
21498 else if (TREE_CODE (member) == SCOPE_REF
21499 && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
21500 && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
21502 if (complain & tf_error)
21504 if (TYPE_P (TREE_OPERAND (member, 0)))
21505 error ("%qT is not a class or namespace",
21506 TREE_OPERAND (member, 0));
21507 else
21508 error ("%qD is not a class or namespace",
21509 TREE_OPERAND (member, 0));
21511 RETURN (error_mark_node);
21514 r = finish_class_member_access_expr (object, member,
21515 /*template_p=*/false,
21516 complain);
21517 if (REF_PARENTHESIZED_P (t))
21518 r = force_paren_expr (r);
21519 RETURN (r);
21522 case THROW_EXPR:
21523 RETURN (build_throw
21524 (input_location, RECUR (TREE_OPERAND (t, 0))));
21526 case CONSTRUCTOR:
21528 vec<constructor_elt, va_gc> *n;
21529 constructor_elt *ce;
21530 unsigned HOST_WIDE_INT idx;
21531 bool process_index_p;
21532 int newlen;
21533 bool need_copy_p = false;
21534 tree r;
21536 tsubst_flags_t tcomplain = complain;
21537 if (COMPOUND_LITERAL_P (t))
21538 tcomplain |= tf_tst_ok;
21539 tree type = tsubst (TREE_TYPE (t), args, tcomplain, in_decl);
21540 if (type == error_mark_node)
21541 RETURN (error_mark_node);
21543 /* We do not want to process the index of aggregate
21544 initializers as they are identifier nodes which will be
21545 looked up by digest_init. */
21546 process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
21548 if (null_member_pointer_value_p (t))
21550 gcc_assert (same_type_p (type, TREE_TYPE (t)));
21551 RETURN (t);
21554 n = vec_safe_copy (CONSTRUCTOR_ELTS (t));
21555 newlen = vec_safe_length (n);
21556 FOR_EACH_VEC_SAFE_ELT (n, idx, ce)
21558 if (ce->index && process_index_p
21559 /* An identifier index is looked up in the type
21560 being initialized, not the current scope. */
21561 && TREE_CODE (ce->index) != IDENTIFIER_NODE)
21562 ce->index = RECUR (ce->index);
21564 if (PACK_EXPANSION_P (ce->value))
21566 /* Substitute into the pack expansion. */
21567 ce->value = tsubst_pack_expansion (ce->value, args, complain,
21568 in_decl);
21570 if (ce->value == error_mark_node
21571 || PACK_EXPANSION_P (ce->value))
21573 else if (TREE_VEC_LENGTH (ce->value) == 1)
21574 /* Just move the argument into place. */
21575 ce->value = TREE_VEC_ELT (ce->value, 0);
21576 else
21578 /* Update the length of the final CONSTRUCTOR
21579 arguments vector, and note that we will need to
21580 copy.*/
21581 newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
21582 need_copy_p = true;
21585 else
21586 ce->value = RECUR (ce->value);
21589 if (need_copy_p)
21591 vec<constructor_elt, va_gc> *old_n = n;
21593 vec_alloc (n, newlen);
21594 FOR_EACH_VEC_ELT (*old_n, idx, ce)
21596 if (TREE_CODE (ce->value) == TREE_VEC)
21598 int i, len = TREE_VEC_LENGTH (ce->value);
21599 for (i = 0; i < len; ++i)
21600 CONSTRUCTOR_APPEND_ELT (n, 0,
21601 TREE_VEC_ELT (ce->value, i));
21603 else
21604 CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
21608 r = build_constructor (init_list_type_node, n);
21609 CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
21610 CONSTRUCTOR_IS_DESIGNATED_INIT (r)
21611 = CONSTRUCTOR_IS_DESIGNATED_INIT (t);
21613 if (TREE_HAS_CONSTRUCTOR (t))
21615 fcl_t cl = fcl_functional;
21616 if (CONSTRUCTOR_C99_COMPOUND_LITERAL (t))
21617 cl = fcl_c99;
21618 RETURN (finish_compound_literal (type, r, complain, cl));
21621 TREE_TYPE (r) = type;
21622 RETURN (r);
21625 case TYPEID_EXPR:
21627 tree operand_0 = TREE_OPERAND (t, 0);
21628 if (TYPE_P (operand_0))
21630 operand_0 = tsubst (operand_0, args, complain, in_decl);
21631 RETURN (get_typeid (operand_0, complain));
21633 else
21635 operand_0 = RECUR (operand_0);
21636 RETURN (build_typeid (operand_0, complain));
21640 case VAR_DECL:
21641 if (!args)
21642 RETURN (t);
21643 /* Fall through */
21645 case PARM_DECL:
21647 tree r = tsubst_copy (t, args, complain, in_decl);
21648 /* ??? We're doing a subset of finish_id_expression here. */
21649 if (tree wrap = maybe_get_tls_wrapper_call (r))
21650 /* Replace an evaluated use of the thread_local variable with
21651 a call to its wrapper. */
21652 r = wrap;
21653 else if (outer_automatic_var_p (r))
21654 r = process_outer_var_ref (r, complain);
21656 if (!TYPE_REF_P (TREE_TYPE (t)))
21657 /* If the original type was a reference, we'll be wrapped in
21658 the appropriate INDIRECT_REF. */
21659 r = convert_from_reference (r);
21660 RETURN (r);
21663 case VA_ARG_EXPR:
21665 tree op0 = RECUR (TREE_OPERAND (t, 0));
21666 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
21667 RETURN (build_x_va_arg (EXPR_LOCATION (t), op0, type));
21670 case OFFSETOF_EXPR:
21672 tree object_ptr
21673 = tsubst_copy_and_build (TREE_OPERAND (t, 1), args,
21674 complain, in_decl);
21675 RETURN (finish_offsetof (object_ptr,
21676 RECUR (TREE_OPERAND (t, 0)),
21677 EXPR_LOCATION (t)));
21680 case ADDRESSOF_EXPR:
21681 RETURN (cp_build_addressof (EXPR_LOCATION (t),
21682 RECUR (TREE_OPERAND (t, 0)), complain));
21684 case TRAIT_EXPR:
21686 tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
21687 complain, in_decl);
21688 tree type2 = tsubst (TRAIT_EXPR_TYPE2 (t), args,
21689 complain, in_decl);
21690 RETURN (finish_trait_expr (TRAIT_EXPR_LOCATION (t),
21691 TRAIT_EXPR_KIND (t), type1, type2));
21694 case STMT_EXPR:
21696 tree old_stmt_expr = cur_stmt_expr;
21697 tree stmt_expr = begin_stmt_expr ();
21699 cur_stmt_expr = stmt_expr;
21700 tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl);
21701 stmt_expr = finish_stmt_expr (stmt_expr, false);
21702 cur_stmt_expr = old_stmt_expr;
21704 /* If the resulting list of expression statement is empty,
21705 fold it further into void_node. */
21706 if (empty_expr_stmt_p (stmt_expr))
21707 stmt_expr = void_node;
21709 RETURN (stmt_expr);
21712 case LAMBDA_EXPR:
21714 if (complain & tf_partial)
21716 /* We don't have a full set of template arguments yet; don't touch
21717 the lambda at all. */
21718 gcc_assert (processing_template_decl);
21719 return t;
21721 tree r = tsubst_lambda_expr (t, args, complain, in_decl);
21723 RETURN (build_lambda_object (r));
21726 case TRANSACTION_EXPR:
21727 RETURN (tsubst_expr (t, args, complain, in_decl));
21729 case PAREN_EXPR:
21730 if (REF_PARENTHESIZED_P (t))
21731 RETURN (finish_parenthesized_expr (RECUR (TREE_OPERAND (t, 0))));
21732 else
21733 /* Recreate the PAREN_EXPR from __builtin_assoc_barrier. */
21735 tree op0 = RECUR (TREE_OPERAND (t, 0));
21736 RETURN (build1_loc (input_location, PAREN_EXPR,
21737 TREE_TYPE (op0), op0));
21740 case VEC_PERM_EXPR:
21742 tree op0 = RECUR (TREE_OPERAND (t, 0));
21743 tree op1 = RECUR (TREE_OPERAND (t, 1));
21744 tree op2 = RECUR (TREE_OPERAND (t, 2));
21745 RETURN (build_x_vec_perm_expr (input_location, op0, op1, op2,
21746 complain));
21749 case REQUIRES_EXPR:
21751 tree r = tsubst_requires_expr (t, args, tf_none, in_decl);
21752 RETURN (r);
21755 case RANGE_EXPR:
21756 /* No need to substitute further, a RANGE_EXPR will always be built
21757 with constant operands. */
21758 RETURN (t);
21760 case NON_LVALUE_EXPR:
21761 case VIEW_CONVERT_EXPR:
21763 tree op = RECUR (TREE_OPERAND (t, 0));
21765 if (location_wrapper_p (t))
21766 /* We need to do this here as well as in tsubst_copy so we get the
21767 other tsubst_copy_and_build semantics for a PARM_DECL operand. */
21768 RETURN (maybe_wrap_with_location (op, EXPR_LOCATION (t)));
21770 gcc_checking_assert (TREE_CODE (t) == VIEW_CONVERT_EXPR);
21771 if (REF_PARENTHESIZED_P (t))
21772 /* force_paren_expr can also create a VIEW_CONVERT_EXPR. */
21773 RETURN (finish_parenthesized_expr (op));
21775 /* Otherwise, we're dealing with a wrapper to make a C++20 template
21776 parameter object const. */
21777 if (TREE_TYPE (op) == NULL_TREE
21778 || !CP_TYPE_CONST_P (TREE_TYPE (op)))
21780 /* The template argument is not const, presumably because
21781 it is still dependent, and so not the const template parm
21782 object. */
21783 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
21784 if (TREE_CODE (op) == CONSTRUCTOR
21785 || TREE_CODE (op) == IMPLICIT_CONV_EXPR)
21787 /* Don't add a wrapper to these. */
21788 op = copy_node (op);
21789 TREE_TYPE (op) = type;
21791 else
21792 /* Do add a wrapper otherwise (in particular, if op is
21793 another TEMPLATE_PARM_INDEX). */
21794 op = build1 (VIEW_CONVERT_EXPR, type, op);
21796 RETURN (op);
21799 default:
21800 /* Handle Objective-C++ constructs, if appropriate. */
21802 tree subst
21803 = objcp_tsubst_copy_and_build (t, args, complain, in_decl);
21804 if (subst)
21805 RETURN (subst);
21807 RETURN (tsubst_copy (t, args, complain, in_decl));
21810 #undef RECUR
21811 #undef RETURN
21812 out:
21813 input_location = save_loc;
21814 return retval;
21817 /* Verify that the instantiated ARGS are valid. For type arguments,
21818 make sure that the type's linkage is ok. For non-type arguments,
21819 make sure they are constants if they are integral or enumerations.
21820 Emit an error under control of COMPLAIN, and return TRUE on error. */
21822 static bool
21823 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
21825 if (dependent_template_arg_p (t))
21826 return false;
21827 if (ARGUMENT_PACK_P (t))
21829 tree vec = ARGUMENT_PACK_ARGS (t);
21830 int len = TREE_VEC_LENGTH (vec);
21831 bool result = false;
21832 int i;
21834 for (i = 0; i < len; ++i)
21835 if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
21836 result = true;
21837 return result;
21839 else if (TYPE_P (t))
21841 /* [basic.link]: A name with no linkage (notably, the name
21842 of a class or enumeration declared in a local scope)
21843 shall not be used to declare an entity with linkage.
21844 This implies that names with no linkage cannot be used as
21845 template arguments
21847 DR 757 relaxes this restriction for C++0x. */
21848 tree nt = (cxx_dialect > cxx98 ? NULL_TREE
21849 : no_linkage_check (t, /*relaxed_p=*/false));
21851 if (nt)
21853 /* DR 488 makes use of a type with no linkage cause
21854 type deduction to fail. */
21855 if (complain & tf_error)
21857 if (TYPE_UNNAMED_P (nt))
21858 error ("%qT is/uses unnamed type", t);
21859 else
21860 error ("template argument for %qD uses local type %qT",
21861 tmpl, t);
21863 return true;
21865 /* In order to avoid all sorts of complications, we do not
21866 allow variably-modified types as template arguments. */
21867 else if (variably_modified_type_p (t, NULL_TREE))
21869 if (complain & tf_error)
21870 error ("%qT is a variably modified type", t);
21871 return true;
21874 /* Class template and alias template arguments should be OK. */
21875 else if (DECL_TYPE_TEMPLATE_P (t))
21877 /* A non-type argument of integral or enumerated type must be a
21878 constant. */
21879 else if (TREE_TYPE (t)
21880 && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
21881 && !REFERENCE_REF_P (t)
21882 && !TREE_CONSTANT (t))
21884 if (complain & tf_error)
21885 error ("integral expression %qE is not constant", t);
21886 return true;
21888 return false;
21891 static bool
21892 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
21894 int ix, len = DECL_NTPARMS (tmpl);
21895 bool result = false;
21897 for (ix = 0; ix != len; ix++)
21899 if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
21900 result = true;
21902 if (result && (complain & tf_error))
21903 error (" trying to instantiate %qD", tmpl);
21904 return result;
21907 /* Call mark_used on each entity within the non-type template arguments in
21908 ARGS for an instantiation of TMPL, to ensure that each such entity is
21909 considered odr-used (and therefore marked for instantiation) regardless of
21910 whether the specialization was first formed in a template context (which
21911 inhibits mark_used).
21913 This function assumes push_to_top_level has been called beforehand. */
21915 static void
21916 mark_template_arguments_used (tree tmpl, tree args)
21918 /* It suffices to do this only when instantiating a primary template. */
21919 if (TREE_CODE (tmpl) != TEMPLATE_DECL || !PRIMARY_TEMPLATE_P (tmpl))
21920 return;
21922 /* We already marked outer arguments when specializing the context. */
21923 args = INNERMOST_TEMPLATE_ARGS (args);
21925 for (tree arg : tree_vec_range (args))
21927 /* A (pointer/reference to) function or variable NTTP argument. */
21928 if (TREE_CODE (arg) == ADDR_EXPR
21929 || TREE_CODE (arg) == INDIRECT_REF)
21931 while (TREE_CODE (arg) == ADDR_EXPR
21932 || REFERENCE_REF_P (arg)
21933 || CONVERT_EXPR_P (arg))
21934 arg = TREE_OPERAND (arg, 0);
21935 if (VAR_OR_FUNCTION_DECL_P (arg))
21937 /* Pass tf_none to avoid duplicate diagnostics: if this call
21938 fails then an earlier call to mark_used for this argument
21939 must have also failed and emitted a diagnostic. */
21940 bool ok = mark_used (arg, tf_none);
21941 gcc_checking_assert (ok || seen_error ());
21944 /* A class NTTP argument. */
21945 else if (VAR_P (arg)
21946 && DECL_NTTP_OBJECT_P (arg))
21948 auto mark_used_r = [](tree *tp, int *, void *) {
21949 if (VAR_OR_FUNCTION_DECL_P (*tp))
21951 bool ok = mark_used (*tp, tf_none);
21952 gcc_checking_assert (ok || seen_error ());
21954 return NULL_TREE;
21956 cp_walk_tree_without_duplicates (&DECL_INITIAL (arg),
21957 mark_used_r, nullptr);
21962 /* We're out of SFINAE context now, so generate diagnostics for the access
21963 errors we saw earlier when instantiating D from TMPL and ARGS. */
21965 static void
21966 recheck_decl_substitution (tree d, tree tmpl, tree args)
21968 tree pattern = DECL_TEMPLATE_RESULT (tmpl);
21969 tree type = TREE_TYPE (pattern);
21970 location_t loc = input_location;
21972 push_access_scope (d);
21973 push_deferring_access_checks (dk_no_deferred);
21974 input_location = DECL_SOURCE_LOCATION (pattern);
21975 tsubst (type, args, tf_warning_or_error, d);
21976 input_location = loc;
21977 pop_deferring_access_checks ();
21978 pop_access_scope (d);
21981 /* Instantiate the indicated variable, function, or alias template TMPL with
21982 the template arguments in TARG_PTR. */
21984 tree
21985 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
21987 auto_timevar tv (TV_TEMPLATE_INST);
21989 tree targ_ptr = orig_args;
21990 tree fndecl;
21991 tree gen_tmpl;
21992 tree spec;
21993 bool access_ok = true;
21995 if (tmpl == error_mark_node)
21996 return error_mark_node;
21998 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
22000 if (modules_p ())
22001 lazy_load_pendings (tmpl);
22003 /* If this function is a clone, handle it specially. */
22004 if (DECL_CLONED_FUNCTION_P (tmpl))
22006 tree spec;
22007 tree clone;
22009 /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
22010 DECL_CLONED_FUNCTION. */
22011 spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
22012 targ_ptr, complain);
22013 if (spec == error_mark_node)
22014 return error_mark_node;
22016 /* Look for the clone. */
22017 FOR_EACH_CLONE (clone, spec)
22018 if (DECL_NAME (clone) == DECL_NAME (tmpl))
22019 return clone;
22020 /* We should always have found the clone by now. */
22021 gcc_unreachable ();
22022 return NULL_TREE;
22025 if (targ_ptr == error_mark_node)
22026 return error_mark_node;
22028 /* Check to see if we already have this specialization. */
22029 gen_tmpl = most_general_template (tmpl);
22030 if (TMPL_ARGS_DEPTH (targ_ptr)
22031 < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)))
22032 /* targ_ptr only has the innermost template args, so add the outer ones
22033 from tmpl, which could be either a partial instantiation or gen_tmpl (in
22034 the case of a non-dependent call within a template definition). */
22035 targ_ptr = (add_outermost_template_args
22036 (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (tmpl)),
22037 targ_ptr));
22039 /* It would be nice to avoid hashing here and then again in tsubst_decl,
22040 but it doesn't seem to be on the hot path. */
22041 spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
22043 gcc_checking_assert (tmpl == gen_tmpl
22044 || ((fndecl
22045 = retrieve_specialization (tmpl, orig_args, 0))
22046 == spec)
22047 || fndecl == NULL_TREE);
22049 if (spec != NULL_TREE)
22051 if (FNDECL_HAS_ACCESS_ERRORS (spec))
22053 if (complain & tf_error)
22054 recheck_decl_substitution (spec, gen_tmpl, targ_ptr);
22055 return error_mark_node;
22057 return spec;
22060 if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
22061 complain))
22062 return error_mark_node;
22064 /* We are building a FUNCTION_DECL, during which the access of its
22065 parameters and return types have to be checked. However this
22066 FUNCTION_DECL which is the desired context for access checking
22067 is not built yet. We solve this chicken-and-egg problem by
22068 deferring all checks until we have the FUNCTION_DECL. */
22069 push_deferring_access_checks (dk_deferred);
22071 /* Instantiation of the function happens in the context of the function
22072 template, not the context of the overload resolution we're doing. */
22073 push_to_top_level ();
22074 /* If there are dependent arguments, e.g. because we're doing partial
22075 ordering, make sure processing_template_decl stays set. */
22076 if (uses_template_parms (targ_ptr))
22077 ++processing_template_decl;
22078 if (DECL_CLASS_SCOPE_P (gen_tmpl))
22080 tree ctx;
22081 if (!uses_template_parms (DECL_CONTEXT (tmpl)))
22082 /* If the context of the partially instantiated template is
22083 already non-dependent, then we might as well use it. */
22084 ctx = DECL_CONTEXT (tmpl);
22085 else
22086 ctx = tsubst_aggr_type (DECL_CONTEXT (gen_tmpl), targ_ptr,
22087 complain, gen_tmpl, true);
22088 push_nested_class (ctx);
22091 tree pattern = DECL_TEMPLATE_RESULT (gen_tmpl);
22093 tree partial_ti = NULL_TREE;
22094 fndecl = NULL_TREE;
22095 if (VAR_P (pattern))
22097 /* We need to determine if we're using a partial or explicit
22098 specialization now, because the type of the variable could be
22099 different. */
22100 tree tid = build2 (TEMPLATE_ID_EXPR, NULL_TREE, tmpl, targ_ptr);
22101 partial_ti = most_specialized_partial_spec (tid, complain);
22102 if (partial_ti == error_mark_node)
22103 pattern = error_mark_node;
22104 else if (partial_ti)
22106 tree partial_tmpl = TI_TEMPLATE (partial_ti);
22107 tree partial_args = TI_ARGS (partial_ti);
22108 tree partial_pat = DECL_TEMPLATE_RESULT (partial_tmpl);
22109 fndecl = tsubst (partial_pat, partial_args, complain, gen_tmpl);
22113 /* Substitute template parameters to obtain the specialization. */
22114 if (fndecl == NULL_TREE)
22115 fndecl = tsubst (pattern, targ_ptr, complain, gen_tmpl);
22116 if (DECL_CLASS_SCOPE_P (gen_tmpl))
22117 pop_nested_class ();
22118 pop_from_top_level ();
22120 if (fndecl == error_mark_node)
22122 pop_deferring_access_checks ();
22123 return error_mark_node;
22126 /* The DECL_TI_TEMPLATE should always be the immediate parent
22127 template, not the most general template. */
22128 DECL_TI_TEMPLATE (fndecl) = tmpl;
22129 DECL_TI_ARGS (fndecl) = targ_ptr;
22130 if (VAR_P (pattern))
22131 /* Now that we we've formed this variable template specialization,
22132 remember the result of most_specialized_partial_spec for it. */
22133 TI_PARTIAL_INFO (DECL_TEMPLATE_INFO (fndecl)) = partial_ti;
22135 set_instantiating_module (fndecl);
22137 /* Now we know the specialization, compute access previously
22138 deferred. Do no access control for inheriting constructors,
22139 as we already checked access for the inherited constructor. */
22140 if (!(flag_new_inheriting_ctors
22141 && DECL_INHERITED_CTOR (fndecl)))
22143 push_access_scope (fndecl);
22144 if (!perform_deferred_access_checks (complain))
22145 access_ok = false;
22146 pop_access_scope (fndecl);
22148 pop_deferring_access_checks ();
22150 /* If we've just instantiated the main entry point for a function,
22151 instantiate all the alternate entry points as well. We do this
22152 by cloning the instantiation of the main entry point, not by
22153 instantiating the template clones. */
22154 if (tree chain = DECL_CHAIN (gen_tmpl))
22155 if (DECL_P (chain) && DECL_CLONED_FUNCTION_P (chain))
22156 clone_cdtor (fndecl, /*update_methods=*/false);
22158 if (!access_ok)
22160 if (!(complain & tf_error))
22162 /* Remember to reinstantiate when we're out of SFINAE so the user
22163 can see the errors. */
22164 FNDECL_HAS_ACCESS_ERRORS (fndecl) = true;
22166 return error_mark_node;
22169 return fndecl;
22172 /* Instantiate the alias template TMPL with ARGS. Also push a template
22173 instantiation level, which instantiate_template doesn't do because
22174 functions and variables have sufficient context established by the
22175 callers. */
22177 static tree
22178 instantiate_alias_template (tree tmpl, tree args, tsubst_flags_t complain)
22180 if (tmpl == error_mark_node || args == error_mark_node)
22181 return error_mark_node;
22183 args = coerce_template_parms (DECL_TEMPLATE_PARMS (tmpl),
22184 args, tmpl, complain);
22185 if (args == error_mark_node)
22186 return error_mark_node;
22188 /* FIXME check for satisfaction in check_instantiated_args. */
22189 if (!constraints_satisfied_p (tmpl, args))
22191 if (complain & tf_error)
22193 auto_diagnostic_group d;
22194 error ("template constraint failure for %qD", tmpl);
22195 diagnose_constraints (input_location, tmpl, args);
22197 return error_mark_node;
22200 if (!push_tinst_level (tmpl, args))
22201 return error_mark_node;
22202 tree r = instantiate_template (tmpl, args, complain);
22203 pop_tinst_level ();
22205 if (tree d = dependent_alias_template_spec_p (TREE_TYPE (r), nt_opaque))
22207 /* An alias template specialization can be dependent
22208 even if its underlying type is not. */
22209 TYPE_DEPENDENT_P (d) = true;
22210 TYPE_DEPENDENT_P_VALID (d) = true;
22211 /* Sometimes a dependent alias spec is equivalent to its expansion,
22212 sometimes not. So always use structural_comptypes. */
22213 SET_TYPE_STRUCTURAL_EQUALITY (d);
22216 return r;
22219 /* PARM is a template parameter pack for FN. Returns true iff
22220 PARM is used in a deducible way in the argument list of FN. */
22222 static bool
22223 pack_deducible_p (tree parm, tree fn)
22225 tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
22226 for (; t; t = TREE_CHAIN (t))
22228 tree type = TREE_VALUE (t);
22229 tree packs;
22230 if (!PACK_EXPANSION_P (type))
22231 continue;
22232 for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
22233 packs; packs = TREE_CHAIN (packs))
22234 if (template_args_equal (TREE_VALUE (packs), parm))
22236 /* The template parameter pack is used in a function parameter
22237 pack. If this is the end of the parameter list, the
22238 template parameter pack is deducible. */
22239 if (TREE_CHAIN (t) == void_list_node)
22240 return true;
22241 else
22242 /* Otherwise, not. Well, it could be deduced from
22243 a non-pack parameter, but doing so would end up with
22244 a deduction mismatch, so don't bother. */
22245 return false;
22248 /* The template parameter pack isn't used in any function parameter
22249 packs, but it might be used deeper, e.g. tuple<Args...>. */
22250 return true;
22253 /* Subroutine of fn_type_unification: check non-dependent parms for
22254 convertibility. */
22256 static int
22257 check_non_deducible_conversions (tree parms, const tree *args, unsigned nargs,
22258 tree fn, unification_kind_t strict, int flags,
22259 struct conversion **convs, bool explain_p)
22261 /* Non-constructor methods need to leave a conversion for 'this', which
22262 isn't included in nargs here. */
22263 unsigned offset = (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
22264 && !DECL_CONSTRUCTOR_P (fn));
22266 for (unsigned ia = 0;
22267 parms && parms != void_list_node && ia < nargs; )
22269 tree parm = TREE_VALUE (parms);
22271 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
22272 && (!TREE_CHAIN (parms)
22273 || TREE_CHAIN (parms) == void_list_node))
22274 /* For a function parameter pack that occurs at the end of the
22275 parameter-declaration-list, the type A of each remaining
22276 argument of the call is compared with the type P of the
22277 declarator-id of the function parameter pack. */
22278 break;
22280 parms = TREE_CHAIN (parms);
22282 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
22283 /* For a function parameter pack that does not occur at the
22284 end of the parameter-declaration-list, the type of the
22285 parameter pack is a non-deduced context. */
22286 continue;
22288 if (!uses_template_parms (parm))
22290 tree arg = args[ia];
22291 conversion **conv_p = convs ? &convs[ia+offset] : NULL;
22292 int lflags = conv_flags (ia, nargs, fn, arg, flags);
22294 if (check_non_deducible_conversion (parm, arg, strict, lflags,
22295 conv_p, explain_p))
22296 return 1;
22299 ++ia;
22302 return 0;
22305 /* The FN is a TEMPLATE_DECL for a function. ARGS is an array with
22306 NARGS elements of the arguments that are being used when calling
22307 it. TARGS is a vector into which the deduced template arguments
22308 are placed.
22310 Returns either a FUNCTION_DECL for the matching specialization of FN or
22311 NULL_TREE if no suitable specialization can be found. If EXPLAIN_P is
22312 true, diagnostics will be printed to explain why it failed.
22314 If FN is a conversion operator, or we are trying to produce a specific
22315 specialization, RETURN_TYPE is the return type desired.
22317 The EXPLICIT_TARGS are explicit template arguments provided via a
22318 template-id.
22320 The parameter STRICT is one of:
22322 DEDUCE_CALL:
22323 We are deducing arguments for a function call, as in
22324 [temp.deduct.call]. If RETURN_TYPE is non-null, we are
22325 deducing arguments for a call to the result of a conversion
22326 function template, as in [over.call.object].
22328 DEDUCE_CONV:
22329 We are deducing arguments for a conversion function, as in
22330 [temp.deduct.conv].
22332 DEDUCE_EXACT:
22333 We are deducing arguments when doing an explicit instantiation
22334 as in [temp.explicit], when determining an explicit specialization
22335 as in [temp.expl.spec], or when taking the address of a function
22336 template, as in [temp.deduct.funcaddr]. */
22338 tree
22339 fn_type_unification (tree fn,
22340 tree explicit_targs,
22341 tree targs,
22342 const tree *args,
22343 unsigned int nargs,
22344 tree return_type,
22345 unification_kind_t strict,
22346 int flags,
22347 struct conversion **convs,
22348 bool explain_p,
22349 bool decltype_p)
22351 tree parms;
22352 tree fntype;
22353 tree decl = NULL_TREE;
22354 tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
22355 bool ok;
22356 static int deduction_depth;
22357 /* type_unification_real will pass back any access checks from default
22358 template argument substitution. */
22359 vec<deferred_access_check, va_gc> *checks = NULL;
22360 /* We don't have all the template args yet. */
22361 bool incomplete = true;
22363 tree orig_fn = fn;
22364 if (flag_new_inheriting_ctors)
22365 fn = strip_inheriting_ctors (fn);
22367 tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
22368 tree r = error_mark_node;
22370 tree full_targs = targs;
22371 if (TMPL_ARGS_DEPTH (targs)
22372 < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (fn)))
22373 full_targs = (add_outermost_template_args
22374 (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (fn)),
22375 targs));
22377 if (decltype_p)
22378 complain |= tf_decltype;
22380 /* In C++0x, it's possible to have a function template whose type depends
22381 on itself recursively. This is most obvious with decltype, but can also
22382 occur with enumeration scope (c++/48969). So we need to catch infinite
22383 recursion and reject the substitution at deduction time; this function
22384 will return error_mark_node for any repeated substitution.
22386 This also catches excessive recursion such as when f<N> depends on
22387 f<N-1> across all integers, and returns error_mark_node for all the
22388 substitutions back up to the initial one.
22390 This is, of course, not reentrant. */
22391 if (excessive_deduction_depth)
22392 return error_mark_node;
22393 ++deduction_depth;
22395 gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
22397 fntype = TREE_TYPE (fn);
22398 if (explicit_targs)
22400 /* [temp.deduct]
22402 The specified template arguments must match the template
22403 parameters in kind (i.e., type, nontype, template), and there
22404 must not be more arguments than there are parameters;
22405 otherwise type deduction fails.
22407 Nontype arguments must match the types of the corresponding
22408 nontype template parameters, or must be convertible to the
22409 types of the corresponding nontype parameters as specified in
22410 _temp.arg.nontype_, otherwise type deduction fails.
22412 All references in the function type of the function template
22413 to the corresponding template parameters are replaced by the
22414 specified template argument values. If a substitution in a
22415 template parameter or in the function type of the function
22416 template results in an invalid type, type deduction fails. */
22417 int i, len = TREE_VEC_LENGTH (tparms);
22418 location_t loc = input_location;
22419 incomplete = false;
22421 if (explicit_targs == error_mark_node)
22422 goto fail;
22424 if (TMPL_ARGS_DEPTH (explicit_targs)
22425 < TMPL_ARGS_DEPTH (full_targs))
22426 explicit_targs = add_outermost_template_args (full_targs,
22427 explicit_targs);
22429 /* Adjust any explicit template arguments before entering the
22430 substitution context. */
22431 explicit_targs
22432 = (coerce_template_parms (tparms, explicit_targs, fn,
22433 complain|tf_partial,
22434 /*require_all_args=*/false));
22435 if (explicit_targs == error_mark_node)
22436 goto fail;
22438 /* Substitute the explicit args into the function type. This is
22439 necessary so that, for instance, explicitly declared function
22440 arguments can match null pointed constants. If we were given
22441 an incomplete set of explicit args, we must not do semantic
22442 processing during substitution as we could create partial
22443 instantiations. */
22444 for (i = 0; i < len; i++)
22446 tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
22447 bool parameter_pack = false;
22448 tree targ = TREE_VEC_ELT (explicit_targs, i);
22450 /* Dig out the actual parm. */
22451 if (TREE_CODE (parm) == TYPE_DECL
22452 || TREE_CODE (parm) == TEMPLATE_DECL)
22454 parm = TREE_TYPE (parm);
22455 parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
22457 else if (TREE_CODE (parm) == PARM_DECL)
22459 parm = DECL_INITIAL (parm);
22460 parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
22463 if (targ == NULL_TREE)
22464 /* No explicit argument for this template parameter. */
22465 incomplete = true;
22466 else if (parameter_pack && pack_deducible_p (parm, fn))
22468 /* Mark the argument pack as "incomplete". We could
22469 still deduce more arguments during unification.
22470 We remove this mark in type_unification_real. */
22471 ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
22472 ARGUMENT_PACK_EXPLICIT_ARGS (targ)
22473 = ARGUMENT_PACK_ARGS (targ);
22475 /* We have some incomplete argument packs. */
22476 incomplete = true;
22480 if (incomplete)
22482 if (!push_tinst_level (fn, explicit_targs))
22484 excessive_deduction_depth = true;
22485 goto fail;
22487 ++processing_template_decl;
22488 input_location = DECL_SOURCE_LOCATION (fn);
22489 /* Ignore any access checks; we'll see them again in
22490 instantiate_template and they might have the wrong
22491 access path at this point. */
22492 push_deferring_access_checks (dk_deferred);
22493 tsubst_flags_t ecomplain = complain | tf_partial | tf_fndecl_type;
22494 fntype = tsubst (TREE_TYPE (fn), explicit_targs, ecomplain, NULL_TREE);
22495 pop_deferring_access_checks ();
22496 input_location = loc;
22497 --processing_template_decl;
22498 pop_tinst_level ();
22500 if (fntype == error_mark_node)
22501 goto fail;
22504 /* Place the explicitly specified arguments in TARGS. */
22505 explicit_targs = INNERMOST_TEMPLATE_ARGS (explicit_targs);
22506 for (i = NUM_TMPL_ARGS (explicit_targs); i--;)
22507 TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (explicit_targs, i);
22508 if (!incomplete && CHECKING_P
22509 && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
22510 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
22511 (targs, NUM_TMPL_ARGS (explicit_targs));
22514 if (return_type && strict != DEDUCE_CALL)
22516 tree *new_args = XALLOCAVEC (tree, nargs + 1);
22517 new_args[0] = return_type;
22518 memcpy (new_args + 1, args, nargs * sizeof (tree));
22519 args = new_args;
22520 ++nargs;
22523 if (!incomplete)
22524 goto deduced;
22526 /* Never do unification on the 'this' parameter. */
22527 parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
22529 if (return_type && strict == DEDUCE_CALL)
22531 /* We're deducing for a call to the result of a template conversion
22532 function. The parms we really want are in return_type. */
22533 if (INDIRECT_TYPE_P (return_type))
22534 return_type = TREE_TYPE (return_type);
22535 parms = TYPE_ARG_TYPES (return_type);
22537 else if (return_type)
22539 parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
22542 /* We allow incomplete unification without an error message here
22543 because the standard doesn't seem to explicitly prohibit it. Our
22544 callers must be ready to deal with unification failures in any
22545 event. */
22547 /* If we aren't explaining yet, push tinst context so we can see where
22548 any errors (e.g. from class instantiations triggered by instantiation
22549 of default template arguments) come from. If we are explaining, this
22550 context is redundant. */
22551 if (!explain_p && !push_tinst_level (fn, targs))
22553 excessive_deduction_depth = true;
22554 goto fail;
22557 ok = !type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
22558 full_targs, parms, args, nargs, /*subr=*/0,
22559 strict, &checks, explain_p);
22560 if (!explain_p)
22561 pop_tinst_level ();
22562 if (!ok)
22563 goto fail;
22565 /* Now that we have bindings for all of the template arguments,
22566 ensure that the arguments deduced for the template template
22567 parameters have compatible template parameter lists. We cannot
22568 check this property before we have deduced all template
22569 arguments, because the template parameter types of a template
22570 template parameter might depend on prior template parameters
22571 deduced after the template template parameter. The following
22572 ill-formed example illustrates this issue:
22574 template<typename T, template<T> class C> void f(C<5>, T);
22576 template<int N> struct X {};
22578 void g() {
22579 f(X<5>(), 5l); // error: template argument deduction fails
22582 The template parameter list of 'C' depends on the template type
22583 parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
22584 'long'. Thus, we can't check that 'C' cannot bind to 'X' at the
22585 time that we deduce 'C'. */
22586 if (!template_template_parm_bindings_ok_p
22587 (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
22589 unify_inconsistent_template_template_parameters (explain_p);
22590 goto fail;
22593 deduced:
22595 /* CWG2369: Check satisfaction before non-deducible conversions. */
22596 if (!constraints_satisfied_p (fn, targs))
22598 if (explain_p)
22599 diagnose_constraints (DECL_SOURCE_LOCATION (fn), fn, targs);
22600 goto fail;
22603 /* DR 1391: All parameters have args, now check non-dependent parms for
22604 convertibility. We don't do this if all args were explicitly specified,
22605 as the standard says that we substitute explicit args immediately. */
22606 if (incomplete
22607 && check_non_deducible_conversions (parms, args, nargs, fn, strict, flags,
22608 convs, explain_p))
22609 goto fail;
22611 /* All is well so far. Now, check:
22613 [temp.deduct]
22615 When all template arguments have been deduced, all uses of
22616 template parameters in nondeduced contexts are replaced with
22617 the corresponding deduced argument values. If the
22618 substitution results in an invalid type, as described above,
22619 type deduction fails. */
22620 if (!push_tinst_level (fn, targs))
22622 excessive_deduction_depth = true;
22623 goto fail;
22626 /* Also collect access checks from the instantiation. */
22627 reopen_deferring_access_checks (checks);
22629 decl = instantiate_template (fn, targs, complain);
22631 checks = get_deferred_access_checks ();
22632 pop_deferring_access_checks ();
22634 pop_tinst_level ();
22636 if (decl == error_mark_node)
22637 goto fail;
22639 /* Now perform any access checks encountered during substitution. */
22640 push_access_scope (decl);
22641 ok = perform_access_checks (checks, complain);
22642 pop_access_scope (decl);
22643 if (!ok)
22644 goto fail;
22646 /* If we're looking for an exact match, check that what we got
22647 is indeed an exact match. It might not be if some template
22648 parameters are used in non-deduced contexts. But don't check
22649 for an exact match if we have dependent template arguments;
22650 in that case we're doing partial ordering, and we already know
22651 that we have two candidates that will provide the actual type. */
22652 if (strict == DEDUCE_EXACT && !any_dependent_template_arguments_p (targs))
22654 tree substed = TREE_TYPE (decl);
22655 unsigned int i;
22657 tree sarg
22658 = skip_artificial_parms_for (decl, TYPE_ARG_TYPES (substed));
22659 if (return_type)
22660 sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
22661 for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
22662 if (!same_type_p (args[i], TREE_VALUE (sarg)))
22664 unify_type_mismatch (explain_p, args[i],
22665 TREE_VALUE (sarg));
22666 goto fail;
22668 if ((i < nargs || sarg)
22669 /* add_candidates uses DEDUCE_EXACT for x.operator foo(), but args
22670 doesn't contain the trailing void, and conv fns are always (). */
22671 && !DECL_CONV_FN_P (decl))
22673 unsigned nsargs = i + list_length (sarg);
22674 unify_arity (explain_p, nargs, nsargs);
22675 goto fail;
22679 /* After doing deduction with the inherited constructor, actually return an
22680 instantiation of the inheriting constructor. */
22681 if (orig_fn != fn)
22682 decl = instantiate_template (orig_fn, targs, complain);
22684 r = decl;
22686 fail:
22687 --deduction_depth;
22688 if (excessive_deduction_depth)
22690 if (deduction_depth == 0)
22691 /* Reset once we're all the way out. */
22692 excessive_deduction_depth = false;
22695 return r;
22698 /* Returns true iff PARM is a forwarding reference in the context of
22699 template argument deduction for TMPL. */
22701 static bool
22702 forwarding_reference_p (tree parm, tree tmpl)
22704 /* [temp.deduct.call], "A forwarding reference is an rvalue reference to a
22705 cv-unqualified template parameter ..." */
22706 if (TYPE_REF_P (parm)
22707 && TYPE_REF_IS_RVALUE (parm)
22708 && TREE_CODE (TREE_TYPE (parm)) == TEMPLATE_TYPE_PARM
22709 && cp_type_quals (TREE_TYPE (parm)) == TYPE_UNQUALIFIED)
22711 parm = TREE_TYPE (parm);
22712 /* [temp.deduct.call], "... that does not represent a template parameter
22713 of a class template (during class template argument deduction)." */
22714 if (tmpl
22715 && deduction_guide_p (tmpl)
22716 && DECL_ARTIFICIAL (tmpl))
22718 /* Since the template parameters of a synthesized guide consist of
22719 the template parameters of the class template followed by those of
22720 the constructor (if any), we can tell if PARM represents a template
22721 parameter of the class template by comparing its index with the
22722 arity of the class template. */
22723 tree ctmpl = CLASSTYPE_TI_TEMPLATE (TREE_TYPE (TREE_TYPE (tmpl)));
22724 if (TEMPLATE_TYPE_IDX (parm)
22725 < TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (ctmpl)))
22726 return false;
22728 return true;
22730 return false;
22733 /* Adjust types before performing type deduction, as described in
22734 [temp.deduct.call] and [temp.deduct.conv]. The rules in these two
22735 sections are symmetric. PARM is the type of a function parameter
22736 or the return type of the conversion function. ARG is the type of
22737 the argument passed to the call, or the type of the value
22738 initialized with the result of the conversion function.
22739 ARG_EXPR is the original argument expression, which may be null. */
22741 static int
22742 maybe_adjust_types_for_deduction (tree tparms,
22743 unification_kind_t strict,
22744 tree* parm,
22745 tree* arg,
22746 tree arg_expr)
22748 int result = 0;
22750 switch (strict)
22752 case DEDUCE_CALL:
22753 break;
22755 case DEDUCE_CONV:
22756 /* [temp.deduct.conv] First remove a reference type on parm.
22757 DRs 322 & 976 affected this. */
22758 if (TYPE_REF_P (*parm))
22759 *parm = TREE_TYPE (*parm);
22761 /* Swap PARM and ARG throughout the remainder of this
22762 function; the handling is precisely symmetric since PARM
22763 will initialize ARG rather than vice versa. */
22764 std::swap (parm, arg);
22766 break;
22768 case DEDUCE_EXACT:
22769 /* Core issue #873: Do the DR606 thing (see below) for these cases,
22770 too, but here handle it by stripping the reference from PARM
22771 rather than by adding it to ARG. */
22772 if (forwarding_reference_p (*parm, TPARMS_PRIMARY_TEMPLATE (tparms))
22773 && TYPE_REF_P (*arg)
22774 && !TYPE_REF_IS_RVALUE (*arg))
22775 *parm = TREE_TYPE (*parm);
22776 /* Nothing else to do in this case. */
22777 return 0;
22779 default:
22780 gcc_unreachable ();
22783 if (!TYPE_REF_P (*parm))
22785 /* [temp.deduct.call]
22787 If P is not a reference type:
22789 --If A is an array type, the pointer type produced by the
22790 array-to-pointer standard conversion (_conv.array_) is
22791 used in place of A for type deduction; otherwise,
22793 --If A is a function type, the pointer type produced by
22794 the function-to-pointer standard conversion
22795 (_conv.func_) is used in place of A for type deduction;
22796 otherwise,
22798 --If A is a cv-qualified type, the top level
22799 cv-qualifiers of A's type are ignored for type
22800 deduction. */
22801 if (TREE_CODE (*arg) == ARRAY_TYPE)
22802 *arg = build_pointer_type (TREE_TYPE (*arg));
22803 else if (TREE_CODE (*arg) == FUNCTION_TYPE)
22804 *arg = build_pointer_type (*arg);
22805 else
22806 *arg = TYPE_MAIN_VARIANT (*arg);
22809 /* [temp.deduct.call], "If P is a forwarding reference and the argument is
22810 an lvalue, the type 'lvalue reference to A' is used in place of A for
22811 type deduction." */
22812 if (forwarding_reference_p (*parm, TPARMS_PRIMARY_TEMPLATE (tparms))
22813 && (arg_expr ? lvalue_p (arg_expr)
22814 /* try_one_overload doesn't provide an arg_expr, but
22815 functions are always lvalues. */
22816 : TREE_CODE (*arg) == FUNCTION_TYPE))
22817 *arg = build_reference_type (*arg);
22819 /* [temp.deduct.call]
22821 If P is a cv-qualified type, the top level cv-qualifiers
22822 of P's type are ignored for type deduction. If P is a
22823 reference type, the type referred to by P is used for
22824 type deduction. */
22825 *parm = TYPE_MAIN_VARIANT (*parm);
22826 if (TYPE_REF_P (*parm))
22828 *parm = TREE_TYPE (*parm);
22829 result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
22832 return result;
22835 /* Subroutine of fn_type_unification. PARM is a function parameter of a
22836 template which doesn't contain any deducible template parameters; check if
22837 ARG is a suitable match for it. STRICT, FLAGS and EXPLAIN_P are as in
22838 unify_one_argument. */
22840 static int
22841 check_non_deducible_conversion (tree parm, tree arg, unification_kind_t strict,
22842 int flags, struct conversion **conv_p,
22843 bool explain_p)
22845 tree type;
22847 if (!TYPE_P (arg))
22848 type = TREE_TYPE (arg);
22849 else
22850 type = arg;
22852 if (same_type_p (parm, type))
22853 return unify_success (explain_p);
22855 tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
22856 if (strict == DEDUCE_CONV)
22858 if (can_convert_arg (type, parm, NULL_TREE, flags, complain))
22859 return unify_success (explain_p);
22861 else if (strict == DEDUCE_CALL)
22863 bool ok = false;
22864 tree conv_arg = TYPE_P (arg) ? NULL_TREE : arg;
22865 if (conv_p)
22866 /* Avoid recalculating this in add_function_candidate. */
22867 ok = (*conv_p
22868 = good_conversion (parm, type, conv_arg, flags, complain));
22869 else
22870 ok = can_convert_arg (parm, type, conv_arg, flags, complain);
22871 if (ok)
22872 return unify_success (explain_p);
22875 if (strict == DEDUCE_EXACT)
22876 return unify_type_mismatch (explain_p, parm, arg);
22877 else
22878 return unify_arg_conversion (explain_p, parm, type, arg);
22881 static bool uses_deducible_template_parms (tree type);
22883 /* Returns true iff the expression EXPR is one from which a template
22884 argument can be deduced. In other words, if it's an undecorated
22885 use of a template non-type parameter. */
22887 static bool
22888 deducible_expression (tree expr)
22890 /* Strip implicit conversions and implicit INDIRECT_REFs. */
22891 while (CONVERT_EXPR_P (expr)
22892 || TREE_CODE (expr) == VIEW_CONVERT_EXPR
22893 || REFERENCE_REF_P (expr))
22894 expr = TREE_OPERAND (expr, 0);
22895 return (TREE_CODE (expr) == TEMPLATE_PARM_INDEX);
22898 /* Returns true iff the array domain DOMAIN uses a template parameter in a
22899 deducible way; that is, if it has a max value of <PARM> - 1. */
22901 static bool
22902 deducible_array_bound (tree domain)
22904 if (domain == NULL_TREE)
22905 return false;
22907 tree max = TYPE_MAX_VALUE (domain);
22908 if (TREE_CODE (max) != MINUS_EXPR)
22909 return false;
22911 return deducible_expression (TREE_OPERAND (max, 0));
22914 /* Returns true iff the template arguments ARGS use a template parameter
22915 in a deducible way. */
22917 static bool
22918 deducible_template_args (tree args)
22920 for (tree elt : tree_vec_range (args))
22922 bool deducible;
22923 if (ARGUMENT_PACK_P (elt))
22924 deducible = deducible_template_args (ARGUMENT_PACK_ARGS (elt));
22925 else
22927 if (PACK_EXPANSION_P (elt))
22928 elt = PACK_EXPANSION_PATTERN (elt);
22929 if (TREE_CODE (elt) == TEMPLATE_TEMPLATE_PARM)
22930 deducible = true;
22931 else if (TYPE_P (elt))
22932 deducible = uses_deducible_template_parms (elt);
22933 else
22934 deducible = deducible_expression (elt);
22936 if (deducible)
22937 return true;
22939 return false;
22942 /* Returns true iff TYPE contains any deducible references to template
22943 parameters, as per 14.8.2.5. */
22945 static bool
22946 uses_deducible_template_parms (tree type)
22948 if (PACK_EXPANSION_P (type))
22949 type = PACK_EXPANSION_PATTERN (type);
22951 /* T
22952 cv-list T
22953 TT<T>
22954 TT<i>
22955 TT<> */
22956 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
22957 || TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
22958 return true;
22960 /* T*
22962 T&& */
22963 if (INDIRECT_TYPE_P (type))
22964 return uses_deducible_template_parms (TREE_TYPE (type));
22966 /* T[integer-constant ]
22967 type [i] */
22968 if (TREE_CODE (type) == ARRAY_TYPE)
22969 return (uses_deducible_template_parms (TREE_TYPE (type))
22970 || deducible_array_bound (TYPE_DOMAIN (type)));
22972 /* T type ::*
22973 type T::*
22974 T T::*
22975 T (type ::*)()
22976 type (T::*)()
22977 type (type ::*)(T)
22978 type (T::*)(T)
22979 T (type ::*)(T)
22980 T (T::*)()
22981 T (T::*)(T) */
22982 if (TYPE_PTRMEM_P (type))
22983 return (uses_deducible_template_parms (TYPE_PTRMEM_CLASS_TYPE (type))
22984 || (uses_deducible_template_parms
22985 (TYPE_PTRMEM_POINTED_TO_TYPE (type))));
22987 /* template-name <T> (where template-name refers to a class template)
22988 template-name <i> (where template-name refers to a class template) */
22989 if (CLASS_TYPE_P (type)
22990 && CLASSTYPE_TEMPLATE_INFO (type)
22991 && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type)))
22992 return deducible_template_args (INNERMOST_TEMPLATE_ARGS
22993 (CLASSTYPE_TI_ARGS (type)));
22995 /* type (T)
22997 T(T) */
22998 if (FUNC_OR_METHOD_TYPE_P (type))
23000 if (uses_deducible_template_parms (TREE_TYPE (type)))
23001 return true;
23002 tree parm = TYPE_ARG_TYPES (type);
23003 if (TREE_CODE (type) == METHOD_TYPE)
23004 parm = TREE_CHAIN (parm);
23005 for (; parm; parm = TREE_CHAIN (parm))
23006 if (uses_deducible_template_parms (TREE_VALUE (parm)))
23007 return true;
23008 if (flag_noexcept_type
23009 && TYPE_RAISES_EXCEPTIONS (type)
23010 && TREE_PURPOSE (TYPE_RAISES_EXCEPTIONS (type))
23011 && deducible_expression (TREE_PURPOSE (TYPE_RAISES_EXCEPTIONS (type))))
23012 return true;
23015 return false;
23018 /* Subroutine of type_unification_real and unify_pack_expansion to
23019 handle unification of a single P/A pair. Parameters are as
23020 for those functions. */
23022 static int
23023 unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
23024 int subr, unification_kind_t strict,
23025 bool explain_p)
23027 tree arg_expr = NULL_TREE;
23028 int arg_strict;
23030 if (arg == error_mark_node || parm == error_mark_node)
23031 return unify_invalid (explain_p);
23032 if (arg == unknown_type_node)
23033 /* We can't deduce anything from this, but we might get all the
23034 template args from other function args. */
23035 return unify_success (explain_p);
23037 /* Implicit conversions (Clause 4) will be performed on a function
23038 argument to convert it to the type of the corresponding function
23039 parameter if the parameter type contains no template-parameters that
23040 participate in template argument deduction. */
23041 if (strict != DEDUCE_EXACT
23042 && TYPE_P (parm) && !uses_deducible_template_parms (parm))
23043 /* For function parameters with no deducible template parameters,
23044 just return. We'll check non-dependent conversions later. */
23045 return unify_success (explain_p);
23047 switch (strict)
23049 case DEDUCE_CALL:
23050 arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
23051 | UNIFY_ALLOW_MORE_CV_QUAL
23052 | UNIFY_ALLOW_DERIVED);
23053 break;
23055 case DEDUCE_CONV:
23056 arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
23057 break;
23059 case DEDUCE_EXACT:
23060 arg_strict = UNIFY_ALLOW_NONE;
23061 break;
23063 default:
23064 gcc_unreachable ();
23067 /* We only do these transformations if this is the top-level
23068 parameter_type_list in a call or declaration matching; in other
23069 situations (nested function declarators, template argument lists) we
23070 won't be comparing a type to an expression, and we don't do any type
23071 adjustments. */
23072 if (!subr)
23074 if (!TYPE_P (arg))
23076 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
23077 if (type_unknown_p (arg))
23079 /* [temp.deduct.type] A template-argument can be
23080 deduced from a pointer to function or pointer
23081 to member function argument if the set of
23082 overloaded functions does not contain function
23083 templates and at most one of a set of
23084 overloaded functions provides a unique
23085 match. */
23086 resolve_overloaded_unification (tparms, targs, parm,
23087 arg, strict,
23088 arg_strict, explain_p);
23089 /* If a unique match was not found, this is a
23090 non-deduced context, so we still succeed. */
23091 return unify_success (explain_p);
23094 arg_expr = arg;
23095 arg = unlowered_expr_type (arg);
23096 if (arg == error_mark_node)
23097 return unify_invalid (explain_p);
23100 arg_strict |= maybe_adjust_types_for_deduction (tparms, strict,
23101 &parm, &arg, arg_expr);
23103 else
23104 if ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
23105 != (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL))
23106 return unify_template_argument_mismatch (explain_p, parm, arg);
23108 /* For deduction from an init-list we need the actual list. */
23109 if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
23110 arg = arg_expr;
23111 return unify (tparms, targs, parm, arg, arg_strict, explain_p);
23114 /* for_each_template_parm callback that always returns 0. */
23116 static int
23117 zero_r (tree, void *)
23119 return 0;
23122 /* for_each_template_parm any_fn callback to handle deduction of a template
23123 type argument from the type of an array bound. */
23125 static int
23126 array_deduction_r (tree t, void *data)
23128 tree_pair_p d = (tree_pair_p)data;
23129 tree &tparms = d->purpose;
23130 tree &targs = d->value;
23132 if (TREE_CODE (t) == ARRAY_TYPE)
23133 if (tree dom = TYPE_DOMAIN (t))
23134 if (tree max = TYPE_MAX_VALUE (dom))
23136 if (TREE_CODE (max) == MINUS_EXPR)
23137 max = TREE_OPERAND (max, 0);
23138 if (TREE_CODE (max) == TEMPLATE_PARM_INDEX)
23139 unify (tparms, targs, TREE_TYPE (max), size_type_node,
23140 UNIFY_ALLOW_NONE, /*explain*/false);
23143 /* Keep walking. */
23144 return 0;
23147 /* Try to deduce any not-yet-deduced template type arguments from the type of
23148 an array bound. This is handled separately from unify because 14.8.2.5 says
23149 "The type of a type parameter is only deduced from an array bound if it is
23150 not otherwise deduced." */
23152 static void
23153 try_array_deduction (tree tparms, tree targs, tree parm)
23155 tree_pair_s data = { tparms, targs };
23156 hash_set<tree> visited;
23157 for_each_template_parm (parm, zero_r, &data, &visited,
23158 /*nondeduced*/false, array_deduction_r);
23161 /* Most parms like fn_type_unification.
23163 If SUBR is 1, we're being called recursively (to unify the
23164 arguments of a function or method parameter of a function
23165 template).
23167 CHECKS is a pointer to a vector of access checks encountered while
23168 substituting default template arguments. */
23170 static int
23171 type_unification_real (tree tparms,
23172 tree full_targs,
23173 tree xparms,
23174 const tree *xargs,
23175 unsigned int xnargs,
23176 int subr,
23177 unification_kind_t strict,
23178 vec<deferred_access_check, va_gc> **checks,
23179 bool explain_p)
23181 tree parm, arg;
23182 int i;
23183 int ntparms = TREE_VEC_LENGTH (tparms);
23184 int saw_undeduced = 0;
23185 tree parms;
23186 const tree *args;
23187 unsigned int nargs;
23188 unsigned int ia;
23190 gcc_assert (TREE_CODE (tparms) == TREE_VEC);
23191 gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
23192 gcc_assert (ntparms > 0);
23194 tree targs = INNERMOST_TEMPLATE_ARGS (full_targs);
23196 /* Reset the number of non-defaulted template arguments contained
23197 in TARGS. */
23198 NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
23200 again:
23201 parms = xparms;
23202 args = xargs;
23203 nargs = xnargs;
23205 /* Only fn_type_unification cares about terminal void. */
23206 if (nargs && args[nargs-1] == void_type_node)
23207 --nargs;
23209 ia = 0;
23210 while (parms && parms != void_list_node
23211 && ia < nargs)
23213 parm = TREE_VALUE (parms);
23215 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
23216 && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
23217 /* For a function parameter pack that occurs at the end of the
23218 parameter-declaration-list, the type A of each remaining
23219 argument of the call is compared with the type P of the
23220 declarator-id of the function parameter pack. */
23221 break;
23223 parms = TREE_CHAIN (parms);
23225 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
23226 /* For a function parameter pack that does not occur at the
23227 end of the parameter-declaration-list, the type of the
23228 parameter pack is a non-deduced context. */
23229 continue;
23231 arg = args[ia];
23232 ++ia;
23234 if (unify_one_argument (tparms, full_targs, parm, arg, subr, strict,
23235 explain_p))
23236 return 1;
23239 if (parms
23240 && parms != void_list_node
23241 && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
23243 /* Unify the remaining arguments with the pack expansion type. */
23244 tree argvec;
23245 tree parmvec = make_tree_vec (1);
23247 /* Allocate a TREE_VEC and copy in all of the arguments */
23248 argvec = make_tree_vec (nargs - ia);
23249 for (i = 0; ia < nargs; ++ia, ++i)
23250 TREE_VEC_ELT (argvec, i) = args[ia];
23252 /* Copy the parameter into parmvec. */
23253 TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
23254 if (unify_pack_expansion (tparms, full_targs, parmvec, argvec, strict,
23255 /*subr=*/subr, explain_p))
23256 return 1;
23258 /* Advance to the end of the list of parameters. */
23259 parms = TREE_CHAIN (parms);
23262 /* Fail if we've reached the end of the parm list, and more args
23263 are present, and the parm list isn't variadic. */
23264 if (ia < nargs && parms == void_list_node)
23265 return unify_too_many_arguments (explain_p, nargs, ia);
23266 /* Fail if parms are left and they don't have default values and
23267 they aren't all deduced as empty packs (c++/57397). This is
23268 consistent with sufficient_parms_p. */
23269 if (parms && parms != void_list_node
23270 && TREE_PURPOSE (parms) == NULL_TREE)
23272 unsigned int count = nargs;
23273 tree p = parms;
23274 bool type_pack_p;
23277 type_pack_p = TREE_CODE (TREE_VALUE (p)) == TYPE_PACK_EXPANSION;
23278 if (!type_pack_p)
23279 count++;
23280 p = TREE_CHAIN (p);
23282 while (p && p != void_list_node);
23283 if (count != nargs)
23284 return unify_too_few_arguments (explain_p, ia, count,
23285 type_pack_p);
23288 if (!subr)
23290 tsubst_flags_t complain = (explain_p
23291 ? tf_warning_or_error
23292 : tf_none);
23293 bool tried_array_deduction = (cxx_dialect < cxx17);
23295 for (i = 0; i < ntparms; i++)
23297 tree targ = TREE_VEC_ELT (targs, i);
23298 tree tparm = TREE_VEC_ELT (tparms, i);
23300 /* Clear the "incomplete" flags on all argument packs now so that
23301 substituting them into later default arguments works. */
23302 if (targ && ARGUMENT_PACK_P (targ))
23304 ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
23305 ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
23308 if (targ || tparm == error_mark_node)
23309 continue;
23310 tparm = TREE_VALUE (tparm);
23312 if (TREE_CODE (tparm) == TYPE_DECL
23313 && !tried_array_deduction)
23315 try_array_deduction (tparms, targs, xparms);
23316 tried_array_deduction = true;
23317 if (TREE_VEC_ELT (targs, i))
23318 continue;
23321 /* If this is an undeduced nontype parameter that depends on
23322 a type parameter, try another pass; its type may have been
23323 deduced from a later argument than the one from which
23324 this parameter can be deduced. */
23325 if (TREE_CODE (tparm) == PARM_DECL
23326 && !is_auto (TREE_TYPE (tparm))
23327 && uses_template_parms (TREE_TYPE (tparm))
23328 && saw_undeduced < 2)
23330 saw_undeduced = 1;
23331 continue;
23334 /* Core issue #226 (C++0x) [temp.deduct]:
23336 If a template argument has not been deduced, its
23337 default template argument, if any, is used.
23339 When we are in C++98 mode, TREE_PURPOSE will either
23340 be NULL_TREE or ERROR_MARK_NODE, so we do not need
23341 to explicitly check cxx_dialect here. */
23342 if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
23343 /* OK, there is a default argument. Wait until after the
23344 conversion check to do substitution. */
23345 continue;
23347 /* If the type parameter is a parameter pack, then it will
23348 be deduced to an empty parameter pack. */
23349 if (template_parameter_pack_p (tparm))
23351 tree arg;
23353 if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
23355 arg = make_node (NONTYPE_ARGUMENT_PACK);
23356 TREE_CONSTANT (arg) = 1;
23358 else
23359 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
23361 ARGUMENT_PACK_ARGS (arg) = make_tree_vec (0);
23363 TREE_VEC_ELT (targs, i) = arg;
23364 continue;
23367 return unify_parameter_deduction_failure (explain_p, tparm);
23370 /* During partial ordering, we deduce dependent template args. */
23371 bool any_dependent_targs = false;
23373 /* Now substitute into the default template arguments. */
23374 for (i = 0; i < ntparms; i++)
23376 tree targ = TREE_VEC_ELT (targs, i);
23377 tree tparm = TREE_VEC_ELT (tparms, i);
23379 if (targ)
23381 if (!any_dependent_targs && dependent_template_arg_p (targ))
23382 any_dependent_targs = true;
23383 continue;
23385 if (tparm == error_mark_node)
23386 continue;
23388 tree parm = TREE_VALUE (tparm);
23389 tree arg = TREE_PURPOSE (tparm);
23390 reopen_deferring_access_checks (*checks);
23391 location_t save_loc = input_location;
23392 if (DECL_P (parm))
23393 input_location = DECL_SOURCE_LOCATION (parm);
23395 if (saw_undeduced == 1
23396 && TREE_CODE (parm) == PARM_DECL
23397 && !is_auto (TREE_TYPE (parm))
23398 && uses_template_parms (TREE_TYPE (parm)))
23400 /* The type of this non-type parameter depends on undeduced
23401 parameters. Don't try to use its default argument yet,
23402 since we might deduce an argument for it on the next pass,
23403 but do check whether the arguments we already have cause
23404 substitution failure, so that that happens before we try
23405 later default arguments (78489). */
23406 ++processing_template_decl;
23407 tree type = tsubst (TREE_TYPE (parm), full_targs, complain,
23408 NULL_TREE);
23409 --processing_template_decl;
23410 if (type == error_mark_node)
23411 arg = error_mark_node;
23412 else
23413 arg = NULL_TREE;
23415 else
23417 /* Even if the call is happening in template context, getting
23418 here means it's non-dependent, and a default argument is
23419 considered a separate definition under [temp.decls], so we can
23420 do this substitution without processing_template_decl. This
23421 is important if the default argument contains something that
23422 might be instantiation-dependent like access (87480). */
23423 processing_template_decl_sentinel s (!any_dependent_targs);
23424 tree substed = NULL_TREE;
23425 if (saw_undeduced == 1 && !any_dependent_targs)
23427 /* First instatiate in template context, in case we still
23428 depend on undeduced template parameters. */
23429 ++processing_template_decl;
23430 substed = tsubst_template_arg (arg, full_targs, complain,
23431 NULL_TREE);
23432 --processing_template_decl;
23433 if (substed != error_mark_node
23434 && !uses_template_parms (substed))
23435 /* We replaced all the tparms, substitute again out of
23436 template context. */
23437 substed = NULL_TREE;
23439 if (!substed)
23440 substed = tsubst_template_arg (arg, full_targs, complain,
23441 NULL_TREE);
23443 if (!uses_template_parms (substed))
23444 arg = convert_template_argument (parm, substed, full_targs,
23445 complain, i, NULL_TREE);
23446 else if (saw_undeduced == 1)
23447 arg = NULL_TREE;
23448 else if (!any_dependent_targs)
23449 arg = error_mark_node;
23452 input_location = save_loc;
23453 *checks = get_deferred_access_checks ();
23454 pop_deferring_access_checks ();
23456 if (arg == error_mark_node)
23457 return 1;
23458 else if (arg)
23460 TREE_VEC_ELT (targs, i) = arg;
23461 /* The position of the first default template argument,
23462 is also the number of non-defaulted arguments in TARGS.
23463 Record that. */
23464 if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
23465 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
23469 if (saw_undeduced++ == 1)
23470 goto again;
23473 if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
23474 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
23476 return unify_success (explain_p);
23479 /* Subroutine of type_unification_real. Args are like the variables
23480 at the call site. ARG is an overloaded function (or template-id);
23481 we try deducing template args from each of the overloads, and if
23482 only one succeeds, we go with that. Modifies TARGS and returns
23483 true on success. */
23485 static bool
23486 resolve_overloaded_unification (tree tparms,
23487 tree targs,
23488 tree parm,
23489 tree arg,
23490 unification_kind_t strict,
23491 int sub_strict,
23492 bool explain_p)
23494 tree tempargs = copy_node (targs);
23495 int good = 0;
23496 tree goodfn = NULL_TREE;
23497 bool addr_p;
23499 if (TREE_CODE (arg) == ADDR_EXPR)
23501 arg = TREE_OPERAND (arg, 0);
23502 addr_p = true;
23504 else
23505 addr_p = false;
23507 if (TREE_CODE (arg) == COMPONENT_REF)
23508 /* Handle `&x' where `x' is some static or non-static member
23509 function name. */
23510 arg = TREE_OPERAND (arg, 1);
23512 if (TREE_CODE (arg) == OFFSET_REF)
23513 arg = TREE_OPERAND (arg, 1);
23515 /* Strip baselink information. */
23516 if (BASELINK_P (arg))
23517 arg = BASELINK_FUNCTIONS (arg);
23519 if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
23521 /* If we got some explicit template args, we need to plug them into
23522 the affected templates before we try to unify, in case the
23523 explicit args will completely resolve the templates in question. */
23525 int ok = 0;
23526 tree expl_subargs = TREE_OPERAND (arg, 1);
23527 arg = TREE_OPERAND (arg, 0);
23529 for (lkp_iterator iter (arg); iter; ++iter)
23531 tree fn = *iter;
23532 tree subargs, elem;
23534 if (TREE_CODE (fn) != TEMPLATE_DECL)
23535 continue;
23537 subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
23538 expl_subargs, NULL_TREE, tf_none);
23539 if (subargs != error_mark_node
23540 && !any_dependent_template_arguments_p (subargs))
23542 fn = instantiate_template (fn, subargs, tf_none);
23543 if (!constraints_satisfied_p (fn))
23544 continue;
23545 if (undeduced_auto_decl (fn))
23547 /* Instantiate the function to deduce its return type. */
23548 ++function_depth;
23549 instantiate_decl (fn, /*defer*/false, /*class*/false);
23550 --function_depth;
23553 if (flag_noexcept_type)
23554 maybe_instantiate_noexcept (fn, tf_none);
23556 elem = TREE_TYPE (fn);
23557 if (try_one_overload (tparms, targs, tempargs, parm,
23558 elem, strict, sub_strict, addr_p, explain_p)
23559 && (!goodfn || !same_type_p (goodfn, elem)))
23561 goodfn = elem;
23562 ++good;
23565 else if (subargs)
23566 ++ok;
23568 /* If no templates (or more than one) are fully resolved by the
23569 explicit arguments, this template-id is a non-deduced context; it
23570 could still be OK if we deduce all template arguments for the
23571 enclosing call through other arguments. */
23572 if (good != 1)
23573 good = ok;
23575 else if (!OVL_P (arg))
23576 /* If ARG is, for example, "(0, &f)" then its type will be unknown
23577 -- but the deduction does not succeed because the expression is
23578 not just the function on its own. */
23579 return false;
23580 else
23581 for (lkp_iterator iter (arg); iter; ++iter)
23583 tree fn = *iter;
23584 if (try_one_overload (tparms, targs, tempargs, parm, TREE_TYPE (fn),
23585 strict, sub_strict, addr_p, explain_p)
23586 && (!goodfn || !decls_match (goodfn, fn)))
23588 goodfn = fn;
23589 ++good;
23593 /* [temp.deduct.type] A template-argument can be deduced from a pointer
23594 to function or pointer to member function argument if the set of
23595 overloaded functions does not contain function templates and at most
23596 one of a set of overloaded functions provides a unique match.
23598 So if we found multiple possibilities, we return success but don't
23599 deduce anything. */
23601 if (good == 1)
23603 int i = TREE_VEC_LENGTH (targs);
23604 for (; i--; )
23605 if (TREE_VEC_ELT (tempargs, i))
23607 tree old = TREE_VEC_ELT (targs, i);
23608 tree new_ = TREE_VEC_ELT (tempargs, i);
23609 if (new_ && old && ARGUMENT_PACK_P (old)
23610 && ARGUMENT_PACK_EXPLICIT_ARGS (old))
23611 /* Don't forget explicit template arguments in a pack. */
23612 ARGUMENT_PACK_EXPLICIT_ARGS (new_)
23613 = ARGUMENT_PACK_EXPLICIT_ARGS (old);
23614 TREE_VEC_ELT (targs, i) = new_;
23617 if (good)
23618 return true;
23620 return false;
23623 /* Core DR 115: In contexts where deduction is done and fails, or in
23624 contexts where deduction is not done, if a template argument list is
23625 specified and it, along with any default template arguments, identifies
23626 a single function template specialization, then the template-id is an
23627 lvalue for the function template specialization. */
23629 tree
23630 resolve_nondeduced_context (tree orig_expr, tsubst_flags_t complain)
23632 tree expr, offset, baselink;
23633 bool addr;
23635 if (!type_unknown_p (orig_expr))
23636 return orig_expr;
23638 expr = orig_expr;
23639 addr = false;
23640 offset = NULL_TREE;
23641 baselink = NULL_TREE;
23643 if (TREE_CODE (expr) == ADDR_EXPR)
23645 expr = TREE_OPERAND (expr, 0);
23646 addr = true;
23648 if (TREE_CODE (expr) == OFFSET_REF)
23650 offset = expr;
23651 expr = TREE_OPERAND (expr, 1);
23653 if (BASELINK_P (expr))
23655 baselink = expr;
23656 expr = BASELINK_FUNCTIONS (expr);
23659 if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
23661 int good = 0;
23662 tree goodfn = NULL_TREE;
23664 /* If we got some explicit template args, we need to plug them into
23665 the affected templates before we try to unify, in case the
23666 explicit args will completely resolve the templates in question. */
23668 tree expl_subargs = TREE_OPERAND (expr, 1);
23669 tree arg = TREE_OPERAND (expr, 0);
23670 tree badfn = NULL_TREE;
23671 tree badargs = NULL_TREE;
23673 for (lkp_iterator iter (arg); iter; ++iter)
23675 tree fn = *iter;
23676 tree subargs, elem;
23678 if (TREE_CODE (fn) != TEMPLATE_DECL)
23679 continue;
23681 subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
23682 expl_subargs, NULL_TREE, tf_none);
23683 if (subargs != error_mark_node
23684 && !any_dependent_template_arguments_p (subargs))
23686 elem = instantiate_template (fn, subargs, tf_none);
23687 if (elem == error_mark_node)
23689 badfn = fn;
23690 badargs = subargs;
23692 else if (elem && (!goodfn || !decls_match (goodfn, elem))
23693 && constraints_satisfied_p (elem))
23695 goodfn = elem;
23696 ++good;
23700 if (good == 1)
23702 mark_used (goodfn);
23703 expr = goodfn;
23704 if (baselink)
23705 expr = build_baselink (BASELINK_BINFO (baselink),
23706 BASELINK_ACCESS_BINFO (baselink),
23707 expr, BASELINK_OPTYPE (baselink));
23708 if (offset)
23710 tree base
23711 = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
23712 expr = build_offset_ref (base, expr, addr, complain);
23714 if (addr)
23715 expr = cp_build_addr_expr (expr, complain);
23716 return expr;
23718 else if (good == 0 && badargs && (complain & tf_error))
23719 /* There were no good options and at least one bad one, so let the
23720 user know what the problem is. */
23721 instantiate_template (badfn, badargs, complain);
23723 return orig_expr;
23726 /* As above, but error out if the expression remains overloaded. */
23728 tree
23729 resolve_nondeduced_context_or_error (tree exp, tsubst_flags_t complain)
23731 exp = resolve_nondeduced_context (exp, complain);
23732 if (type_unknown_p (exp))
23734 if (complain & tf_error)
23735 cxx_incomplete_type_error (exp, TREE_TYPE (exp));
23736 return error_mark_node;
23738 return exp;
23741 /* Subroutine of resolve_overloaded_unification; does deduction for a single
23742 overload. Fills TARGS with any deduced arguments, or error_mark_node if
23743 different overloads deduce different arguments for a given parm.
23744 ADDR_P is true if the expression for which deduction is being
23745 performed was of the form "& fn" rather than simply "fn".
23747 Returns 1 on success. */
23749 static int
23750 try_one_overload (tree tparms,
23751 tree orig_targs,
23752 tree targs,
23753 tree parm,
23754 tree arg,
23755 unification_kind_t strict,
23756 int sub_strict,
23757 bool addr_p,
23758 bool explain_p)
23760 int nargs;
23761 tree tempargs;
23762 int i;
23764 if (arg == error_mark_node)
23765 return 0;
23767 /* [temp.deduct.type] A template-argument can be deduced from a pointer
23768 to function or pointer to member function argument if the set of
23769 overloaded functions does not contain function templates and at most
23770 one of a set of overloaded functions provides a unique match.
23772 So if this is a template, just return success. */
23774 if (uses_template_parms (arg))
23775 return 1;
23777 if (TREE_CODE (arg) == METHOD_TYPE)
23778 arg = build_ptrmemfunc_type (build_pointer_type (arg));
23779 else if (addr_p)
23780 arg = build_pointer_type (arg);
23782 sub_strict |= maybe_adjust_types_for_deduction (tparms, strict,
23783 &parm, &arg, NULL_TREE);
23785 /* We don't copy orig_targs for this because if we have already deduced
23786 some template args from previous args, unify would complain when we
23787 try to deduce a template parameter for the same argument, even though
23788 there isn't really a conflict. */
23789 nargs = TREE_VEC_LENGTH (targs);
23790 tempargs = make_tree_vec (nargs);
23792 if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
23793 return 0;
23795 /* First make sure we didn't deduce anything that conflicts with
23796 explicitly specified args. */
23797 for (i = nargs; i--; )
23799 tree elt = TREE_VEC_ELT (tempargs, i);
23800 tree oldelt = TREE_VEC_ELT (orig_targs, i);
23802 if (!elt)
23803 /*NOP*/;
23804 else if (uses_template_parms (elt))
23805 /* Since we're unifying against ourselves, we will fill in
23806 template args used in the function parm list with our own
23807 template parms. Discard them. */
23808 TREE_VEC_ELT (tempargs, i) = NULL_TREE;
23809 else if (oldelt && ARGUMENT_PACK_P (oldelt))
23811 /* Check that the argument at each index of the deduced argument pack
23812 is equivalent to the corresponding explicitly specified argument.
23813 We may have deduced more arguments than were explicitly specified,
23814 and that's OK. */
23816 /* We used to assert ARGUMENT_PACK_INCOMPLETE_P (oldelt) here, but
23817 that's wrong if we deduce the same argument pack from multiple
23818 function arguments: it's only incomplete the first time. */
23820 tree explicit_pack = ARGUMENT_PACK_ARGS (oldelt);
23821 tree deduced_pack = ARGUMENT_PACK_ARGS (elt);
23823 if (TREE_VEC_LENGTH (deduced_pack)
23824 < TREE_VEC_LENGTH (explicit_pack))
23825 return 0;
23827 for (int j = 0; j < TREE_VEC_LENGTH (explicit_pack); j++)
23828 if (!template_args_equal (TREE_VEC_ELT (explicit_pack, j),
23829 TREE_VEC_ELT (deduced_pack, j)))
23830 return 0;
23832 else if (oldelt && !template_args_equal (oldelt, elt))
23833 return 0;
23836 for (i = nargs; i--; )
23838 tree elt = TREE_VEC_ELT (tempargs, i);
23840 if (elt)
23841 TREE_VEC_ELT (targs, i) = elt;
23844 return 1;
23847 /* PARM is a template class (perhaps with unbound template
23848 parameters). ARG is a fully instantiated type. If ARG can be
23849 bound to PARM, return ARG, otherwise return NULL_TREE. TPARMS and
23850 TARGS are as for unify. */
23852 static tree
23853 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
23854 bool explain_p)
23856 if (!CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
23857 return NULL_TREE;
23858 else if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23859 /* Matches anything. */;
23860 else if (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
23861 != most_general_template (CLASSTYPE_TI_TEMPLATE (parm)))
23862 return NULL_TREE;
23864 /* We need to make a new template argument vector for the call to
23865 unify. If we used TARGS, we'd clutter it up with the result of
23866 the attempted unification, even if this class didn't work out.
23867 We also don't want to commit ourselves to all the unifications
23868 we've already done, since unification is supposed to be done on
23869 an argument-by-argument basis. In other words, consider the
23870 following pathological case:
23872 template <int I, int J, int K>
23873 struct S {};
23875 template <int I, int J>
23876 struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
23878 template <int I, int J, int K>
23879 void f(S<I, J, K>, S<I, I, I>);
23881 void g() {
23882 S<0, 0, 0> s0;
23883 S<0, 1, 2> s2;
23885 f(s0, s2);
23888 Now, by the time we consider the unification involving `s2', we
23889 already know that we must have `f<0, 0, 0>'. But, even though
23890 `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
23891 because there are two ways to unify base classes of S<0, 1, 2>
23892 with S<I, I, I>. If we kept the already deduced knowledge, we
23893 would reject the possibility I=1. */
23894 targs = copy_template_args (targs);
23895 for (tree& targ : tree_vec_range (INNERMOST_TEMPLATE_ARGS (targs)))
23896 targ = NULL_TREE;
23898 int err;
23899 if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23900 err = unify_bound_ttp_args (tparms, targs, parm, arg, explain_p);
23901 else
23902 err = unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
23903 CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE, explain_p);
23905 return err ? NULL_TREE : arg;
23908 /* Given a template type PARM and a class type ARG, find the unique
23909 base type in ARG that is an instance of PARM. We do not examine
23910 ARG itself; only its base-classes. If there is not exactly one
23911 appropriate base class, return NULL_TREE. PARM may be the type of
23912 a partial specialization, as well as a plain template type. Used
23913 by unify. */
23915 static enum template_base_result
23916 get_template_base (tree tparms, tree targs, tree parm, tree arg,
23917 bool explain_p, tree *result)
23919 tree rval = NULL_TREE;
23920 tree binfo;
23922 gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
23924 binfo = TYPE_BINFO (complete_type (arg));
23925 if (!binfo)
23927 /* The type could not be completed. */
23928 *result = NULL_TREE;
23929 return tbr_incomplete_type;
23932 /* Walk in inheritance graph order. The search order is not
23933 important, and this avoids multiple walks of virtual bases. */
23934 for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
23936 tree r = try_class_unification (tparms, targs, parm,
23937 BINFO_TYPE (binfo), explain_p);
23939 if (r)
23941 /* If there is more than one satisfactory baseclass, then:
23943 [temp.deduct.call]
23945 If they yield more than one possible deduced A, the type
23946 deduction fails.
23948 applies. */
23949 if (rval && !same_type_p (r, rval))
23951 /* [temp.deduct.call]/4.3: If there is a class C that is a
23952 (direct or indirect) base class of D and derived (directly or
23953 indirectly) from a class B and that would be a valid deduced
23954 A, the deduced A cannot be B or pointer to B, respectively. */
23955 if (DERIVED_FROM_P (r, rval))
23956 /* Ignore r. */
23957 continue;
23958 else if (DERIVED_FROM_P (rval, r))
23959 /* Ignore rval. */;
23960 else
23962 *result = NULL_TREE;
23963 return tbr_ambiguous_baseclass;
23967 rval = r;
23971 *result = rval;
23972 return tbr_success;
23975 /* Returns the level of DECL, which declares a template parameter. */
23977 static int
23978 template_decl_level (tree decl)
23980 switch (TREE_CODE (decl))
23982 case TYPE_DECL:
23983 case TEMPLATE_DECL:
23984 return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
23986 case PARM_DECL:
23987 return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
23989 default:
23990 gcc_unreachable ();
23992 return 0;
23995 /* Decide whether ARG can be unified with PARM, considering only the
23996 cv-qualifiers of each type, given STRICT as documented for unify.
23997 Returns nonzero iff the unification is OK on that basis. */
23999 static int
24000 check_cv_quals_for_unify (int strict, tree arg, tree parm)
24002 int arg_quals = cp_type_quals (arg);
24003 int parm_quals = cp_type_quals (parm);
24005 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
24006 && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
24008 /* Although a CVR qualifier is ignored when being applied to a
24009 substituted template parameter ([8.3.2]/1 for example), that
24010 does not allow us to unify "const T" with "int&" because both
24011 types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
24012 It is ok when we're allowing additional CV qualifiers
24013 at the outer level [14.8.2.1]/3,1st bullet. */
24014 if ((TYPE_REF_P (arg)
24015 || FUNC_OR_METHOD_TYPE_P (arg))
24016 && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
24017 return 0;
24019 if ((!INDIRECT_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
24020 && (parm_quals & TYPE_QUAL_RESTRICT))
24021 return 0;
24024 if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
24025 && (arg_quals & parm_quals) != parm_quals)
24026 return 0;
24028 if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
24029 && (parm_quals & arg_quals) != arg_quals)
24030 return 0;
24032 return 1;
24035 /* Determines the LEVEL and INDEX for the template parameter PARM. */
24036 void
24037 template_parm_level_and_index (tree parm, int* level, int* index)
24039 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
24040 || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
24041 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
24043 *index = TEMPLATE_TYPE_IDX (parm);
24044 *level = TEMPLATE_TYPE_LEVEL (parm);
24046 else
24048 *index = TEMPLATE_PARM_IDX (parm);
24049 *level = TEMPLATE_PARM_LEVEL (parm);
24053 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP) \
24054 do { \
24055 if (unify (TP, TA, P, A, S, EP)) \
24056 return 1; \
24057 } while (0)
24059 /* Unifies the remaining arguments in PACKED_ARGS with the pack
24060 expansion at the end of PACKED_PARMS. Returns 0 if the type
24061 deduction succeeds, 1 otherwise. STRICT is the same as in
24062 fn_type_unification. CALL_ARGS_P is true iff PACKED_ARGS is actually a
24063 function call argument list. We'll need to adjust the arguments to make them
24064 types. SUBR tells us if this is from a recursive call to
24065 type_unification_real, or for comparing two template argument
24066 lists. */
24068 static int
24069 unify_pack_expansion (tree tparms, tree targs, tree packed_parms,
24070 tree packed_args, unification_kind_t strict,
24071 bool subr, bool explain_p)
24073 tree parm
24074 = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
24075 tree pattern = PACK_EXPANSION_PATTERN (parm);
24076 tree pack, packs = NULL_TREE;
24077 int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
24079 /* Add in any args remembered from an earlier partial instantiation. */
24080 targs = add_to_template_args (PACK_EXPANSION_EXTRA_ARGS (parm), targs);
24081 int levels = TMPL_ARGS_DEPTH (targs);
24083 packed_args = expand_template_argument_pack (packed_args);
24085 int len = TREE_VEC_LENGTH (packed_args);
24087 /* Determine the parameter packs we will be deducing from the
24088 pattern, and record their current deductions. */
24089 for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm);
24090 pack; pack = TREE_CHAIN (pack))
24092 tree parm_pack = TREE_VALUE (pack);
24093 int idx, level;
24095 /* Only template parameter packs can be deduced, not e.g. function
24096 parameter packs or __bases or __integer_pack. */
24097 if (!TEMPLATE_PARM_P (parm_pack))
24098 continue;
24100 /* Determine the index and level of this parameter pack. */
24101 template_parm_level_and_index (parm_pack, &level, &idx);
24102 if (level > levels)
24103 continue;
24105 /* Keep track of the parameter packs and their corresponding
24106 argument packs. */
24107 packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
24108 TREE_TYPE (packs) = make_tree_vec (len - start);
24111 /* Loop through all of the arguments that have not yet been
24112 unified and unify each with the pattern. */
24113 for (i = start; i < len; i++)
24115 tree parm;
24116 bool any_explicit = false;
24117 tree arg = TREE_VEC_ELT (packed_args, i);
24119 /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
24120 or the element of its argument pack at the current index if
24121 this argument was explicitly specified. */
24122 for (pack = packs; pack; pack = TREE_CHAIN (pack))
24124 int idx, level;
24125 tree arg, pargs;
24126 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
24128 arg = NULL_TREE;
24129 if (TREE_VALUE (pack)
24130 && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
24131 && (i - start < TREE_VEC_LENGTH (pargs)))
24133 any_explicit = true;
24134 arg = TREE_VEC_ELT (pargs, i - start);
24136 TMPL_ARG (targs, level, idx) = arg;
24139 /* If we had explicit template arguments, substitute them into the
24140 pattern before deduction. */
24141 if (any_explicit)
24143 /* Some arguments might still be unspecified or dependent. */
24144 bool dependent;
24145 ++processing_template_decl;
24146 dependent = any_dependent_template_arguments_p (targs);
24147 if (!dependent)
24148 --processing_template_decl;
24149 parm = tsubst (pattern, targs,
24150 explain_p ? tf_warning_or_error : tf_none,
24151 NULL_TREE);
24152 if (dependent)
24153 --processing_template_decl;
24154 if (parm == error_mark_node)
24155 return 1;
24157 else
24158 parm = pattern;
24160 /* Unify the pattern with the current argument. */
24161 if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
24162 explain_p))
24163 return 1;
24165 /* For each parameter pack, collect the deduced value. */
24166 for (pack = packs; pack; pack = TREE_CHAIN (pack))
24168 int idx, level;
24169 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
24171 TREE_VEC_ELT (TREE_TYPE (pack), i - start) =
24172 TMPL_ARG (targs, level, idx);
24176 /* Verify that the results of unification with the parameter packs
24177 produce results consistent with what we've seen before, and make
24178 the deduced argument packs available. */
24179 for (pack = packs; pack; pack = TREE_CHAIN (pack))
24181 tree old_pack = TREE_VALUE (pack);
24182 tree new_args = TREE_TYPE (pack);
24183 int i, len = TREE_VEC_LENGTH (new_args);
24184 int idx, level;
24185 bool nondeduced_p = false;
24187 /* By default keep the original deduced argument pack.
24188 If necessary, more specific code is going to update the
24189 resulting deduced argument later down in this function. */
24190 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
24191 TMPL_ARG (targs, level, idx) = old_pack;
24193 /* If NEW_ARGS contains any NULL_TREE entries, we didn't
24194 actually deduce anything. */
24195 for (i = 0; i < len && !nondeduced_p; ++i)
24196 if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
24197 nondeduced_p = true;
24198 if (nondeduced_p)
24199 continue;
24201 if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
24203 /* If we had fewer function args than explicit template args,
24204 just use the explicits. */
24205 tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
24206 int explicit_len = TREE_VEC_LENGTH (explicit_args);
24207 if (len < explicit_len)
24208 new_args = explicit_args;
24211 if (!old_pack)
24213 tree result;
24214 /* Build the deduced *_ARGUMENT_PACK. */
24215 if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
24217 result = make_node (NONTYPE_ARGUMENT_PACK);
24218 TREE_CONSTANT (result) = 1;
24220 else
24221 result = cxx_make_type (TYPE_ARGUMENT_PACK);
24223 ARGUMENT_PACK_ARGS (result) = new_args;
24225 /* Note the deduced argument packs for this parameter
24226 pack. */
24227 TMPL_ARG (targs, level, idx) = result;
24229 else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
24230 && (ARGUMENT_PACK_ARGS (old_pack)
24231 == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
24233 /* We only had the explicitly-provided arguments before, but
24234 now we have a complete set of arguments. */
24235 tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
24237 ARGUMENT_PACK_ARGS (old_pack) = new_args;
24238 ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
24239 ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
24241 else
24243 tree bad_old_arg = NULL_TREE, bad_new_arg = NULL_TREE;
24244 tree old_args = ARGUMENT_PACK_ARGS (old_pack);
24245 temp_override<int> ovl (TREE_VEC_LENGTH (old_args));
24246 /* During template argument deduction for the aggregate deduction
24247 candidate, the number of elements in a trailing parameter pack
24248 is only deduced from the number of remaining function
24249 arguments if it is not otherwise deduced. */
24250 if (cxx_dialect >= cxx20
24251 && TREE_VEC_LENGTH (new_args) < TREE_VEC_LENGTH (old_args)
24252 /* FIXME This isn't set properly for partial instantiations. */
24253 && TPARMS_PRIMARY_TEMPLATE (tparms)
24254 && builtin_guide_p (TPARMS_PRIMARY_TEMPLATE (tparms)))
24255 TREE_VEC_LENGTH (old_args) = TREE_VEC_LENGTH (new_args);
24256 if (!comp_template_args (old_args, new_args,
24257 &bad_old_arg, &bad_new_arg))
24258 /* Inconsistent unification of this parameter pack. */
24259 return unify_parameter_pack_inconsistent (explain_p,
24260 bad_old_arg,
24261 bad_new_arg);
24265 return unify_success (explain_p);
24268 /* Handle unification of the domain of an array. PARM_DOM and ARG_DOM are
24269 INTEGER_TYPEs representing the TYPE_DOMAIN of ARRAY_TYPEs. The other
24270 parameters and return value are as for unify. */
24272 static int
24273 unify_array_domain (tree tparms, tree targs,
24274 tree parm_dom, tree arg_dom,
24275 bool explain_p)
24277 tree parm_max;
24278 tree arg_max;
24279 bool parm_cst;
24280 bool arg_cst;
24282 /* Our representation of array types uses "N - 1" as the
24283 TYPE_MAX_VALUE for an array with "N" elements, if "N" is
24284 not an integer constant. We cannot unify arbitrarily
24285 complex expressions, so we eliminate the MINUS_EXPRs
24286 here. */
24287 parm_max = TYPE_MAX_VALUE (parm_dom);
24288 parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
24289 if (!parm_cst)
24291 gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
24292 parm_max = TREE_OPERAND (parm_max, 0);
24294 arg_max = TYPE_MAX_VALUE (arg_dom);
24295 arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
24296 if (!arg_cst)
24298 /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
24299 trying to unify the type of a variable with the type
24300 of a template parameter. For example:
24302 template <unsigned int N>
24303 void f (char (&) [N]);
24304 int g();
24305 void h(int i) {
24306 char a[g(i)];
24307 f(a);
24310 Here, the type of the ARG will be "int [g(i)]", and
24311 may be a SAVE_EXPR, etc. */
24312 if (TREE_CODE (arg_max) != MINUS_EXPR)
24313 return unify_vla_arg (explain_p, arg_dom);
24314 arg_max = TREE_OPERAND (arg_max, 0);
24317 /* If only one of the bounds used a MINUS_EXPR, compensate
24318 by adding one to the other bound. */
24319 if (parm_cst && !arg_cst)
24320 parm_max = fold_build2_loc (input_location, PLUS_EXPR,
24321 integer_type_node,
24322 parm_max,
24323 integer_one_node);
24324 else if (arg_cst && !parm_cst)
24325 arg_max = fold_build2_loc (input_location, PLUS_EXPR,
24326 integer_type_node,
24327 arg_max,
24328 integer_one_node);
24330 return unify (tparms, targs, parm_max, arg_max,
24331 UNIFY_ALLOW_INTEGER, explain_p);
24334 /* Returns whether T, a P or A in unify, is a type, template or expression. */
24336 enum pa_kind_t { pa_type, pa_tmpl, pa_expr };
24338 static pa_kind_t
24339 pa_kind (tree t)
24341 if (PACK_EXPANSION_P (t))
24342 t = PACK_EXPANSION_PATTERN (t);
24343 if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM
24344 || TREE_CODE (t) == UNBOUND_CLASS_TEMPLATE
24345 || DECL_TYPE_TEMPLATE_P (t))
24346 return pa_tmpl;
24347 else if (TYPE_P (t))
24348 return pa_type;
24349 else
24350 return pa_expr;
24353 /* Deduce the value of template parameters. TPARMS is the (innermost)
24354 set of template parameters to a template. TARGS is the bindings
24355 for those template parameters, as determined thus far; TARGS may
24356 include template arguments for outer levels of template parameters
24357 as well. PARM is a parameter to a template function, or a
24358 subcomponent of that parameter; ARG is the corresponding argument.
24359 This function attempts to match PARM with ARG in a manner
24360 consistent with the existing assignments in TARGS. If more values
24361 are deduced, then TARGS is updated.
24363 Returns 0 if the type deduction succeeds, 1 otherwise. The
24364 parameter STRICT is a bitwise or of the following flags:
24366 UNIFY_ALLOW_NONE:
24367 Require an exact match between PARM and ARG.
24368 UNIFY_ALLOW_MORE_CV_QUAL:
24369 Allow the deduced ARG to be more cv-qualified (by qualification
24370 conversion) than ARG.
24371 UNIFY_ALLOW_LESS_CV_QUAL:
24372 Allow the deduced ARG to be less cv-qualified than ARG.
24373 UNIFY_ALLOW_DERIVED:
24374 Allow the deduced ARG to be a template base class of ARG,
24375 or a pointer to a template base class of the type pointed to by
24376 ARG.
24377 UNIFY_ALLOW_INTEGER:
24378 Allow any integral type to be deduced. See the TEMPLATE_PARM_INDEX
24379 case for more information.
24380 UNIFY_ALLOW_OUTER_LEVEL:
24381 This is the outermost level of a deduction. Used to determine validity
24382 of qualification conversions. A valid qualification conversion must
24383 have const qualified pointers leading up to the inner type which
24384 requires additional CV quals, except at the outer level, where const
24385 is not required [conv.qual]. It would be normal to set this flag in
24386 addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
24387 UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
24388 This is the outermost level of a deduction, and PARM can be more CV
24389 qualified at this point.
24390 UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
24391 This is the outermost level of a deduction, and PARM can be less CV
24392 qualified at this point. */
24394 static int
24395 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
24396 bool explain_p)
24398 int idx;
24399 tree targ;
24400 tree tparm;
24401 int strict_in = strict;
24402 tsubst_flags_t complain = (explain_p
24403 ? tf_warning_or_error
24404 : tf_none);
24406 /* I don't think this will do the right thing with respect to types.
24407 But the only case I've seen it in so far has been array bounds, where
24408 signedness is the only information lost, and I think that will be
24409 okay. VIEW_CONVERT_EXPR can appear with class NTTP, thanks to
24410 finish_id_expression_1, and are also OK. */
24411 while (CONVERT_EXPR_P (parm) || TREE_CODE (parm) == VIEW_CONVERT_EXPR)
24412 parm = TREE_OPERAND (parm, 0);
24414 if (arg == error_mark_node)
24415 return unify_invalid (explain_p);
24416 if (arg == unknown_type_node
24417 || arg == init_list_type_node)
24418 /* We can't deduce anything from this, but we might get all the
24419 template args from other function args. */
24420 return unify_success (explain_p);
24422 if (parm == any_targ_node || arg == any_targ_node)
24423 return unify_success (explain_p);
24425 /* If PARM uses template parameters, then we can't bail out here,
24426 even if ARG == PARM, since we won't record unifications for the
24427 template parameters. We might need them if we're trying to
24428 figure out which of two things is more specialized. */
24429 if (arg == parm && !uses_template_parms (parm))
24430 return unify_success (explain_p);
24432 /* Handle init lists early, so the rest of the function can assume
24433 we're dealing with a type. */
24434 if (BRACE_ENCLOSED_INITIALIZER_P (arg))
24436 tree elttype;
24437 tree orig_parm = parm;
24439 if (!is_std_init_list (parm)
24440 && TREE_CODE (parm) != ARRAY_TYPE)
24441 /* We can only deduce from an initializer list argument if the
24442 parameter is std::initializer_list or an array; otherwise this
24443 is a non-deduced context. */
24444 return unify_success (explain_p);
24446 if (TREE_CODE (parm) == ARRAY_TYPE)
24447 elttype = TREE_TYPE (parm);
24448 else
24450 elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
24451 /* Deduction is defined in terms of a single type, so just punt
24452 on the (bizarre) std::initializer_list<T...>. */
24453 if (PACK_EXPANSION_P (elttype))
24454 return unify_success (explain_p);
24457 if (strict != DEDUCE_EXACT
24458 && TYPE_P (elttype)
24459 && !uses_deducible_template_parms (elttype))
24460 /* If ELTTYPE has no deducible template parms, skip deduction from
24461 the list elements. */;
24462 else
24463 for (auto &e: CONSTRUCTOR_ELTS (arg))
24465 tree elt = e.value;
24466 int elt_strict = strict;
24468 if (elt == error_mark_node)
24469 return unify_invalid (explain_p);
24471 if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
24473 tree type = TREE_TYPE (elt);
24474 if (type == error_mark_node)
24475 return unify_invalid (explain_p);
24476 /* It should only be possible to get here for a call. */
24477 gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
24478 elt_strict |= maybe_adjust_types_for_deduction
24479 (tparms, DEDUCE_CALL, &elttype, &type, elt);
24480 elt = type;
24483 RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
24484 explain_p);
24487 if (TREE_CODE (parm) == ARRAY_TYPE
24488 && deducible_array_bound (TYPE_DOMAIN (parm)))
24490 /* Also deduce from the length of the initializer list. */
24491 tree max = size_int (CONSTRUCTOR_NELTS (arg));
24492 tree idx = compute_array_index_type (NULL_TREE, max, tf_none);
24493 if (idx == error_mark_node)
24494 return unify_invalid (explain_p);
24495 return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
24496 idx, explain_p);
24499 /* If the std::initializer_list<T> deduction worked, replace the
24500 deduced A with std::initializer_list<A>. */
24501 if (orig_parm != parm)
24503 idx = TEMPLATE_TYPE_IDX (orig_parm);
24504 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
24505 targ = listify (targ);
24506 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
24508 return unify_success (explain_p);
24511 /* If parm and arg aren't the same kind of thing (template, type, or
24512 expression), fail early. */
24513 if (pa_kind (parm) != pa_kind (arg))
24514 return unify_invalid (explain_p);
24516 /* Immediately reject some pairs that won't unify because of
24517 cv-qualification mismatches. */
24518 if (TREE_CODE (arg) == TREE_CODE (parm)
24519 && TYPE_P (arg)
24520 /* It is the elements of the array which hold the cv quals of an array
24521 type, and the elements might be template type parms. We'll check
24522 when we recurse. */
24523 && TREE_CODE (arg) != ARRAY_TYPE
24524 /* We check the cv-qualifiers when unifying with template type
24525 parameters below. We want to allow ARG `const T' to unify with
24526 PARM `T' for example, when computing which of two templates
24527 is more specialized, for example. */
24528 && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
24529 && !check_cv_quals_for_unify (strict_in, arg, parm))
24530 return unify_cv_qual_mismatch (explain_p, parm, arg);
24532 if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
24533 && TYPE_P (parm) && !CP_TYPE_CONST_P (parm)
24534 && !FUNC_OR_METHOD_TYPE_P (parm))
24535 strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
24536 /* PMFs recurse at the same level, so don't strip this yet. */
24537 if (!TYPE_PTRMEMFUNC_P (parm))
24538 strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
24539 strict &= ~UNIFY_ALLOW_DERIVED;
24540 strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
24541 strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
24543 switch (TREE_CODE (parm))
24545 case TYPENAME_TYPE:
24546 case SCOPE_REF:
24547 case UNBOUND_CLASS_TEMPLATE:
24548 /* In a type which contains a nested-name-specifier, template
24549 argument values cannot be deduced for template parameters used
24550 within the nested-name-specifier. */
24551 return unify_success (explain_p);
24553 case TEMPLATE_TYPE_PARM:
24554 case TEMPLATE_TEMPLATE_PARM:
24555 case BOUND_TEMPLATE_TEMPLATE_PARM:
24556 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
24557 if (error_operand_p (tparm))
24558 return unify_invalid (explain_p);
24560 if (TEMPLATE_TYPE_LEVEL (parm)
24561 != template_decl_level (tparm))
24562 /* The PARM is not one we're trying to unify. Just check
24563 to see if it matches ARG. */
24565 if (TREE_CODE (arg) == TREE_CODE (parm)
24566 && (is_auto (parm) ? is_auto (arg)
24567 : same_type_p (parm, arg)))
24568 return unify_success (explain_p);
24569 else
24570 return unify_type_mismatch (explain_p, parm, arg);
24572 idx = TEMPLATE_TYPE_IDX (parm);
24573 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
24574 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
24575 if (error_operand_p (tparm))
24576 return unify_invalid (explain_p);
24578 /* Check for mixed types and values. */
24579 if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
24580 && TREE_CODE (tparm) != TYPE_DECL)
24581 || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
24582 && TREE_CODE (tparm) != TEMPLATE_DECL))
24583 gcc_unreachable ();
24585 if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
24587 if ((strict_in & UNIFY_ALLOW_DERIVED)
24588 && CLASS_TYPE_P (arg))
24590 /* First try to match ARG directly. */
24591 tree t = try_class_unification (tparms, targs, parm, arg,
24592 explain_p);
24593 if (!t)
24595 /* Otherwise, look for a suitable base of ARG, as below. */
24596 enum template_base_result r;
24597 r = get_template_base (tparms, targs, parm, arg,
24598 explain_p, &t);
24599 if (!t)
24600 return unify_no_common_base (explain_p, r, parm, arg);
24601 arg = t;
24604 /* ARG must be constructed from a template class or a template
24605 template parameter. */
24606 else if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
24607 && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
24608 return unify_template_deduction_failure (explain_p, parm, arg);
24610 /* Deduce arguments T, i from TT<T> or TT<i>. */
24611 if (unify_bound_ttp_args (tparms, targs, parm, arg, explain_p))
24612 return 1;
24614 arg = TYPE_TI_TEMPLATE (arg);
24615 if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg))
24616 /* If the template is a template template parameter, use the
24617 TEMPLATE_TEMPLATE_PARM for matching. */
24618 arg = TREE_TYPE (arg);
24620 /* Fall through to deduce template name. */
24623 if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
24624 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
24626 /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>. */
24628 /* Simple cases: Value already set, does match or doesn't. */
24629 if (targ != NULL_TREE && template_args_equal (targ, arg))
24630 return unify_success (explain_p);
24631 else if (targ)
24632 return unify_inconsistency (explain_p, parm, targ, arg);
24634 else
24636 /* If PARM is `const T' and ARG is only `int', we don't have
24637 a match unless we are allowing additional qualification.
24638 If ARG is `const int' and PARM is just `T' that's OK;
24639 that binds `const int' to `T'. */
24640 if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
24641 arg, parm))
24642 return unify_cv_qual_mismatch (explain_p, parm, arg);
24644 /* Consider the case where ARG is `const volatile int' and
24645 PARM is `const T'. Then, T should be `volatile int'. */
24646 arg = cp_build_qualified_type
24647 (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
24648 if (arg == error_mark_node)
24649 return unify_invalid (explain_p);
24651 /* Simple cases: Value already set, does match or doesn't. */
24652 if (targ != NULL_TREE && same_type_p (targ, arg))
24653 return unify_success (explain_p);
24654 else if (targ)
24655 return unify_inconsistency (explain_p, parm, targ, arg);
24657 /* Make sure that ARG is not a variable-sized array. (Note
24658 that were talking about variable-sized arrays (like
24659 `int[n]'), rather than arrays of unknown size (like
24660 `int[]').) We'll get very confused by such a type since
24661 the bound of the array is not constant, and therefore
24662 not mangleable. Besides, such types are not allowed in
24663 ISO C++, so we can do as we please here. We do allow
24664 them for 'auto' deduction, since that isn't ABI-exposed. */
24665 if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
24666 return unify_vla_arg (explain_p, arg);
24668 /* Strip typedefs as in convert_template_argument. */
24669 arg = canonicalize_type_argument (arg, tf_none);
24672 /* If ARG is a parameter pack or an expansion, we cannot unify
24673 against it unless PARM is also a parameter pack. */
24674 if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
24675 && !template_parameter_pack_p (parm))
24676 return unify_parameter_pack_mismatch (explain_p, parm, arg);
24678 /* If the argument deduction results is a METHOD_TYPE,
24679 then there is a problem.
24680 METHOD_TYPE doesn't map to any real C++ type the result of
24681 the deduction cannot be of that type. */
24682 if (TREE_CODE (arg) == METHOD_TYPE)
24683 return unify_method_type_error (explain_p, arg);
24685 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
24686 return unify_success (explain_p);
24688 case TEMPLATE_PARM_INDEX:
24689 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
24690 if (error_operand_p (tparm))
24691 return unify_invalid (explain_p);
24693 if (TEMPLATE_PARM_LEVEL (parm)
24694 != template_decl_level (tparm))
24696 /* The PARM is not one we're trying to unify. Just check
24697 to see if it matches ARG. */
24698 int result = !(TREE_CODE (arg) == TREE_CODE (parm)
24699 && cp_tree_equal (parm, arg));
24700 if (result)
24701 unify_expression_unequal (explain_p, parm, arg);
24702 return result;
24705 idx = TEMPLATE_PARM_IDX (parm);
24706 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
24708 if (targ)
24710 if ((strict & UNIFY_ALLOW_INTEGER)
24711 && TREE_TYPE (targ) && TREE_TYPE (arg)
24712 && CP_INTEGRAL_TYPE_P (TREE_TYPE (targ)))
24713 /* We're deducing from an array bound, the type doesn't matter.
24714 This conversion should match the one below. */
24715 arg = fold (build_nop (TREE_TYPE (targ), arg));
24716 int x = !cp_tree_equal (targ, arg);
24717 if (x)
24718 unify_inconsistency (explain_p, parm, targ, arg);
24719 return x;
24722 /* [temp.deduct.type] If, in the declaration of a function template
24723 with a non-type template-parameter, the non-type
24724 template-parameter is used in an expression in the function
24725 parameter-list and, if the corresponding template-argument is
24726 deduced, the template-argument type shall match the type of the
24727 template-parameter exactly, except that a template-argument
24728 deduced from an array bound may be of any integral type.
24729 The non-type parameter might use already deduced type parameters. */
24730 tparm = TREE_TYPE (parm);
24731 if (TEMPLATE_PARM_LEVEL (parm) > TMPL_ARGS_DEPTH (targs))
24732 /* We don't have enough levels of args to do any substitution. This
24733 can happen in the context of -fnew-ttp-matching. */;
24734 else
24736 ++processing_template_decl;
24737 tparm = tsubst (tparm, targs, tf_none, NULL_TREE);
24738 --processing_template_decl;
24740 if (tree a = type_uses_auto (tparm))
24742 tparm = do_auto_deduction (tparm, arg, a,
24743 complain, adc_unify, targs,
24744 LOOKUP_NORMAL,
24745 TPARMS_PRIMARY_TEMPLATE (tparms));
24746 if (tparm == error_mark_node)
24747 return 1;
24751 if (!TREE_TYPE (arg)
24752 || TREE_CODE (TREE_TYPE (arg)) == DEPENDENT_OPERATOR_TYPE)
24753 /* Template-parameter dependent expression. Just accept it for now.
24754 It will later be processed in convert_template_argument. */
24756 else if (same_type_ignoring_top_level_qualifiers_p
24757 (non_reference (TREE_TYPE (arg)),
24758 non_reference (tparm)))
24759 /* OK. Ignore top-level quals here because a class-type template
24760 parameter object is const. */;
24761 else if ((strict & UNIFY_ALLOW_INTEGER)
24762 && CP_INTEGRAL_TYPE_P (tparm))
24763 /* Convert the ARG to the type of PARM; the deduced non-type
24764 template argument must exactly match the types of the
24765 corresponding parameter. This conversion should match the
24766 one above. */
24767 arg = fold (build_nop (tparm, arg));
24768 else if (uses_template_parms (tparm))
24770 /* We haven't deduced the type of this parameter yet. */
24771 if (cxx_dialect >= cxx17
24772 /* We deduce from array bounds in try_array_deduction. */
24773 && !(strict & UNIFY_ALLOW_INTEGER)
24774 && TEMPLATE_PARM_LEVEL (parm) <= TMPL_ARGS_DEPTH (targs))
24776 /* Deduce it from the non-type argument. As above, ignore
24777 top-level quals here too. */
24778 tree atype = cv_unqualified (TREE_TYPE (arg));
24779 RECUR_AND_CHECK_FAILURE (tparms, targs,
24780 tparm, atype,
24781 UNIFY_ALLOW_NONE, explain_p);
24782 /* Now check whether the type of this parameter is still
24783 dependent, and give up if so. */
24784 ++processing_template_decl;
24785 tparm = tsubst (TREE_TYPE (parm), targs, tf_none, NULL_TREE);
24786 --processing_template_decl;
24787 if (uses_template_parms (tparm))
24788 return unify_success (explain_p);
24790 else
24791 /* Try again later. */
24792 return unify_success (explain_p);
24794 else
24795 return unify_type_mismatch (explain_p, tparm, TREE_TYPE (arg));
24797 /* If ARG is a parameter pack or an expansion, we cannot unify
24798 against it unless PARM is also a parameter pack. */
24799 if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
24800 && !TEMPLATE_PARM_PARAMETER_PACK (parm))
24801 return unify_parameter_pack_mismatch (explain_p, parm, arg);
24804 bool removed_attr = false;
24805 arg = strip_typedefs_expr (arg, &removed_attr);
24807 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
24808 return unify_success (explain_p);
24810 case PTRMEM_CST:
24812 /* A pointer-to-member constant can be unified only with
24813 another constant. */
24814 if (TREE_CODE (arg) != PTRMEM_CST)
24815 return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
24817 /* Just unify the class member. It would be useless (and possibly
24818 wrong, depending on the strict flags) to unify also
24819 PTRMEM_CST_CLASS, because we want to be sure that both parm and
24820 arg refer to the same variable, even if through different
24821 classes. For instance:
24823 struct A { int x; };
24824 struct B : A { };
24826 Unification of &A::x and &B::x must succeed. */
24827 return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
24828 PTRMEM_CST_MEMBER (arg), strict, explain_p);
24831 case POINTER_TYPE:
24833 if (!TYPE_PTR_P (arg))
24834 return unify_type_mismatch (explain_p, parm, arg);
24836 /* [temp.deduct.call]
24838 A can be another pointer or pointer to member type that can
24839 be converted to the deduced A via a qualification
24840 conversion (_conv.qual_).
24842 We pass down STRICT here rather than UNIFY_ALLOW_NONE.
24843 This will allow for additional cv-qualification of the
24844 pointed-to types if appropriate. */
24846 if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
24847 /* The derived-to-base conversion only persists through one
24848 level of pointers. */
24849 strict |= (strict_in & UNIFY_ALLOW_DERIVED);
24851 return unify (tparms, targs, TREE_TYPE (parm),
24852 TREE_TYPE (arg), strict, explain_p);
24855 case REFERENCE_TYPE:
24856 if (!TYPE_REF_P (arg))
24857 return unify_type_mismatch (explain_p, parm, arg);
24858 return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
24859 strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
24861 case ARRAY_TYPE:
24862 if (TREE_CODE (arg) != ARRAY_TYPE)
24863 return unify_type_mismatch (explain_p, parm, arg);
24864 if ((TYPE_DOMAIN (parm) == NULL_TREE)
24865 != (TYPE_DOMAIN (arg) == NULL_TREE))
24866 return unify_type_mismatch (explain_p, parm, arg);
24867 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
24868 strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
24869 if (TYPE_DOMAIN (parm) != NULL_TREE)
24870 return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
24871 TYPE_DOMAIN (arg), explain_p);
24872 return unify_success (explain_p);
24874 case REAL_TYPE:
24875 case COMPLEX_TYPE:
24876 case VECTOR_TYPE:
24877 case INTEGER_TYPE:
24878 case BOOLEAN_TYPE:
24879 case ENUMERAL_TYPE:
24880 case VOID_TYPE:
24881 case OPAQUE_TYPE:
24882 case NULLPTR_TYPE:
24883 if (TREE_CODE (arg) != TREE_CODE (parm))
24884 return unify_type_mismatch (explain_p, parm, arg);
24886 /* We have already checked cv-qualification at the top of the
24887 function. */
24888 if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
24889 return unify_type_mismatch (explain_p, parm, arg);
24891 /* As far as unification is concerned, this wins. Later checks
24892 will invalidate it if necessary. */
24893 return unify_success (explain_p);
24895 /* Types INTEGER_CST and MINUS_EXPR can come from array bounds. */
24896 /* Type INTEGER_CST can come from ordinary constant template args. */
24897 case INTEGER_CST:
24898 while (CONVERT_EXPR_P (arg))
24899 arg = TREE_OPERAND (arg, 0);
24901 if (TREE_CODE (arg) != INTEGER_CST)
24902 return unify_template_argument_mismatch (explain_p, parm, arg);
24903 return (tree_int_cst_equal (parm, arg)
24904 ? unify_success (explain_p)
24905 : unify_template_argument_mismatch (explain_p, parm, arg));
24907 case TREE_VEC:
24909 int i, len, argslen;
24910 int parm_variadic_p = 0;
24912 if (TREE_CODE (arg) != TREE_VEC)
24913 return unify_template_argument_mismatch (explain_p, parm, arg);
24915 len = TREE_VEC_LENGTH (parm);
24916 argslen = TREE_VEC_LENGTH (arg);
24918 /* Check for pack expansions in the parameters. */
24919 for (i = 0; i < len; ++i)
24921 if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
24923 if (i == len - 1)
24924 /* We can unify against something with a trailing
24925 parameter pack. */
24926 parm_variadic_p = 1;
24927 else
24928 /* [temp.deduct.type]/9: If the template argument list of
24929 P contains a pack expansion that is not the last
24930 template argument, the entire template argument list
24931 is a non-deduced context. */
24932 return unify_success (explain_p);
24936 /* If we don't have enough arguments to satisfy the parameters
24937 (not counting the pack expression at the end), or we have
24938 too many arguments for a parameter list that doesn't end in
24939 a pack expression, we can't unify. */
24940 if (parm_variadic_p
24941 ? argslen < len - parm_variadic_p
24942 : argslen != len)
24943 return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
24945 /* Unify all of the parameters that precede the (optional)
24946 pack expression. */
24947 for (i = 0; i < len - parm_variadic_p; ++i)
24949 RECUR_AND_CHECK_FAILURE (tparms, targs,
24950 TREE_VEC_ELT (parm, i),
24951 TREE_VEC_ELT (arg, i),
24952 UNIFY_ALLOW_NONE, explain_p);
24954 if (parm_variadic_p)
24955 return unify_pack_expansion (tparms, targs, parm, arg,
24956 DEDUCE_EXACT,
24957 /*subr=*/true, explain_p);
24958 return unify_success (explain_p);
24961 case RECORD_TYPE:
24962 case UNION_TYPE:
24963 if (TREE_CODE (arg) != TREE_CODE (parm))
24964 return unify_type_mismatch (explain_p, parm, arg);
24966 if (TYPE_PTRMEMFUNC_P (parm))
24968 if (!TYPE_PTRMEMFUNC_P (arg))
24969 return unify_type_mismatch (explain_p, parm, arg);
24971 return unify (tparms, targs,
24972 TYPE_PTRMEMFUNC_FN_TYPE (parm),
24973 TYPE_PTRMEMFUNC_FN_TYPE (arg),
24974 strict, explain_p);
24976 else if (TYPE_PTRMEMFUNC_P (arg))
24977 return unify_type_mismatch (explain_p, parm, arg);
24979 if (CLASSTYPE_TEMPLATE_INFO (parm))
24981 tree t = NULL_TREE;
24983 if (strict_in & UNIFY_ALLOW_DERIVED)
24985 /* First, we try to unify the PARM and ARG directly. */
24986 t = try_class_unification (tparms, targs,
24987 parm, arg, explain_p);
24989 if (!t)
24991 /* Fallback to the special case allowed in
24992 [temp.deduct.call]:
24994 If P is a class, and P has the form
24995 template-id, then A can be a derived class of
24996 the deduced A. Likewise, if P is a pointer to
24997 a class of the form template-id, A can be a
24998 pointer to a derived class pointed to by the
24999 deduced A. */
25000 enum template_base_result r;
25001 r = get_template_base (tparms, targs, parm, arg,
25002 explain_p, &t);
25004 if (!t)
25006 /* Don't give the derived diagnostic if we're
25007 already dealing with the same template. */
25008 bool same_template
25009 = (CLASSTYPE_TEMPLATE_INFO (arg)
25010 && (CLASSTYPE_TI_TEMPLATE (parm)
25011 == CLASSTYPE_TI_TEMPLATE (arg)));
25012 return unify_no_common_base (explain_p && !same_template,
25013 r, parm, arg);
25017 else if (CLASSTYPE_TEMPLATE_INFO (arg)
25018 && (CLASSTYPE_TI_TEMPLATE (parm)
25019 == CLASSTYPE_TI_TEMPLATE (arg)))
25020 /* Perhaps PARM is something like S<U> and ARG is S<int>.
25021 Then, we should unify `int' and `U'. */
25022 t = arg;
25023 else
25024 /* There's no chance of unification succeeding. */
25025 return unify_type_mismatch (explain_p, parm, arg);
25027 return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
25028 CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE, explain_p);
25030 else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
25031 return unify_type_mismatch (explain_p, parm, arg);
25032 return unify_success (explain_p);
25034 case METHOD_TYPE:
25035 case FUNCTION_TYPE:
25037 unsigned int nargs;
25038 tree *args;
25039 tree a;
25040 unsigned int i;
25042 if (TREE_CODE (arg) != TREE_CODE (parm))
25043 return unify_type_mismatch (explain_p, parm, arg);
25045 /* CV qualifications for methods can never be deduced, they must
25046 match exactly. We need to check them explicitly here,
25047 because type_unification_real treats them as any other
25048 cv-qualified parameter. */
25049 if (TREE_CODE (parm) == METHOD_TYPE
25050 && (!check_cv_quals_for_unify
25051 (UNIFY_ALLOW_NONE,
25052 class_of_this_parm (arg),
25053 class_of_this_parm (parm))))
25054 return unify_cv_qual_mismatch (explain_p, parm, arg);
25055 if (TREE_CODE (arg) == FUNCTION_TYPE
25056 && type_memfn_quals (parm) != type_memfn_quals (arg))
25057 return unify_cv_qual_mismatch (explain_p, parm, arg);
25058 if (type_memfn_rqual (parm) != type_memfn_rqual (arg))
25059 return unify_type_mismatch (explain_p, parm, arg);
25061 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
25062 TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
25064 nargs = list_length (TYPE_ARG_TYPES (arg));
25065 args = XALLOCAVEC (tree, nargs);
25066 for (a = TYPE_ARG_TYPES (arg), i = 0;
25067 a != NULL_TREE && a != void_list_node;
25068 a = TREE_CHAIN (a), ++i)
25069 args[i] = TREE_VALUE (a);
25070 nargs = i;
25072 if (type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
25073 args, nargs, 1, DEDUCE_EXACT,
25074 NULL, explain_p))
25075 return 1;
25077 if (flag_noexcept_type)
25079 tree pspec = TYPE_RAISES_EXCEPTIONS (parm);
25080 tree aspec = canonical_eh_spec (TYPE_RAISES_EXCEPTIONS (arg));
25081 if (pspec == NULL_TREE) pspec = noexcept_false_spec;
25082 if (aspec == NULL_TREE) aspec = noexcept_false_spec;
25083 if (TREE_PURPOSE (pspec) && TREE_PURPOSE (aspec)
25084 && uses_template_parms (TREE_PURPOSE (pspec)))
25085 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_PURPOSE (pspec),
25086 TREE_PURPOSE (aspec),
25087 UNIFY_ALLOW_NONE, explain_p);
25088 else
25090 bool pn = nothrow_spec_p (pspec);
25091 bool an = nothrow_spec_p (aspec);
25092 /* Here "less cv-qual" means the deduced arg (i.e. parm) has
25093 /more/ noexcept, since function pointer conversions are the
25094 reverse of qualification conversions. */
25095 if (an == pn
25096 || (an < pn && (strict & UNIFY_ALLOW_LESS_CV_QUAL))
25097 || (an > pn && (strict & UNIFY_ALLOW_MORE_CV_QUAL)))
25098 /* OK. */;
25099 else
25100 return unify_type_mismatch (explain_p, parm, arg);
25103 if (flag_tm)
25105 /* As for noexcept. */
25106 bool pn = tx_safe_fn_type_p (parm);
25107 bool an = tx_safe_fn_type_p (arg);
25108 if (an == pn
25109 || (an < pn && (strict & UNIFY_ALLOW_LESS_CV_QUAL))
25110 || (an > pn && (strict & UNIFY_ALLOW_MORE_CV_QUAL)))
25111 /* OK. */;
25112 else
25113 return unify_type_mismatch (explain_p, parm, arg);
25116 return 0;
25119 case OFFSET_TYPE:
25120 /* Unify a pointer to member with a pointer to member function, which
25121 deduces the type of the member as a function type. */
25122 if (TYPE_PTRMEMFUNC_P (arg))
25124 /* Check top-level cv qualifiers */
25125 if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
25126 return unify_cv_qual_mismatch (explain_p, parm, arg);
25128 RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
25129 TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
25130 UNIFY_ALLOW_NONE, explain_p);
25132 /* Determine the type of the function we are unifying against. */
25133 tree fntype = static_fn_type (arg);
25135 return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
25138 if (TREE_CODE (arg) != OFFSET_TYPE)
25139 return unify_type_mismatch (explain_p, parm, arg);
25140 RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
25141 TYPE_OFFSET_BASETYPE (arg),
25142 UNIFY_ALLOW_NONE, explain_p);
25143 return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
25144 strict, explain_p);
25146 case CONST_DECL:
25147 if (DECL_TEMPLATE_PARM_P (parm))
25148 return unify (tparms, targs, DECL_INITIAL (parm), arg, strict, explain_p);
25149 if (arg != scalar_constant_value (parm))
25150 return unify_template_argument_mismatch (explain_p, parm, arg);
25151 return unify_success (explain_p);
25153 case FIELD_DECL:
25154 case TEMPLATE_DECL:
25155 /* Matched cases are handled by the ARG == PARM test above. */
25156 return unify_template_argument_mismatch (explain_p, parm, arg);
25158 case VAR_DECL:
25159 /* We might get a variable as a non-type template argument in parm if the
25160 corresponding parameter is type-dependent. Make any necessary
25161 adjustments based on whether arg is a reference. */
25162 if (CONSTANT_CLASS_P (arg))
25163 parm = fold_non_dependent_expr (parm, complain);
25164 else if (REFERENCE_REF_P (arg))
25166 tree sub = TREE_OPERAND (arg, 0);
25167 STRIP_NOPS (sub);
25168 if (TREE_CODE (sub) == ADDR_EXPR)
25169 arg = TREE_OPERAND (sub, 0);
25171 /* Now use the normal expression code to check whether they match. */
25172 goto expr;
25174 case TYPE_ARGUMENT_PACK:
25175 case NONTYPE_ARGUMENT_PACK:
25176 return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
25177 ARGUMENT_PACK_ARGS (arg), strict, explain_p);
25179 case TYPEOF_TYPE:
25180 case DECLTYPE_TYPE:
25181 case TRAIT_TYPE:
25182 /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
25183 or TRAIT_TYPE nodes. */
25184 return unify_success (explain_p);
25186 case ERROR_MARK:
25187 /* Unification fails if we hit an error node. */
25188 return unify_invalid (explain_p);
25190 case INDIRECT_REF:
25191 if (REFERENCE_REF_P (parm))
25193 bool pexp = PACK_EXPANSION_P (arg);
25194 if (pexp)
25195 arg = PACK_EXPANSION_PATTERN (arg);
25196 if (REFERENCE_REF_P (arg))
25197 arg = TREE_OPERAND (arg, 0);
25198 if (pexp)
25199 arg = make_pack_expansion (arg, complain);
25200 return unify (tparms, targs, TREE_OPERAND (parm, 0), arg,
25201 strict, explain_p);
25203 /* FALLTHRU */
25205 default:
25206 /* An unresolved overload is a nondeduced context. */
25207 if (is_overloaded_fn (parm) || type_unknown_p (parm))
25208 return unify_success (explain_p);
25209 gcc_assert (EXPR_P (parm)
25210 || TREE_CODE (parm) == CONSTRUCTOR
25211 || TREE_CODE (parm) == TRAIT_EXPR);
25212 expr:
25213 /* We must be looking at an expression. This can happen with
25214 something like:
25216 template <int I>
25217 void foo(S<I>, S<I + 2>);
25221 template<typename T>
25222 void foo(A<T, T{}>);
25224 This is a "non-deduced context":
25226 [deduct.type]
25228 The non-deduced contexts are:
25230 --A non-type template argument or an array bound in which
25231 a subexpression references a template parameter.
25233 In these cases, we assume deduction succeeded, but don't
25234 actually infer any unifications. */
25236 if (!uses_template_parms (parm)
25237 && !template_args_equal (parm, arg))
25238 return unify_expression_unequal (explain_p, parm, arg);
25239 else
25240 return unify_success (explain_p);
25243 #undef RECUR_AND_CHECK_FAILURE
25245 /* Note that DECL can be defined in this translation unit, if
25246 required. */
25248 static void
25249 mark_definable (tree decl)
25251 tree clone;
25252 DECL_NOT_REALLY_EXTERN (decl) = 1;
25253 FOR_EACH_CLONE (clone, decl)
25254 DECL_NOT_REALLY_EXTERN (clone) = 1;
25257 /* Called if RESULT is explicitly instantiated, or is a member of an
25258 explicitly instantiated class. */
25260 void
25261 mark_decl_instantiated (tree result, int extern_p)
25263 SET_DECL_EXPLICIT_INSTANTIATION (result);
25265 /* If this entity has already been written out, it's too late to
25266 make any modifications. */
25267 if (TREE_ASM_WRITTEN (result))
25268 return;
25270 /* consteval functions are never emitted. */
25271 if (TREE_CODE (result) == FUNCTION_DECL
25272 && DECL_IMMEDIATE_FUNCTION_P (result))
25273 return;
25275 /* For anonymous namespace we don't need to do anything. */
25276 if (decl_internal_context_p (result))
25278 gcc_assert (!TREE_PUBLIC (result));
25279 return;
25282 if (TREE_CODE (result) != FUNCTION_DECL)
25283 /* The TREE_PUBLIC flag for function declarations will have been
25284 set correctly by tsubst. */
25285 TREE_PUBLIC (result) = 1;
25287 if (extern_p)
25289 DECL_EXTERNAL (result) = 1;
25290 DECL_NOT_REALLY_EXTERN (result) = 0;
25292 else
25294 mark_definable (result);
25295 mark_needed (result);
25296 /* Always make artificials weak. */
25297 if (DECL_ARTIFICIAL (result) && flag_weak)
25298 comdat_linkage (result);
25299 /* For WIN32 we also want to put explicit instantiations in
25300 linkonce sections. */
25301 else if (TREE_PUBLIC (result))
25302 maybe_make_one_only (result);
25303 if (TREE_CODE (result) == FUNCTION_DECL
25304 && DECL_TEMPLATE_INSTANTIATED (result))
25305 /* If the function has already been instantiated, clear DECL_EXTERNAL,
25306 since start_preparsed_function wouldn't have if we had an earlier
25307 extern explicit instantiation. */
25308 DECL_EXTERNAL (result) = 0;
25311 /* If EXTERN_P, then this function will not be emitted -- unless
25312 followed by an explicit instantiation, at which point its linkage
25313 will be adjusted. If !EXTERN_P, then this function will be
25314 emitted here. In neither circumstance do we want
25315 import_export_decl to adjust the linkage. */
25316 DECL_INTERFACE_KNOWN (result) = 1;
25319 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
25320 important template arguments. If any are missing, we check whether
25321 they're important by using error_mark_node for substituting into any
25322 args that were used for partial ordering (the ones between ARGS and END)
25323 and seeing if it bubbles up. */
25325 static bool
25326 check_undeduced_parms (tree targs, tree args, tree end)
25328 bool found = false;
25329 for (tree& targ : tree_vec_range (targs))
25330 if (targ == NULL_TREE)
25332 found = true;
25333 targ = error_mark_node;
25335 if (found)
25337 tree substed = tsubst_arg_types (args, targs, end, tf_none, NULL_TREE);
25338 if (substed == error_mark_node)
25339 return true;
25341 return false;
25344 /* Given two function templates PAT1 and PAT2, return:
25346 1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
25347 -1 if PAT2 is more specialized than PAT1.
25348 0 if neither is more specialized.
25350 LEN indicates the number of parameters we should consider
25351 (defaulted parameters should not be considered).
25353 The 1998 std underspecified function template partial ordering, and
25354 DR214 addresses the issue. We take pairs of arguments, one from
25355 each of the templates, and deduce them against each other. One of
25356 the templates will be more specialized if all the *other*
25357 template's arguments deduce against its arguments and at least one
25358 of its arguments *does* *not* deduce against the other template's
25359 corresponding argument. Deduction is done as for class templates.
25360 The arguments used in deduction have reference and top level cv
25361 qualifiers removed. Iff both arguments were originally reference
25362 types *and* deduction succeeds in both directions, an lvalue reference
25363 wins against an rvalue reference and otherwise the template
25364 with the more cv-qualified argument wins for that pairing (if
25365 neither is more cv-qualified, they both are equal). Unlike regular
25366 deduction, after all the arguments have been deduced in this way,
25367 we do *not* verify the deduced template argument values can be
25368 substituted into non-deduced contexts.
25370 The logic can be a bit confusing here, because we look at deduce1 and
25371 targs1 to see if pat2 is at least as specialized, and vice versa; if we
25372 can find template arguments for pat1 to make arg1 look like arg2, that
25373 means that arg2 is at least as specialized as arg1. */
25376 more_specialized_fn (tree pat1, tree pat2, int len)
25378 tree decl1 = DECL_TEMPLATE_RESULT (pat1);
25379 tree decl2 = DECL_TEMPLATE_RESULT (pat2);
25380 tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
25381 tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
25382 tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
25383 tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
25384 tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
25385 tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
25386 tree origs1, origs2;
25387 bool lose1 = false;
25388 bool lose2 = false;
25390 /* Remove the this parameter from non-static member functions. If
25391 one is a non-static member function and the other is not a static
25392 member function, remove the first parameter from that function
25393 also. This situation occurs for operator functions where we
25394 locate both a member function (with this pointer) and non-member
25395 operator (with explicit first operand). */
25396 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
25398 len--; /* LEN is the number of significant arguments for DECL1 */
25399 args1 = TREE_CHAIN (args1);
25400 if (!DECL_STATIC_FUNCTION_P (decl2))
25401 args2 = TREE_CHAIN (args2);
25403 else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
25405 args2 = TREE_CHAIN (args2);
25406 if (!DECL_STATIC_FUNCTION_P (decl1))
25408 len--;
25409 args1 = TREE_CHAIN (args1);
25413 /* If only one is a conversion operator, they are unordered. */
25414 if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
25415 return 0;
25417 /* Consider the return type for a conversion function */
25418 if (DECL_CONV_FN_P (decl1))
25420 args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
25421 args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
25422 len++;
25425 processing_template_decl++;
25427 origs1 = args1;
25428 origs2 = args2;
25430 while (len--
25431 /* Stop when an ellipsis is seen. */
25432 && args1 != NULL_TREE && args2 != NULL_TREE)
25434 tree arg1 = TREE_VALUE (args1);
25435 tree arg2 = TREE_VALUE (args2);
25436 int deduce1, deduce2;
25437 int quals1 = -1;
25438 int quals2 = -1;
25439 int ref1 = 0;
25440 int ref2 = 0;
25442 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
25443 && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25445 /* When both arguments are pack expansions, we need only
25446 unify the patterns themselves. */
25447 arg1 = PACK_EXPANSION_PATTERN (arg1);
25448 arg2 = PACK_EXPANSION_PATTERN (arg2);
25450 /* This is the last comparison we need to do. */
25451 len = 0;
25454 if (TYPE_REF_P (arg1))
25456 ref1 = TYPE_REF_IS_RVALUE (arg1) + 1;
25457 arg1 = TREE_TYPE (arg1);
25458 quals1 = cp_type_quals (arg1);
25461 if (TYPE_REF_P (arg2))
25463 ref2 = TYPE_REF_IS_RVALUE (arg2) + 1;
25464 arg2 = TREE_TYPE (arg2);
25465 quals2 = cp_type_quals (arg2);
25468 arg1 = TYPE_MAIN_VARIANT (arg1);
25469 arg2 = TYPE_MAIN_VARIANT (arg2);
25471 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
25473 int i, len2 = remaining_arguments (args2);
25474 tree parmvec = make_tree_vec (1);
25475 tree argvec = make_tree_vec (len2);
25476 tree ta = args2;
25478 /* Setup the parameter vector, which contains only ARG1. */
25479 TREE_VEC_ELT (parmvec, 0) = arg1;
25481 /* Setup the argument vector, which contains the remaining
25482 arguments. */
25483 for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
25484 TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
25486 deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
25487 argvec, DEDUCE_EXACT,
25488 /*subr=*/true, /*explain_p=*/false)
25489 == 0);
25491 /* We cannot deduce in the other direction, because ARG1 is
25492 a pack expansion but ARG2 is not. */
25493 deduce2 = 0;
25495 else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25497 int i, len1 = remaining_arguments (args1);
25498 tree parmvec = make_tree_vec (1);
25499 tree argvec = make_tree_vec (len1);
25500 tree ta = args1;
25502 /* Setup the parameter vector, which contains only ARG1. */
25503 TREE_VEC_ELT (parmvec, 0) = arg2;
25505 /* Setup the argument vector, which contains the remaining
25506 arguments. */
25507 for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
25508 TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
25510 deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
25511 argvec, DEDUCE_EXACT,
25512 /*subr=*/true, /*explain_p=*/false)
25513 == 0);
25515 /* We cannot deduce in the other direction, because ARG2 is
25516 a pack expansion but ARG1 is not.*/
25517 deduce1 = 0;
25520 else
25522 /* The normal case, where neither argument is a pack
25523 expansion. */
25524 deduce1 = (unify (tparms1, targs1, arg1, arg2,
25525 UNIFY_ALLOW_NONE, /*explain_p=*/false)
25526 == 0);
25527 deduce2 = (unify (tparms2, targs2, arg2, arg1,
25528 UNIFY_ALLOW_NONE, /*explain_p=*/false)
25529 == 0);
25532 /* If we couldn't deduce arguments for tparms1 to make arg1 match
25533 arg2, then arg2 is not as specialized as arg1. */
25534 if (!deduce1)
25535 lose2 = true;
25536 if (!deduce2)
25537 lose1 = true;
25539 /* "If, for a given type, deduction succeeds in both directions
25540 (i.e., the types are identical after the transformations above)
25541 and both P and A were reference types (before being replaced with
25542 the type referred to above):
25543 - if the type from the argument template was an lvalue reference and
25544 the type from the parameter template was not, the argument type is
25545 considered to be more specialized than the other; otherwise,
25546 - if the type from the argument template is more cv-qualified
25547 than the type from the parameter template (as described above),
25548 the argument type is considered to be more specialized than the other;
25549 otherwise,
25550 - neither type is more specialized than the other." */
25552 if (deduce1 && deduce2)
25554 if (ref1 && ref2 && ref1 != ref2)
25556 if (ref1 > ref2)
25557 lose1 = true;
25558 else
25559 lose2 = true;
25561 else if (quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
25563 if ((quals1 & quals2) == quals2)
25564 lose2 = true;
25565 if ((quals1 & quals2) == quals1)
25566 lose1 = true;
25570 if (lose1 && lose2)
25571 /* We've failed to deduce something in either direction.
25572 These must be unordered. */
25573 break;
25575 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
25576 || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25577 /* We have already processed all of the arguments in our
25578 handing of the pack expansion type. */
25579 len = 0;
25581 args1 = TREE_CHAIN (args1);
25582 args2 = TREE_CHAIN (args2);
25585 /* "In most cases, all template parameters must have values in order for
25586 deduction to succeed, but for partial ordering purposes a template
25587 parameter may remain without a value provided it is not used in the
25588 types being used for partial ordering."
25590 Thus, if we are missing any of the targs1 we need to substitute into
25591 origs1, then pat2 is not as specialized as pat1. This can happen when
25592 there is a nondeduced context. */
25593 if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
25594 lose2 = true;
25595 if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
25596 lose1 = true;
25598 processing_template_decl--;
25600 /* If both deductions succeed, the partial ordering selects the more
25601 constrained template. */
25602 /* P2113: If the corresponding template-parameters of the
25603 template-parameter-lists are not equivalent ([temp.over.link]) or if
25604 the function parameters that positionally correspond between the two
25605 templates are not of the same type, neither template is more
25606 specialized than the other. */
25607 if (!lose1 && !lose2
25608 && comp_template_parms (DECL_TEMPLATE_PARMS (pat1),
25609 DECL_TEMPLATE_PARMS (pat2))
25610 && compparms (origs1, origs2))
25612 int winner = more_constrained (decl1, decl2);
25613 if (winner > 0)
25614 lose2 = true;
25615 else if (winner < 0)
25616 lose1 = true;
25619 /* All things being equal, if the next argument is a pack expansion
25620 for one function but not for the other, prefer the
25621 non-variadic function. FIXME this is bogus; see c++/41958. */
25622 if (lose1 == lose2
25623 && args1 && TREE_VALUE (args1)
25624 && args2 && TREE_VALUE (args2))
25626 lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
25627 lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
25630 if (lose1 == lose2)
25631 return 0;
25632 else if (!lose1)
25633 return 1;
25634 else
25635 return -1;
25638 /* Determine which of two partial specializations of TMPL is more
25639 specialized.
25641 PAT1 is a TREE_LIST whose TREE_VALUE is the TEMPLATE_DECL corresponding
25642 to the first partial specialization. The TREE_PURPOSE is the
25643 innermost set of template parameters for the partial
25644 specialization. PAT2 is similar, but for the second template.
25646 Return 1 if the first partial specialization is more specialized;
25647 -1 if the second is more specialized; 0 if neither is more
25648 specialized.
25650 See [temp.class.order] for information about determining which of
25651 two templates is more specialized. */
25653 static int
25654 more_specialized_partial_spec (tree tmpl, tree pat1, tree pat2)
25656 tree targs;
25657 int winner = 0;
25658 bool any_deductions = false;
25660 tree tmpl1 = TREE_VALUE (pat1);
25661 tree tmpl2 = TREE_VALUE (pat2);
25662 tree specargs1 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl1)));
25663 tree specargs2 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl2)));
25665 /* Just like what happens for functions, if we are ordering between
25666 different template specializations, we may encounter dependent
25667 types in the arguments, and we need our dependency check functions
25668 to behave correctly. */
25669 ++processing_template_decl;
25670 targs = get_partial_spec_bindings (tmpl, tmpl1, specargs2);
25671 if (targs)
25673 --winner;
25674 any_deductions = true;
25677 targs = get_partial_spec_bindings (tmpl, tmpl2, specargs1);
25678 if (targs)
25680 ++winner;
25681 any_deductions = true;
25683 --processing_template_decl;
25685 /* If both deductions succeed, the partial ordering selects the more
25686 constrained template. */
25687 if (!winner && any_deductions)
25688 winner = more_constrained (tmpl1, tmpl2);
25690 /* In the case of a tie where at least one of the templates
25691 has a parameter pack at the end, the template with the most
25692 non-packed parameters wins. */
25693 if (winner == 0
25694 && any_deductions
25695 && (template_args_variadic_p (TREE_PURPOSE (pat1))
25696 || template_args_variadic_p (TREE_PURPOSE (pat2))))
25698 tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
25699 tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
25700 int len1 = TREE_VEC_LENGTH (args1);
25701 int len2 = TREE_VEC_LENGTH (args2);
25703 /* We don't count the pack expansion at the end. */
25704 if (template_args_variadic_p (TREE_PURPOSE (pat1)))
25705 --len1;
25706 if (template_args_variadic_p (TREE_PURPOSE (pat2)))
25707 --len2;
25709 if (len1 > len2)
25710 return 1;
25711 else if (len1 < len2)
25712 return -1;
25715 return winner;
25718 /* Return the template arguments that will produce the function signature
25719 DECL from the function template FN, with the explicit template
25720 arguments EXPLICIT_ARGS. If CHECK_RETTYPE is true, the return type must
25721 also match. Return NULL_TREE if no satisfactory arguments could be
25722 found. */
25724 static tree
25725 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
25727 int ntparms = DECL_NTPARMS (fn);
25728 tree targs = make_tree_vec (ntparms);
25729 tree decl_type = TREE_TYPE (decl);
25730 tree decl_arg_types;
25731 tree *args;
25732 unsigned int nargs, ix;
25733 tree arg;
25735 gcc_assert (decl != DECL_TEMPLATE_RESULT (fn));
25737 /* Never do unification on the 'this' parameter. */
25738 decl_arg_types = skip_artificial_parms_for (decl,
25739 TYPE_ARG_TYPES (decl_type));
25741 nargs = list_length (decl_arg_types);
25742 args = XALLOCAVEC (tree, nargs);
25743 for (arg = decl_arg_types, ix = 0;
25744 arg != NULL_TREE;
25745 arg = TREE_CHAIN (arg), ++ix)
25746 args[ix] = TREE_VALUE (arg);
25748 if (fn_type_unification (fn, explicit_args, targs,
25749 args, ix,
25750 (check_rettype || DECL_CONV_FN_P (fn)
25751 ? TREE_TYPE (decl_type) : NULL_TREE),
25752 DEDUCE_EXACT, LOOKUP_NORMAL, NULL,
25753 /*explain_p=*/false,
25754 /*decltype*/false)
25755 == error_mark_node)
25756 return NULL_TREE;
25758 return targs;
25761 /* Return the innermost template arguments that, when applied to a partial
25762 specialization SPEC_TMPL of TMPL, yield the ARGS.
25764 For example, suppose we have:
25766 template <class T, class U> struct S {};
25767 template <class T> struct S<T*, int> {};
25769 Then, suppose we want to get `S<double*, int>'. SPEC_TMPL will be the
25770 partial specialization and the ARGS will be {double*, int}. The resulting
25771 vector will be {double}, indicating that `T' is bound to `double'. */
25773 static tree
25774 get_partial_spec_bindings (tree tmpl, tree spec_tmpl, tree args)
25776 tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (spec_tmpl);
25777 tree spec_args
25778 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (spec_tmpl)));
25779 int i, ntparms = TREE_VEC_LENGTH (tparms);
25780 tree deduced_args;
25781 tree innermost_deduced_args;
25783 innermost_deduced_args = make_tree_vec (ntparms);
25784 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
25786 deduced_args = copy_node (args);
25787 SET_TMPL_ARGS_LEVEL (deduced_args,
25788 TMPL_ARGS_DEPTH (deduced_args),
25789 innermost_deduced_args);
25791 else
25792 deduced_args = innermost_deduced_args;
25794 bool tried_array_deduction = (cxx_dialect < cxx17);
25795 again:
25796 if (unify (tparms, deduced_args,
25797 INNERMOST_TEMPLATE_ARGS (spec_args),
25798 INNERMOST_TEMPLATE_ARGS (args),
25799 UNIFY_ALLOW_NONE, /*explain_p=*/false))
25800 return NULL_TREE;
25802 for (i = 0; i < ntparms; ++i)
25803 if (! TREE_VEC_ELT (innermost_deduced_args, i))
25805 if (!tried_array_deduction)
25807 try_array_deduction (tparms, innermost_deduced_args,
25808 INNERMOST_TEMPLATE_ARGS (spec_args));
25809 tried_array_deduction = true;
25810 if (TREE_VEC_ELT (innermost_deduced_args, i))
25811 goto again;
25813 return NULL_TREE;
25816 if (!push_tinst_level (spec_tmpl, deduced_args))
25818 excessive_deduction_depth = true;
25819 return NULL_TREE;
25822 /* Verify that nondeduced template arguments agree with the type
25823 obtained from argument deduction.
25825 For example:
25827 struct A { typedef int X; };
25828 template <class T, class U> struct C {};
25829 template <class T> struct C<T, typename T::X> {};
25831 Then with the instantiation `C<A, int>', we can deduce that
25832 `T' is `A' but unify () does not check whether `typename T::X'
25833 is `int'. */
25834 spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
25836 if (spec_args != error_mark_node)
25837 spec_args = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
25838 INNERMOST_TEMPLATE_ARGS (spec_args),
25839 tmpl, tf_none, false);
25841 pop_tinst_level ();
25843 if (spec_args == error_mark_node
25844 /* We only need to check the innermost arguments; the other
25845 arguments will always agree. */
25846 || !comp_template_args_porder (INNERMOST_TEMPLATE_ARGS (spec_args),
25847 INNERMOST_TEMPLATE_ARGS (args)))
25848 return NULL_TREE;
25850 /* Now that we have bindings for all of the template arguments,
25851 ensure that the arguments deduced for the template template
25852 parameters have compatible template parameter lists. See the use
25853 of template_template_parm_bindings_ok_p in fn_type_unification
25854 for more information. */
25855 if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
25856 return NULL_TREE;
25858 return deduced_args;
25861 // Compare two function templates T1 and T2 by deducing bindings
25862 // from one against the other. If both deductions succeed, compare
25863 // constraints to see which is more constrained.
25864 static int
25865 more_specialized_inst (tree t1, tree t2)
25867 int fate = 0;
25868 int count = 0;
25870 if (get_bindings (t1, DECL_TEMPLATE_RESULT (t2), NULL_TREE, true))
25872 --fate;
25873 ++count;
25876 if (get_bindings (t2, DECL_TEMPLATE_RESULT (t1), NULL_TREE, true))
25878 ++fate;
25879 ++count;
25882 // If both deductions succeed, then one may be more constrained.
25883 if (count == 2 && fate == 0)
25884 fate = more_constrained (t1, t2);
25886 return fate;
25889 /* TEMPLATES is a TREE_LIST. Each TREE_VALUE is a TEMPLATE_DECL.
25890 Return the TREE_LIST node with the most specialized template, if
25891 any. If there is no most specialized template, the error_mark_node
25892 is returned.
25894 Note that this function does not look at, or modify, the
25895 TREE_PURPOSE or TREE_TYPE of any of the nodes. Since the node
25896 returned is one of the elements of INSTANTIATIONS, callers may
25897 store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
25898 and retrieve it from the value returned. */
25900 tree
25901 most_specialized_instantiation (tree templates)
25903 tree fn, champ;
25905 ++processing_template_decl;
25907 champ = templates;
25908 for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
25910 gcc_assert (TREE_VALUE (champ) != TREE_VALUE (fn));
25911 int fate = more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn));
25912 if (fate == -1)
25913 champ = fn;
25914 else if (!fate)
25916 /* Equally specialized, move to next function. If there
25917 is no next function, nothing's most specialized. */
25918 fn = TREE_CHAIN (fn);
25919 champ = fn;
25920 if (!fn)
25921 break;
25925 if (champ)
25926 /* Now verify that champ is better than everything earlier in the
25927 instantiation list. */
25928 for (fn = templates; fn != champ; fn = TREE_CHAIN (fn)) {
25929 if (more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn)) != 1)
25931 champ = NULL_TREE;
25932 break;
25936 processing_template_decl--;
25938 if (!champ)
25939 return error_mark_node;
25941 return champ;
25944 /* If DECL is a specialization of some template, return the most
25945 general such template. Otherwise, returns NULL_TREE.
25947 For example, given:
25949 template <class T> struct S { template <class U> void f(U); };
25951 if TMPL is `template <class U> void S<int>::f(U)' this will return
25952 the full template. This function will not trace past partial
25953 specializations, however. For example, given in addition:
25955 template <class T> struct S<T*> { template <class U> void f(U); };
25957 if TMPL is `template <class U> void S<int*>::f(U)' this will return
25958 `template <class T> template <class U> S<T*>::f(U)'. */
25960 tree
25961 most_general_template (tree decl)
25963 if (TREE_CODE (decl) != TEMPLATE_DECL)
25965 if (tree tinfo = get_template_info (decl))
25966 decl = TI_TEMPLATE (tinfo);
25967 /* The TI_TEMPLATE can be an IDENTIFIER_NODE for a
25968 template friend, or a FIELD_DECL for a capture pack. */
25969 if (TREE_CODE (decl) != TEMPLATE_DECL)
25970 return NULL_TREE;
25973 /* Look for more and more general templates. */
25974 while (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
25976 /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
25977 (See cp-tree.h for details.) */
25978 if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
25979 break;
25981 if (CLASS_TYPE_P (TREE_TYPE (decl))
25982 && !TYPE_DECL_ALIAS_P (TYPE_NAME (TREE_TYPE (decl)))
25983 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
25984 break;
25986 /* Stop if we run into an explicitly specialized class template. */
25987 if (!DECL_NAMESPACE_SCOPE_P (decl)
25988 && DECL_CONTEXT (decl)
25989 && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
25990 break;
25992 decl = DECL_TI_TEMPLATE (decl);
25995 return decl;
25998 /* Return the most specialized of the template partial specializations
25999 which can produce TARGET, a specialization of some class or variable
26000 template. The value returned is a TEMPLATE_INFO; the TI_TEMPLATE is a
26001 TEMPLATE_DECL node corresponding to the partial specialization, while
26002 the TI_ARGS is the set of template arguments that must be substituted
26003 into the template pattern in order to generate TARGET. The result is
26004 cached in the TI_PARTIAL_INFO of the corresponding TEMPLATE_INFO unless
26005 RECHECKING is true.
26007 If the choice of partial specialization is ambiguous, a diagnostic
26008 is issued, and the error_mark_node is returned. If there are no
26009 partial specializations matching TARGET, then NULL_TREE is
26010 returned, indicating that the primary template should be used. */
26012 tree
26013 most_specialized_partial_spec (tree target, tsubst_flags_t complain,
26014 bool rechecking /* = false */)
26016 tree tinfo = NULL_TREE;
26017 tree tmpl, args, decl;
26018 if (TYPE_P (target))
26020 tinfo = CLASSTYPE_TEMPLATE_INFO (target);
26021 tmpl = TI_TEMPLATE (tinfo);
26022 args = TI_ARGS (tinfo);
26023 decl = TYPE_NAME (target);
26025 else if (TREE_CODE (target) == TEMPLATE_ID_EXPR)
26027 tmpl = TREE_OPERAND (target, 0);
26028 args = TREE_OPERAND (target, 1);
26029 decl = DECL_TEMPLATE_RESULT (tmpl);
26031 else if (VAR_P (target))
26033 tinfo = DECL_TEMPLATE_INFO (target);
26034 tmpl = TI_TEMPLATE (tinfo);
26035 args = TI_ARGS (tinfo);
26036 decl = target;
26038 else
26039 gcc_unreachable ();
26041 if (!PRIMARY_TEMPLATE_P (tmpl))
26042 return NULL_TREE;
26044 if (!rechecking
26045 && tinfo
26046 && (VAR_P (target) || COMPLETE_TYPE_P (target)))
26047 return TI_PARTIAL_INFO (tinfo);
26049 tree main_tmpl = most_general_template (tmpl);
26050 tree specs = DECL_TEMPLATE_SPECIALIZATIONS (main_tmpl);
26051 if (!specs)
26052 /* There are no partial specializations of this template. */
26053 return NULL_TREE;
26055 push_access_scope_guard pas (decl);
26056 deferring_access_check_sentinel acs (dk_no_deferred);
26058 /* For determining which partial specialization to use, only the
26059 innermost args are interesting. */
26060 tree outer_args = NULL_TREE;
26061 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
26063 outer_args = strip_innermost_template_args (args, 1);
26064 args = INNERMOST_TEMPLATE_ARGS (args);
26067 /* The caller hasn't called push_to_top_level yet, but we need
26068 get_partial_spec_bindings to be done in non-template context so that we'll
26069 fully resolve everything. */
26070 processing_template_decl_sentinel ptds;
26072 tree list = NULL_TREE;
26073 for (tree t = specs; t; t = TREE_CHAIN (t))
26075 const tree ospec_tmpl = TREE_VALUE (t);
26077 tree spec_tmpl;
26078 if (outer_args)
26080 /* Substitute in the template args from the enclosing class. */
26081 ++processing_template_decl;
26082 spec_tmpl = tsubst (ospec_tmpl, outer_args, tf_none, NULL_TREE);
26083 --processing_template_decl;
26084 if (spec_tmpl == error_mark_node)
26085 return error_mark_node;
26087 else
26088 spec_tmpl = ospec_tmpl;
26090 tree spec_args = get_partial_spec_bindings (tmpl, spec_tmpl, args);
26091 if (spec_args)
26093 if (outer_args)
26094 spec_args = add_to_template_args (outer_args, spec_args);
26096 /* Keep the candidate only if its constraints are satisfied. */
26097 if (constraints_satisfied_p (ospec_tmpl, spec_args))
26098 list = tree_cons (spec_args, ospec_tmpl, list);
26102 if (! list)
26103 return NULL_TREE;
26105 tree champ = list;
26106 bool ambiguous_p = false;
26107 for (tree t = TREE_CHAIN (list); t; t = TREE_CHAIN (t))
26109 int fate = more_specialized_partial_spec (tmpl, champ, t);
26110 if (fate == 1)
26112 else
26114 if (fate == 0)
26116 t = TREE_CHAIN (t);
26117 if (! t)
26119 ambiguous_p = true;
26120 break;
26123 champ = t;
26127 if (!ambiguous_p)
26128 for (tree t = list; t && t != champ; t = TREE_CHAIN (t))
26130 int fate = more_specialized_partial_spec (tmpl, champ, t);
26131 if (fate != 1)
26133 ambiguous_p = true;
26134 break;
26138 if (ambiguous_p)
26140 const char *str;
26141 char *spaces = NULL;
26142 if (!(complain & tf_error))
26143 return error_mark_node;
26144 if (TYPE_P (target))
26145 error ("ambiguous template instantiation for %q#T", target);
26146 else
26147 error ("ambiguous template instantiation for %q#D", target);
26148 str = ngettext ("candidate is:", "candidates are:", list_length (list));
26149 for (tree t = list; t; t = TREE_CHAIN (t))
26151 tree subst = build_tree_list (TREE_VALUE (t), TREE_PURPOSE (t));
26152 inform (DECL_SOURCE_LOCATION (TREE_VALUE (t)),
26153 "%s %#qS", spaces ? spaces : str, subst);
26154 spaces = spaces ? spaces : get_spaces (str);
26156 free (spaces);
26157 return error_mark_node;
26160 tree result = build_template_info (TREE_VALUE (champ), TREE_PURPOSE (champ));
26161 if (!rechecking && tinfo)
26162 TI_PARTIAL_INFO (tinfo) = result;
26163 return result;
26166 /* Explicitly instantiate DECL. */
26168 void
26169 do_decl_instantiation (tree decl, tree storage)
26171 tree result = NULL_TREE;
26172 int extern_p = 0;
26174 if (!decl || decl == error_mark_node)
26175 /* An error occurred, for which grokdeclarator has already issued
26176 an appropriate message. */
26177 return;
26178 else if (! DECL_LANG_SPECIFIC (decl))
26180 error ("explicit instantiation of non-template %q#D", decl);
26181 return;
26183 else if (DECL_DECLARED_CONCEPT_P (decl))
26185 if (VAR_P (decl))
26186 error ("explicit instantiation of variable concept %q#D", decl);
26187 else
26188 error ("explicit instantiation of function concept %q#D", decl);
26189 return;
26192 bool var_templ = (DECL_TEMPLATE_INFO (decl)
26193 && variable_template_p (DECL_TI_TEMPLATE (decl)));
26195 if (VAR_P (decl) && !var_templ)
26197 /* There is an asymmetry here in the way VAR_DECLs and
26198 FUNCTION_DECLs are handled by grokdeclarator. In the case of
26199 the latter, the DECL we get back will be marked as a
26200 template instantiation, and the appropriate
26201 DECL_TEMPLATE_INFO will be set up. This does not happen for
26202 VAR_DECLs so we do the lookup here. Probably, grokdeclarator
26203 should handle VAR_DECLs as it currently handles
26204 FUNCTION_DECLs. */
26205 if (!DECL_CLASS_SCOPE_P (decl))
26207 error ("%qD is not a static data member of a class template", decl);
26208 return;
26210 result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
26211 if (!result || !VAR_P (result))
26213 error ("no matching template for %qD found", decl);
26214 return;
26216 if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
26218 error ("type %qT for explicit instantiation %qD does not match "
26219 "declared type %qT", TREE_TYPE (result), decl,
26220 TREE_TYPE (decl));
26221 return;
26224 else if (TREE_CODE (decl) != FUNCTION_DECL && !var_templ)
26226 error ("explicit instantiation of %q#D", decl);
26227 return;
26229 else
26230 result = decl;
26232 /* Check for various error cases. Note that if the explicit
26233 instantiation is valid the RESULT will currently be marked as an
26234 *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
26235 until we get here. */
26237 if (DECL_TEMPLATE_SPECIALIZATION (result))
26239 /* DR 259 [temp.spec].
26241 Both an explicit instantiation and a declaration of an explicit
26242 specialization shall not appear in a program unless the explicit
26243 instantiation follows a declaration of the explicit specialization.
26245 For a given set of template parameters, if an explicit
26246 instantiation of a template appears after a declaration of an
26247 explicit specialization for that template, the explicit
26248 instantiation has no effect. */
26249 return;
26251 else if (DECL_EXPLICIT_INSTANTIATION (result))
26253 /* [temp.spec]
26255 No program shall explicitly instantiate any template more
26256 than once.
26258 We check DECL_NOT_REALLY_EXTERN so as not to complain when
26259 the first instantiation was `extern' and the second is not,
26260 and EXTERN_P for the opposite case. */
26261 if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
26262 permerror (input_location, "duplicate explicit instantiation of %q#D", result);
26263 /* If an "extern" explicit instantiation follows an ordinary
26264 explicit instantiation, the template is instantiated. */
26265 if (extern_p)
26266 return;
26268 else if (!DECL_IMPLICIT_INSTANTIATION (result))
26270 error ("no matching template for %qD found", result);
26271 return;
26273 else if (!DECL_TEMPLATE_INFO (result))
26275 permerror (input_location, "explicit instantiation of non-template %q#D", result);
26276 return;
26279 if (storage == NULL_TREE)
26281 else if (storage == ridpointers[(int) RID_EXTERN])
26283 if (cxx_dialect == cxx98)
26284 pedwarn (input_location, OPT_Wpedantic,
26285 "ISO C++ 1998 forbids the use of %<extern%> on explicit "
26286 "instantiations");
26287 extern_p = 1;
26289 else
26290 error ("storage class %qD applied to template instantiation", storage);
26292 check_explicit_instantiation_namespace (result);
26293 mark_decl_instantiated (result, extern_p);
26294 if (! extern_p)
26295 instantiate_decl (result, /*defer_ok=*/true,
26296 /*expl_inst_class_mem_p=*/false);
26299 static void
26300 mark_class_instantiated (tree t, int extern_p)
26302 SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
26303 SET_CLASSTYPE_INTERFACE_KNOWN (t);
26304 CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
26305 TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
26306 if (! extern_p)
26308 CLASSTYPE_DEBUG_REQUESTED (t) = 1;
26309 rest_of_type_compilation (t, 1);
26313 /* Perform an explicit instantiation of template class T. STORAGE, if
26314 non-null, is the RID for extern, inline or static. COMPLAIN is
26315 nonzero if this is called from the parser, zero if called recursively,
26316 since the standard is unclear (as detailed below). */
26318 void
26319 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
26321 if (!(CLASS_TYPE_P (t) && CLASSTYPE_TEMPLATE_INFO (t)))
26323 if (tree ti = TYPE_TEMPLATE_INFO (t))
26324 error ("explicit instantiation of non-class template %qD",
26325 TI_TEMPLATE (ti));
26326 else
26327 error ("explicit instantiation of non-template type %qT", t);
26328 return;
26331 complete_type (t);
26333 if (!COMPLETE_TYPE_P (t))
26335 if (complain & tf_error)
26336 error ("explicit instantiation of %q#T before definition of template",
26338 return;
26341 /* At most one of these will be true. */
26342 bool extern_p = false;
26343 bool nomem_p = false;
26344 bool static_p = false;
26346 if (storage != NULL_TREE)
26348 if (storage == ridpointers[(int) RID_EXTERN])
26350 if (cxx_dialect == cxx98)
26351 pedwarn (input_location, OPT_Wpedantic,
26352 "ISO C++ 1998 forbids the use of %<extern%> on "
26353 "explicit instantiations");
26355 else
26356 pedwarn (input_location, OPT_Wpedantic,
26357 "ISO C++ forbids the use of %qE"
26358 " on explicit instantiations", storage);
26360 if (storage == ridpointers[(int) RID_INLINE])
26361 nomem_p = true;
26362 else if (storage == ridpointers[(int) RID_EXTERN])
26363 extern_p = true;
26364 else if (storage == ridpointers[(int) RID_STATIC])
26365 static_p = true;
26366 else
26367 error ("storage class %qD applied to template instantiation",
26368 storage);
26371 if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
26372 /* DR 259 [temp.spec].
26374 Both an explicit instantiation and a declaration of an explicit
26375 specialization shall not appear in a program unless the
26376 explicit instantiation follows a declaration of the explicit
26377 specialization.
26379 For a given set of template parameters, if an explicit
26380 instantiation of a template appears after a declaration of an
26381 explicit specialization for that template, the explicit
26382 instantiation has no effect. */
26383 return;
26385 if (CLASSTYPE_EXPLICIT_INSTANTIATION (t) && !CLASSTYPE_INTERFACE_ONLY (t))
26387 /* We've already instantiated the template. */
26389 /* [temp.spec]
26391 No program shall explicitly instantiate any template more
26392 than once.
26394 If EXTERN_P then this is ok. */
26395 if (!extern_p && (complain & tf_error))
26396 permerror (input_location,
26397 "duplicate explicit instantiation of %q#T", t);
26399 return;
26402 check_explicit_instantiation_namespace (TYPE_NAME (t));
26403 mark_class_instantiated (t, extern_p);
26405 if (nomem_p)
26406 return;
26408 /* In contrast to implicit instantiation, where only the
26409 declarations, and not the definitions, of members are
26410 instantiated, we have here:
26412 [temp.explicit]
26414 An explicit instantiation that names a class template
26415 specialization is also an explicit instantiation of the same
26416 kind (declaration or definition) of each of its members (not
26417 including members inherited from base classes and members
26418 that are templates) that has not been previously explicitly
26419 specialized in the translation unit containing the explicit
26420 instantiation, provided that the associated constraints, if
26421 any, of that member are satisfied by the template arguments
26422 of the explicit instantiation. */
26423 for (tree fld = TYPE_FIELDS (t); fld; fld = DECL_CHAIN (fld))
26424 if ((VAR_P (fld)
26425 || (TREE_CODE (fld) == FUNCTION_DECL
26426 && !static_p
26427 && user_provided_p (fld)))
26428 && DECL_TEMPLATE_INSTANTIATION (fld)
26429 && constraints_satisfied_p (fld))
26431 mark_decl_instantiated (fld, extern_p);
26432 if (! extern_p)
26433 instantiate_decl (fld, /*defer_ok=*/true,
26434 /*expl_inst_class_mem_p=*/true);
26436 else if (DECL_IMPLICIT_TYPEDEF_P (fld))
26438 tree type = TREE_TYPE (fld);
26440 if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
26441 && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
26442 do_type_instantiation (type, storage, 0);
26446 /* Given a function DECL, which is a specialization of TMPL, modify
26447 DECL to be a re-instantiation of TMPL with the same template
26448 arguments. TMPL should be the template into which tsubst'ing
26449 should occur for DECL, not the most general template.
26451 One reason for doing this is a scenario like this:
26453 template <class T>
26454 void f(const T&, int i);
26456 void g() { f(3, 7); }
26458 template <class T>
26459 void f(const T& t, const int i) { }
26461 Note that when the template is first instantiated, with
26462 instantiate_template, the resulting DECL will have no name for the
26463 first parameter, and the wrong type for the second. So, when we go
26464 to instantiate the DECL, we regenerate it. */
26466 static void
26467 regenerate_decl_from_template (tree decl, tree tmpl, tree args)
26469 /* The arguments used to instantiate DECL, from the most general
26470 template. */
26471 tree code_pattern = DECL_TEMPLATE_RESULT (tmpl);
26473 /* Make sure that we can see identifiers, and compute access correctly. */
26474 push_access_scope (decl);
26476 if (TREE_CODE (decl) == FUNCTION_DECL)
26478 tree specs;
26479 int args_depth;
26480 int parms_depth;
26482 /* Don't bother with this for unique friends that can't be redeclared and
26483 might change type if regenerated (PR69836). */
26484 if (DECL_UNIQUE_FRIEND_P (decl))
26485 goto done;
26487 /* Use the source location of the definition. */
26488 DECL_SOURCE_LOCATION (decl) = DECL_SOURCE_LOCATION (tmpl);
26490 args_depth = TMPL_ARGS_DEPTH (args);
26491 parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
26492 if (args_depth > parms_depth)
26493 args = get_innermost_template_args (args, parms_depth);
26495 /* Instantiate a dynamic exception-specification. noexcept will be
26496 handled below. */
26497 if (tree raises = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (code_pattern)))
26498 if (TREE_VALUE (raises))
26500 specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
26501 args, tf_error, NULL_TREE,
26502 /*defer_ok*/false);
26503 if (specs && specs != error_mark_node)
26504 TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
26505 specs);
26508 /* Merge parameter declarations. */
26509 if (tree pattern_parm
26510 = skip_artificial_parms_for (code_pattern,
26511 DECL_ARGUMENTS (code_pattern)))
26513 tree *p = &DECL_ARGUMENTS (decl);
26514 for (int skip = num_artificial_parms_for (decl); skip; --skip)
26515 p = &DECL_CHAIN (*p);
26516 *p = tsubst_decl (pattern_parm, args, tf_error);
26517 for (tree t = *p; t; t = DECL_CHAIN (t))
26518 DECL_CONTEXT (t) = decl;
26521 if (DECL_CONTRACTS (decl))
26523 /* If we're regenerating a specialization, the contracts will have
26524 been copied from the most general template. Replace those with
26525 the ones from the actual specialization. */
26526 tree tmpl = DECL_TI_TEMPLATE (decl);
26527 if (DECL_TEMPLATE_SPECIALIZATION (tmpl))
26529 remove_contract_attributes (decl);
26530 copy_contract_attributes (decl, code_pattern);
26533 tsubst_contract_attributes (decl, args, tf_warning_or_error, code_pattern);
26536 /* Merge additional specifiers from the CODE_PATTERN. */
26537 if (DECL_DECLARED_INLINE_P (code_pattern)
26538 && !DECL_DECLARED_INLINE_P (decl))
26539 DECL_DECLARED_INLINE_P (decl) = 1;
26541 maybe_instantiate_noexcept (decl, tf_error);
26543 else if (VAR_P (decl))
26545 start_lambda_scope (decl);
26546 DECL_INITIAL (decl) =
26547 tsubst_init (DECL_INITIAL (code_pattern), decl, args,
26548 tf_error, DECL_TI_TEMPLATE (decl));
26549 finish_lambda_scope ();
26550 if (VAR_HAD_UNKNOWN_BOUND (decl))
26551 TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
26552 tf_error, DECL_TI_TEMPLATE (decl));
26554 else
26555 gcc_unreachable ();
26557 done:
26558 pop_access_scope (decl);
26561 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
26562 substituted to get DECL. */
26564 tree
26565 template_for_substitution (tree decl)
26567 tree tmpl = DECL_TI_TEMPLATE (decl);
26569 /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
26570 for the instantiation. This is not always the most general
26571 template. Consider, for example:
26573 template <class T>
26574 struct S { template <class U> void f();
26575 template <> void f<int>(); };
26577 and an instantiation of S<double>::f<int>. We want TD to be the
26578 specialization S<T>::f<int>, not the more general S<T>::f<U>. */
26579 while (/* An instantiation cannot have a definition, so we need a
26580 more general template. */
26581 DECL_TEMPLATE_INSTANTIATION (tmpl)
26582 /* We must also deal with friend templates. Given:
26584 template <class T> struct S {
26585 template <class U> friend void f() {};
26588 S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
26589 so far as the language is concerned, but that's still
26590 where we get the pattern for the instantiation from. On
26591 other hand, if the definition comes outside the class, say:
26593 template <class T> struct S {
26594 template <class U> friend void f();
26596 template <class U> friend void f() {}
26598 we don't need to look any further. That's what the check for
26599 DECL_INITIAL is for. */
26600 || (TREE_CODE (decl) == FUNCTION_DECL
26601 && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
26602 && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
26604 /* The present template, TD, should not be a definition. If it
26605 were a definition, we should be using it! Note that we
26606 cannot restructure the loop to just keep going until we find
26607 a template with a definition, since that might go too far if
26608 a specialization was declared, but not defined. */
26610 /* Fetch the more general template. */
26611 tmpl = DECL_TI_TEMPLATE (tmpl);
26614 return tmpl;
26617 /* Returns true if we need to instantiate this template instance even if we
26618 know we aren't going to emit it. */
26620 bool
26621 always_instantiate_p (tree decl)
26623 /* We always instantiate inline functions so that we can inline them. An
26624 explicit instantiation declaration prohibits implicit instantiation of
26625 non-inline functions. With high levels of optimization, we would
26626 normally inline non-inline functions -- but we're not allowed to do
26627 that for "extern template" functions. Therefore, we check
26628 DECL_DECLARED_INLINE_P, rather than possibly_inlined_p. */
26629 return ((TREE_CODE (decl) == FUNCTION_DECL
26630 && (DECL_DECLARED_INLINE_P (decl)
26631 || type_uses_auto (TREE_TYPE (TREE_TYPE (decl)))))
26632 /* And we need to instantiate static data members so that
26633 their initializers are available in integral constant
26634 expressions. */
26635 || (VAR_P (decl)
26636 && decl_maybe_constant_var_p (decl)));
26639 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
26640 instantiate it now, modifying TREE_TYPE (fn). Returns false on
26641 error, true otherwise. */
26643 bool
26644 maybe_instantiate_noexcept (tree fn, tsubst_flags_t complain)
26646 if (fn == error_mark_node)
26647 return false;
26649 /* Don't instantiate a noexcept-specification from template context. */
26650 if (processing_template_decl
26651 && (!flag_noexcept_type || type_dependent_expression_p (fn)))
26652 return true;
26654 tree fntype = TREE_TYPE (fn);
26655 tree spec = TYPE_RAISES_EXCEPTIONS (fntype);
26657 if ((!spec || UNEVALUATED_NOEXCEPT_SPEC_P (spec))
26658 && DECL_MAYBE_DELETED (fn))
26660 if (fn == current_function_decl)
26661 /* We're in start_preparsed_function, keep going. */
26662 return true;
26664 ++function_depth;
26665 maybe_synthesize_method (fn);
26666 --function_depth;
26667 return !DECL_DELETED_FN (fn);
26670 if (!spec || !TREE_PURPOSE (spec))
26671 return true;
26673 tree noex = TREE_PURPOSE (spec);
26674 if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
26675 && TREE_CODE (noex) != DEFERRED_PARSE)
26676 return true;
26678 tree orig_fn = NULL_TREE;
26679 /* For a member friend template we can get a TEMPLATE_DECL. Let's use
26680 its FUNCTION_DECL for the rest of this function -- push_access_scope
26681 doesn't accept TEMPLATE_DECLs. */
26682 if (DECL_FUNCTION_TEMPLATE_P (fn))
26684 orig_fn = fn;
26685 fn = DECL_TEMPLATE_RESULT (fn);
26688 if (DECL_CLONED_FUNCTION_P (fn))
26690 tree prime = DECL_CLONED_FUNCTION (fn);
26691 if (!maybe_instantiate_noexcept (prime, complain))
26692 return false;
26693 spec = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (prime));
26695 else if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
26697 static hash_set<tree>* fns = new hash_set<tree>;
26698 bool added = false;
26699 if (DEFERRED_NOEXCEPT_PATTERN (noex) == NULL_TREE)
26701 spec = get_defaulted_eh_spec (fn, complain);
26702 if (spec == error_mark_node)
26703 /* This might have failed because of an unparsed DMI, so
26704 let's try again later. */
26705 return false;
26707 else if (!(added = !fns->add (fn)))
26709 /* If hash_set::add returns true, the element was already there. */
26710 location_t loc = cp_expr_loc_or_loc (DEFERRED_NOEXCEPT_PATTERN (noex),
26711 DECL_SOURCE_LOCATION (fn));
26712 error_at (loc,
26713 "exception specification of %qD depends on itself",
26714 fn);
26715 spec = noexcept_false_spec;
26717 else if (push_tinst_level (fn))
26719 push_to_top_level ();
26720 push_access_scope (fn);
26721 push_deferring_access_checks (dk_no_deferred);
26722 input_location = DECL_SOURCE_LOCATION (fn);
26724 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
26725 && !DECL_LOCAL_DECL_P (fn))
26727 /* If needed, set current_class_ptr for the benefit of
26728 tsubst_copy/PARM_DECL. */
26729 tree this_parm = DECL_ARGUMENTS (fn);
26730 current_class_ptr = NULL_TREE;
26731 current_class_ref = cp_build_fold_indirect_ref (this_parm);
26732 current_class_ptr = this_parm;
26735 /* If this function is represented by a TEMPLATE_DECL, then
26736 the deferred noexcept-specification might still contain
26737 dependent types, even after substitution. And we need the
26738 dependency check functions to work in build_noexcept_spec. */
26739 if (orig_fn)
26740 ++processing_template_decl;
26742 /* Do deferred instantiation of the noexcept-specifier. */
26743 noex = tsubst_copy_and_build (DEFERRED_NOEXCEPT_PATTERN (noex),
26744 DEFERRED_NOEXCEPT_ARGS (noex),
26745 tf_warning_or_error, fn);
26747 /* Build up the noexcept-specification. */
26748 spec = build_noexcept_spec (noex, tf_warning_or_error);
26750 if (orig_fn)
26751 --processing_template_decl;
26753 pop_deferring_access_checks ();
26754 pop_access_scope (fn);
26755 pop_tinst_level ();
26756 pop_from_top_level ();
26758 else
26759 spec = noexcept_false_spec;
26761 if (added)
26762 fns->remove (fn);
26765 if (spec == error_mark_node)
26767 /* This failed with a hard error, so let's go with false. */
26768 gcc_assert (seen_error ());
26769 spec = noexcept_false_spec;
26772 TREE_TYPE (fn) = build_exception_variant (fntype, spec);
26773 if (orig_fn)
26774 TREE_TYPE (orig_fn) = TREE_TYPE (fn);
26776 return true;
26779 /* We're starting to process the function INST, an instantiation of PATTERN;
26780 add their parameters to local_specializations. */
26782 void
26783 register_parameter_specializations (tree pattern, tree inst)
26785 tree tmpl_parm = DECL_ARGUMENTS (pattern);
26786 tree spec_parm = DECL_ARGUMENTS (inst);
26787 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (inst))
26789 register_local_specialization (spec_parm, tmpl_parm);
26790 spec_parm = skip_artificial_parms_for (inst, spec_parm);
26791 tmpl_parm = skip_artificial_parms_for (pattern, tmpl_parm);
26793 for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
26795 if (!DECL_PACK_P (tmpl_parm))
26797 register_local_specialization (spec_parm, tmpl_parm);
26798 spec_parm = DECL_CHAIN (spec_parm);
26800 else
26802 /* Register the (value) argument pack as a specialization of
26803 TMPL_PARM, then move on. */
26804 tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
26805 register_local_specialization (argpack, tmpl_parm);
26808 gcc_assert (!spec_parm);
26811 /* Instantiate the body of D using PATTERN with ARGS. We have
26812 already determined PATTERN is the correct template to use.
26813 NESTED_P is true if this is a nested function, in which case
26814 PATTERN will be a FUNCTION_DECL not a TEMPLATE_DECL. */
26816 static void
26817 instantiate_body (tree pattern, tree args, tree d, bool nested_p)
26819 tree td = NULL_TREE;
26820 tree code_pattern = pattern;
26822 if (!nested_p)
26824 td = pattern;
26825 code_pattern = DECL_TEMPLATE_RESULT (td);
26827 else
26828 /* Only OMP reductions are nested. */
26829 gcc_checking_assert (DECL_OMP_DECLARE_REDUCTION_P (code_pattern));
26831 vec<tree> omp_privatization_save;
26832 if (current_function_decl)
26833 save_omp_privatization_clauses (omp_privatization_save);
26835 bool push_to_top = maybe_push_to_top_level (d);
26837 mark_template_arguments_used (pattern, args);
26839 if (VAR_P (d))
26841 /* The variable might be a lambda's extra scope, and that
26842 lambda's visibility depends on D's. */
26843 maybe_commonize_var (d);
26844 determine_visibility (d);
26847 /* Mark D as instantiated so that recursive calls to
26848 instantiate_decl do not try to instantiate it again. */
26849 DECL_TEMPLATE_INSTANTIATED (d) = 1;
26851 if (td)
26852 /* Regenerate the declaration in case the template has been modified
26853 by a subsequent redeclaration. */
26854 regenerate_decl_from_template (d, td, args);
26856 /* We already set the file and line above. Reset them now in case
26857 they changed as a result of calling regenerate_decl_from_template. */
26858 input_location = DECL_SOURCE_LOCATION (d);
26860 if (VAR_P (d))
26862 /* Clear out DECL_RTL; whatever was there before may not be right
26863 since we've reset the type of the declaration. */
26864 SET_DECL_RTL (d, NULL);
26865 DECL_IN_AGGR_P (d) = 0;
26867 /* The initializer is placed in DECL_INITIAL by
26868 regenerate_decl_from_template so we don't need to
26869 push/pop_access_scope again here. Pull it out so that
26870 cp_finish_decl can process it. */
26871 bool const_init = false;
26872 tree init = DECL_INITIAL (d);
26873 DECL_INITIAL (d) = NULL_TREE;
26874 DECL_INITIALIZED_P (d) = 0;
26876 /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
26877 initializer. That function will defer actual emission until
26878 we have a chance to determine linkage. */
26879 DECL_EXTERNAL (d) = 0;
26881 /* Enter the scope of D so that access-checking works correctly. */
26882 bool enter_context = DECL_CLASS_SCOPE_P (d);
26883 if (enter_context)
26884 push_nested_class (DECL_CONTEXT (d));
26886 const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
26887 cp_finish_decl (d, init, const_init, NULL_TREE, 0);
26889 if (enter_context)
26890 pop_nested_class ();
26892 else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
26893 synthesize_method (d);
26894 else if (TREE_CODE (d) == FUNCTION_DECL)
26896 /* Set up the list of local specializations. */
26897 local_specialization_stack lss (push_to_top ? lss_blank : lss_copy);
26898 tree block = NULL_TREE;
26900 /* Set up context. */
26901 if (nested_p)
26902 block = push_stmt_list ();
26903 else
26905 start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
26907 perform_instantiation_time_access_checks (code_pattern, args);
26910 /* Create substitution entries for the parameters. */
26911 register_parameter_specializations (code_pattern, d);
26913 /* Substitute into the body of the function. */
26914 if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
26915 tsubst_omp_udr (DECL_SAVED_TREE (code_pattern), args,
26916 tf_warning_or_error, d);
26917 else
26919 tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
26920 tf_warning_or_error, DECL_TI_TEMPLATE (d));
26922 /* Set the current input_location to the end of the function
26923 so that finish_function knows where we are. */
26924 input_location
26925 = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
26927 /* Remember if we saw an infinite loop in the template. */
26928 current_function_infinite_loop
26929 = DECL_STRUCT_FUNCTION (code_pattern)->language->infinite_loop;
26932 /* Finish the function. */
26933 if (nested_p)
26934 DECL_SAVED_TREE (d) = pop_stmt_list (block);
26935 else
26937 d = finish_function (/*inline_p=*/false);
26938 expand_or_defer_fn (d);
26941 if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
26942 cp_check_omp_declare_reduction (d);
26945 /* We're not deferring instantiation any more. */
26946 if (!nested_p)
26947 TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
26949 maybe_pop_from_top_level (push_to_top);
26951 if (current_function_decl)
26952 restore_omp_privatization_clauses (omp_privatization_save);
26955 /* Produce the definition of D, a _DECL generated from a template. If
26956 DEFER_OK is true, then we don't have to actually do the
26957 instantiation now; we just have to do it sometime. Normally it is
26958 an error if this is an explicit instantiation but D is undefined.
26959 EXPL_INST_CLASS_MEM_P is true iff D is a member of an explicitly
26960 instantiated class template. */
26962 tree
26963 instantiate_decl (tree d, bool defer_ok, bool expl_inst_class_mem_p)
26965 tree tmpl = DECL_TI_TEMPLATE (d);
26966 tree gen_args;
26967 tree args;
26968 tree td;
26969 tree code_pattern;
26970 tree spec;
26971 tree gen_tmpl;
26972 bool pattern_defined;
26973 location_t saved_loc = input_location;
26974 int saved_unevaluated_operand = cp_unevaluated_operand;
26975 int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
26976 bool external_p;
26977 bool deleted_p;
26979 /* This function should only be used to instantiate templates for
26980 functions and static member variables. */
26981 gcc_assert (VAR_OR_FUNCTION_DECL_P (d));
26983 /* A concept is never instantiated. */
26984 gcc_assert (!DECL_DECLARED_CONCEPT_P (d));
26986 gcc_checking_assert (!DECL_FUNCTION_SCOPE_P (d));
26988 if (modules_p ())
26989 /* We may have a pending instantiation of D itself. */
26990 lazy_load_pendings (d);
26992 /* Variables are never deferred; if instantiation is required, they
26993 are instantiated right away. That allows for better code in the
26994 case that an expression refers to the value of the variable --
26995 if the variable has a constant value the referring expression can
26996 take advantage of that fact. */
26997 if (VAR_P (d))
26998 defer_ok = false;
27000 /* Don't instantiate cloned functions. Instead, instantiate the
27001 functions they cloned. */
27002 if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
27003 d = DECL_CLONED_FUNCTION (d);
27005 if (DECL_TEMPLATE_INSTANTIATED (d)
27006 || TREE_TYPE (d) == error_mark_node
27007 || (TREE_CODE (d) == FUNCTION_DECL
27008 && DECL_DEFAULTED_FN (d) && DECL_INITIAL (d))
27009 || DECL_TEMPLATE_SPECIALIZATION (d))
27010 /* D has already been instantiated or explicitly specialized, so
27011 there's nothing for us to do here.
27013 It might seem reasonable to check whether or not D is an explicit
27014 instantiation, and, if so, stop here. But when an explicit
27015 instantiation is deferred until the end of the compilation,
27016 DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
27017 the instantiation. */
27018 return d;
27020 /* Check to see whether we know that this template will be
27021 instantiated in some other file, as with "extern template"
27022 extension. */
27023 external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
27025 /* In general, we do not instantiate such templates. */
27026 if (external_p && !always_instantiate_p (d))
27027 return d;
27029 gen_tmpl = most_general_template (tmpl);
27030 gen_args = DECL_TI_ARGS (d);
27032 /* We should already have the extra args. */
27033 gcc_checking_assert (tmpl == gen_tmpl
27034 || (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
27035 == TMPL_ARGS_DEPTH (gen_args)));
27036 /* And what's in the hash table should match D. */
27037 gcc_checking_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0))
27038 == d
27039 || spec == NULL_TREE);
27041 /* This needs to happen before any tsubsting. */
27042 if (! push_tinst_level (d))
27043 return d;
27045 auto_timevar tv (TV_TEMPLATE_INST);
27047 /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
27048 for the instantiation. */
27049 td = template_for_substitution (d);
27050 args = gen_args;
27052 if (variable_template_specialization_p (d))
27054 /* Look up an explicit specialization, if any. */
27055 tree partial_ti = most_specialized_partial_spec (d, tf_warning_or_error);
27056 if (partial_ti && partial_ti != error_mark_node)
27058 td = TI_TEMPLATE (partial_ti);
27059 args = TI_ARGS (partial_ti);
27063 code_pattern = DECL_TEMPLATE_RESULT (td);
27065 /* We should never be trying to instantiate a member of a class
27066 template or partial specialization. */
27067 gcc_assert (d != code_pattern);
27069 if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
27070 || DECL_TEMPLATE_SPECIALIZATION (td))
27071 /* In the case of a friend template whose definition is provided
27072 outside the class, we may have too many arguments. Drop the
27073 ones we don't need. The same is true for specializations. */
27074 args = get_innermost_template_args
27075 (args, TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (td)));
27077 if (TREE_CODE (d) == FUNCTION_DECL)
27079 deleted_p = DECL_DELETED_FN (code_pattern);
27080 pattern_defined = ((DECL_SAVED_TREE (code_pattern) != NULL_TREE
27081 && DECL_INITIAL (code_pattern) != error_mark_node)
27082 || DECL_DEFAULTED_FN (code_pattern)
27083 || deleted_p);
27085 else
27087 deleted_p = false;
27088 if (DECL_CLASS_SCOPE_P (code_pattern))
27089 pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
27090 else
27091 pattern_defined = ! DECL_EXTERNAL (code_pattern);
27094 /* We may be in the middle of deferred access check. Disable it now. */
27095 push_deferring_access_checks (dk_no_deferred);
27097 /* Unless an explicit instantiation directive has already determined
27098 the linkage of D, remember that a definition is available for
27099 this entity. */
27100 if (pattern_defined
27101 && !DECL_INTERFACE_KNOWN (d)
27102 && !DECL_NOT_REALLY_EXTERN (d))
27103 mark_definable (d);
27105 DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
27106 DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
27107 input_location = DECL_SOURCE_LOCATION (d);
27109 /* If D is a member of an explicitly instantiated class template,
27110 and no definition is available, treat it like an implicit
27111 instantiation. */
27112 if (!pattern_defined && expl_inst_class_mem_p
27113 && DECL_EXPLICIT_INSTANTIATION (d))
27115 /* Leave linkage flags alone on instantiations with anonymous
27116 visibility. */
27117 if (TREE_PUBLIC (d))
27119 DECL_NOT_REALLY_EXTERN (d) = 0;
27120 DECL_INTERFACE_KNOWN (d) = 0;
27122 SET_DECL_IMPLICIT_INSTANTIATION (d);
27125 /* Defer all other templates, unless we have been explicitly
27126 forbidden from doing so. */
27127 if (/* If there is no definition, we cannot instantiate the
27128 template. */
27129 ! pattern_defined
27130 /* If it's OK to postpone instantiation, do so. */
27131 || defer_ok
27132 /* If this is a static data member that will be defined
27133 elsewhere, we don't want to instantiate the entire data
27134 member, but we do want to instantiate the initializer so that
27135 we can substitute that elsewhere. */
27136 || (external_p && VAR_P (d))
27137 /* Handle here a deleted function too, avoid generating
27138 its body (c++/61080). */
27139 || deleted_p)
27141 /* The definition of the static data member is now required so
27142 we must substitute the initializer. */
27143 if (VAR_P (d)
27144 && !DECL_INITIAL (d)
27145 && DECL_INITIAL (code_pattern))
27147 tree ns;
27148 tree init;
27149 bool const_init = false;
27150 bool enter_context = DECL_CLASS_SCOPE_P (d);
27152 ns = decl_namespace_context (d);
27153 push_nested_namespace (ns);
27154 if (enter_context)
27155 push_nested_class (DECL_CONTEXT (d));
27156 init = tsubst_expr (DECL_INITIAL (code_pattern),
27157 args,
27158 tf_warning_or_error, NULL_TREE);
27159 /* If instantiating the initializer involved instantiating this
27160 again, don't call cp_finish_decl twice. */
27161 if (!DECL_INITIAL (d))
27163 /* Make sure the initializer is still constant, in case of
27164 circular dependency (template/instantiate6.C). */
27165 const_init
27166 = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
27167 cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
27168 /*asmspec_tree=*/NULL_TREE, 0);
27170 if (enter_context)
27171 pop_nested_class ();
27172 pop_nested_namespace (ns);
27175 /* We restore the source position here because it's used by
27176 add_pending_template. */
27177 input_location = saved_loc;
27179 if (at_eof && !pattern_defined
27180 && DECL_EXPLICIT_INSTANTIATION (d)
27181 && DECL_NOT_REALLY_EXTERN (d))
27182 /* [temp.explicit]
27184 The definition of a non-exported function template, a
27185 non-exported member function template, or a non-exported
27186 member function or static data member of a class template
27187 shall be present in every translation unit in which it is
27188 explicitly instantiated. */
27189 permerror (input_location, "explicit instantiation of %qD "
27190 "but no definition available", d);
27192 /* If we're in unevaluated context, we just wanted to get the
27193 constant value; this isn't an odr use, so don't queue
27194 a full instantiation. */
27195 if (!cp_unevaluated_operand
27196 /* ??? Historically, we have instantiated inline functions, even
27197 when marked as "extern template". */
27198 && !(external_p && VAR_P (d)))
27199 add_pending_template (d);
27201 else
27203 set_instantiating_module (d);
27204 if (variable_template_p (gen_tmpl))
27205 note_variable_template_instantiation (d);
27206 instantiate_body (td, args, d, false);
27209 pop_deferring_access_checks ();
27210 pop_tinst_level ();
27211 input_location = saved_loc;
27212 cp_unevaluated_operand = saved_unevaluated_operand;
27213 c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
27215 return d;
27218 /* Run through the list of templates that we wish we could
27219 instantiate, and instantiate any we can. RETRIES is the
27220 number of times we retry pending template instantiation. */
27222 void
27223 instantiate_pending_templates (int retries)
27225 int reconsider;
27226 location_t saved_loc = input_location;
27228 /* Instantiating templates may trigger vtable generation. This in turn
27229 may require further template instantiations. We place a limit here
27230 to avoid infinite loop. */
27231 if (pending_templates && retries >= max_tinst_depth)
27233 tree decl = pending_templates->tinst->maybe_get_node ();
27235 fatal_error (input_location,
27236 "template instantiation depth exceeds maximum of %d"
27237 " instantiating %q+D, possibly from virtual table generation"
27238 " (use %<-ftemplate-depth=%> to increase the maximum)",
27239 max_tinst_depth, decl);
27240 if (TREE_CODE (decl) == FUNCTION_DECL)
27241 /* Pretend that we defined it. */
27242 DECL_INITIAL (decl) = error_mark_node;
27243 return;
27248 struct pending_template **t = &pending_templates;
27249 struct pending_template *last = NULL;
27250 reconsider = 0;
27251 while (*t)
27253 tree instantiation = reopen_tinst_level ((*t)->tinst);
27254 bool complete = false;
27256 if (TYPE_P (instantiation))
27258 if (!COMPLETE_TYPE_P (instantiation))
27260 instantiate_class_template (instantiation);
27261 if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
27262 for (tree fld = TYPE_FIELDS (instantiation);
27263 fld; fld = TREE_CHAIN (fld))
27264 if ((VAR_P (fld)
27265 || (TREE_CODE (fld) == FUNCTION_DECL
27266 && !DECL_ARTIFICIAL (fld)))
27267 && DECL_TEMPLATE_INSTANTIATION (fld))
27268 instantiate_decl (fld,
27269 /*defer_ok=*/false,
27270 /*expl_inst_class_mem_p=*/false);
27272 if (COMPLETE_TYPE_P (instantiation))
27273 reconsider = 1;
27276 complete = COMPLETE_TYPE_P (instantiation);
27278 else
27280 if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
27281 && !DECL_TEMPLATE_INSTANTIATED (instantiation))
27283 instantiation
27284 = instantiate_decl (instantiation,
27285 /*defer_ok=*/false,
27286 /*expl_inst_class_mem_p=*/false);
27287 if (DECL_TEMPLATE_INSTANTIATED (instantiation))
27288 reconsider = 1;
27291 complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
27292 || DECL_TEMPLATE_INSTANTIATED (instantiation));
27295 if (complete)
27297 /* If INSTANTIATION has been instantiated, then we don't
27298 need to consider it again in the future. */
27299 struct pending_template *drop = *t;
27300 *t = (*t)->next;
27301 set_refcount_ptr (drop->tinst);
27302 pending_template_freelist ().free (drop);
27304 else
27306 last = *t;
27307 t = &(*t)->next;
27309 tinst_depth = 0;
27310 set_refcount_ptr (current_tinst_level);
27312 last_pending_template = last;
27314 while (reconsider);
27316 input_location = saved_loc;
27319 /* Substitute ARGVEC into T, which is a list of initializers for
27320 either base class or a non-static data member. The TREE_PURPOSEs
27321 are DECLs, and the TREE_VALUEs are the initializer values. Used by
27322 instantiate_decl. */
27324 static tree
27325 tsubst_initializer_list (tree t, tree argvec)
27327 tree inits = NULL_TREE;
27328 tree target_ctor = error_mark_node;
27330 for (; t; t = TREE_CHAIN (t))
27332 tree decl;
27333 tree init;
27334 tree expanded_bases = NULL_TREE;
27335 tree expanded_arguments = NULL_TREE;
27336 int i, len = 1;
27338 if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
27340 tree expr;
27341 tree arg;
27343 /* Expand the base class expansion type into separate base
27344 classes. */
27345 expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
27346 tf_warning_or_error,
27347 NULL_TREE);
27348 if (expanded_bases == error_mark_node)
27349 continue;
27351 /* We'll be building separate TREE_LISTs of arguments for
27352 each base. */
27353 len = TREE_VEC_LENGTH (expanded_bases);
27354 expanded_arguments = make_tree_vec (len);
27355 for (i = 0; i < len; i++)
27356 TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
27358 /* Build a dummy EXPR_PACK_EXPANSION that will be used to
27359 expand each argument in the TREE_VALUE of t. */
27360 expr = make_node (EXPR_PACK_EXPANSION);
27361 PACK_EXPANSION_LOCAL_P (expr) = true;
27362 PACK_EXPANSION_PARAMETER_PACKS (expr) =
27363 PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
27365 if (TREE_VALUE (t) == void_type_node)
27366 /* VOID_TYPE_NODE is used to indicate
27367 value-initialization. */
27369 for (i = 0; i < len; i++)
27370 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
27372 else
27374 /* Substitute parameter packs into each argument in the
27375 TREE_LIST. */
27376 in_base_initializer = 1;
27377 for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
27379 tree expanded_exprs;
27381 /* Expand the argument. */
27382 tree value;
27383 if (TREE_CODE (TREE_VALUE (arg)) == EXPR_PACK_EXPANSION)
27384 value = TREE_VALUE (arg);
27385 else
27387 value = expr;
27388 PACK_EXPANSION_PATTERN (value) = TREE_VALUE (arg);
27390 expanded_exprs
27391 = tsubst_pack_expansion (value, argvec,
27392 tf_warning_or_error,
27393 NULL_TREE);
27394 if (expanded_exprs == error_mark_node)
27395 continue;
27397 /* Prepend each of the expanded expressions to the
27398 corresponding TREE_LIST in EXPANDED_ARGUMENTS. */
27399 for (i = 0; i < len; i++)
27400 if (TREE_CODE (TREE_VALUE (arg)) == EXPR_PACK_EXPANSION)
27401 for (int j = 0; j < TREE_VEC_LENGTH (expanded_exprs); j++)
27402 TREE_VEC_ELT (expanded_arguments, i)
27403 = tree_cons (NULL_TREE,
27404 TREE_VEC_ELT (expanded_exprs, j),
27405 TREE_VEC_ELT (expanded_arguments, i));
27406 else
27407 TREE_VEC_ELT (expanded_arguments, i)
27408 = tree_cons (NULL_TREE,
27409 TREE_VEC_ELT (expanded_exprs, i),
27410 TREE_VEC_ELT (expanded_arguments, i));
27412 in_base_initializer = 0;
27414 /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
27415 since we built them backwards. */
27416 for (i = 0; i < len; i++)
27418 TREE_VEC_ELT (expanded_arguments, i) =
27419 nreverse (TREE_VEC_ELT (expanded_arguments, i));
27424 for (i = 0; i < len; ++i)
27426 if (expanded_bases)
27428 decl = TREE_VEC_ELT (expanded_bases, i);
27429 decl = expand_member_init (decl);
27430 init = TREE_VEC_ELT (expanded_arguments, i);
27432 else
27434 tree tmp;
27435 decl = tsubst_copy (TREE_PURPOSE (t), argvec,
27436 tf_warning_or_error, NULL_TREE);
27438 decl = expand_member_init (decl);
27439 if (decl && !DECL_P (decl))
27440 in_base_initializer = 1;
27442 init = TREE_VALUE (t);
27443 tmp = init;
27444 if (init != void_type_node)
27445 init = tsubst_expr (init, argvec,
27446 tf_warning_or_error, NULL_TREE);
27447 if (init == NULL_TREE && tmp != NULL_TREE)
27448 /* If we had an initializer but it instantiated to nothing,
27449 value-initialize the object. This will only occur when
27450 the initializer was a pack expansion where the parameter
27451 packs used in that expansion were of length zero. */
27452 init = void_type_node;
27453 in_base_initializer = 0;
27456 if (target_ctor != error_mark_node
27457 && init != error_mark_node)
27459 error ("mem-initializer for %qD follows constructor delegation",
27460 decl);
27461 return inits;
27463 /* Look for a target constructor. */
27464 if (init != error_mark_node
27465 && decl && CLASS_TYPE_P (decl)
27466 && same_type_p (decl, current_class_type))
27468 maybe_warn_cpp0x (CPP0X_DELEGATING_CTORS);
27469 if (inits)
27471 error ("constructor delegation follows mem-initializer for %qD",
27472 TREE_PURPOSE (inits));
27473 continue;
27475 target_ctor = init;
27478 if (decl)
27480 init = build_tree_list (decl, init);
27481 /* Carry over the dummy TREE_TYPE node containing the source
27482 location. */
27483 TREE_TYPE (init) = TREE_TYPE (t);
27484 TREE_CHAIN (init) = inits;
27485 inits = init;
27489 return inits;
27492 /* Instantiate an enumerated type. TAG is the template type, NEWTAG
27493 is the instantiation (which should have been created with
27494 start_enum) and ARGS are the template arguments to use. */
27496 static void
27497 tsubst_enum (tree tag, tree newtag, tree args)
27499 tree e;
27501 if (SCOPED_ENUM_P (newtag))
27502 begin_scope (sk_scoped_enum, newtag);
27504 for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
27506 tree value;
27507 tree decl = TREE_VALUE (e);
27509 /* Note that in a template enum, the TREE_VALUE is the
27510 CONST_DECL, not the corresponding INTEGER_CST. */
27511 value = tsubst_expr (DECL_INITIAL (decl),
27512 args, tf_warning_or_error, NULL_TREE);
27514 /* Give this enumeration constant the correct access. */
27515 set_current_access_from_decl (decl);
27517 /* Actually build the enumerator itself. Here we're assuming that
27518 enumerators can't have dependent attributes. */
27519 tree newdecl = build_enumerator (DECL_NAME (decl), value, newtag,
27520 DECL_ATTRIBUTES (decl),
27521 DECL_SOURCE_LOCATION (decl));
27522 /* Attribute deprecated without an argument isn't sticky: it'll
27523 melt into a tree flag, so we need to propagate the flag here,
27524 since we just created a new enumerator. */
27525 TREE_DEPRECATED (newdecl) = TREE_DEPRECATED (decl);
27526 TREE_UNAVAILABLE (newdecl) = TREE_UNAVAILABLE (decl);
27529 if (SCOPED_ENUM_P (newtag))
27530 finish_scope ();
27532 finish_enum_value_list (newtag);
27533 finish_enum (newtag);
27535 DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
27536 = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
27537 TREE_DEPRECATED (newtag) = TREE_DEPRECATED (tag);
27538 TREE_UNAVAILABLE (newtag) = TREE_UNAVAILABLE (tag);
27541 /* DECL is a FUNCTION_DECL that is a template specialization. Return
27542 its type -- but without substituting the innermost set of template
27543 arguments. So, innermost set of template parameters will appear in
27544 the type. */
27546 tree
27547 get_mostly_instantiated_function_type (tree decl)
27549 /* For a function, DECL_TI_TEMPLATE is partially instantiated. */
27550 return TREE_TYPE (DECL_TI_TEMPLATE (decl));
27553 /* Return truthvalue if we're processing a template different from
27554 the last one involved in diagnostics. */
27555 bool
27556 problematic_instantiation_changed (void)
27558 return current_tinst_level != last_error_tinst_level;
27561 /* Remember current template involved in diagnostics. */
27562 void
27563 record_last_problematic_instantiation (void)
27565 set_refcount_ptr (last_error_tinst_level, current_tinst_level);
27568 struct tinst_level *
27569 current_instantiation (void)
27571 return current_tinst_level;
27574 /* Return TRUE if current_function_decl is being instantiated, false
27575 otherwise. */
27577 bool
27578 instantiating_current_function_p (void)
27580 return (current_instantiation ()
27581 && (current_instantiation ()->maybe_get_node ()
27582 == current_function_decl));
27585 /* [temp.param] Check that template non-type parm TYPE is of an allowable
27586 type. Return false for ok, true for disallowed. Issue error and
27587 inform messages under control of COMPLAIN. */
27589 static bool
27590 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
27592 if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
27593 return false;
27594 else if (TYPE_PTR_P (type))
27595 return false;
27596 else if (TYPE_REF_P (type)
27597 && !TYPE_REF_IS_RVALUE (type))
27598 return false;
27599 else if (TYPE_PTRMEM_P (type))
27600 return false;
27601 else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
27603 if (CLASS_PLACEHOLDER_TEMPLATE (type) && cxx_dialect < cxx20)
27605 if (complain & tf_error)
27606 error ("non-type template parameters of deduced class type only "
27607 "available with %<-std=c++20%> or %<-std=gnu++20%>");
27608 return true;
27610 return false;
27612 else if (TREE_CODE (type) == NULLPTR_TYPE)
27613 return false;
27614 else if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM
27615 && cxx_dialect < cxx11)
27616 /* Fall through; before C++11 alias templates, a bound ttp
27617 always instantiates into a class type. */;
27618 else if (WILDCARD_TYPE_P (type))
27619 /* Any other wildcard type not already handled above is allowed. */
27620 return false;
27621 else if (TREE_CODE (type) == COMPLEX_TYPE)
27622 /* Fall through. */;
27623 else if (VOID_TYPE_P (type))
27624 /* Fall through. */;
27625 else if (cxx_dialect >= cxx20)
27627 if (dependent_type_p (type))
27628 return false;
27629 if (!complete_type_or_maybe_complain (type, NULL_TREE, complain))
27630 return true;
27631 if (structural_type_p (type))
27632 return false;
27633 if (complain & tf_error)
27635 auto_diagnostic_group d;
27636 error ("%qT is not a valid type for a template non-type "
27637 "parameter because it is not structural", type);
27638 structural_type_p (type, true);
27640 return true;
27642 else if (CLASS_TYPE_P (type))
27644 if (complain & tf_error)
27645 error ("non-type template parameters of class type only available "
27646 "with %<-std=c++20%> or %<-std=gnu++20%>");
27647 return true;
27650 if (complain & tf_error)
27652 if (type == error_mark_node)
27653 inform (input_location, "invalid template non-type parameter");
27654 else
27655 error ("%q#T is not a valid type for a template non-type parameter",
27656 type);
27658 return true;
27661 /* Returns true iff the noexcept-specifier for TYPE is value-dependent. */
27663 static bool
27664 value_dependent_noexcept_spec_p (tree type)
27666 if (tree spec = TYPE_RAISES_EXCEPTIONS (type))
27667 if (tree noex = TREE_PURPOSE (spec))
27668 /* Treat DEFERRED_NOEXCEPT as non-dependent, since it doesn't
27669 affect overload resolution and treating it as dependent breaks
27670 things. Same for an unparsed noexcept expression. */
27671 if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
27672 && TREE_CODE (noex) != DEFERRED_PARSE
27673 && value_dependent_expression_p (noex))
27674 return true;
27676 return false;
27679 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
27680 Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
27682 static bool
27683 dependent_type_p_r (tree type)
27685 tree scope;
27687 /* [temp.dep.type]
27689 A type is dependent if it is:
27691 -- a template parameter. Template template parameters are types
27692 for us (since TYPE_P holds true for them) so we handle
27693 them here. */
27694 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
27695 || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
27696 return true;
27697 /* -- a qualified-id with a nested-name-specifier which contains a
27698 class-name that names a dependent type or whose unqualified-id
27699 names a dependent type. */
27700 if (TREE_CODE (type) == TYPENAME_TYPE)
27701 return true;
27703 /* An alias template specialization can be dependent even if the
27704 resulting type is not. */
27705 if (dependent_alias_template_spec_p (type, nt_transparent))
27706 return true;
27708 /* -- a cv-qualified type where the cv-unqualified type is
27709 dependent.
27710 No code is necessary for this bullet; the code below handles
27711 cv-qualified types, and we don't want to strip aliases with
27712 TYPE_MAIN_VARIANT because of DR 1558. */
27713 /* -- a compound type constructed from any dependent type. */
27714 if (TYPE_PTRMEM_P (type))
27715 return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
27716 || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
27717 (type)));
27718 else if (INDIRECT_TYPE_P (type))
27719 return dependent_type_p (TREE_TYPE (type));
27720 else if (FUNC_OR_METHOD_TYPE_P (type))
27722 tree arg_type;
27724 if (dependent_type_p (TREE_TYPE (type)))
27725 return true;
27726 for (arg_type = TYPE_ARG_TYPES (type);
27727 arg_type;
27728 arg_type = TREE_CHAIN (arg_type))
27729 if (dependent_type_p (TREE_VALUE (arg_type)))
27730 return true;
27731 if (cxx_dialect >= cxx17
27732 && value_dependent_noexcept_spec_p (type))
27733 /* A value-dependent noexcept-specifier makes the type dependent. */
27734 return true;
27735 return false;
27737 /* -- an array type constructed from any dependent type or whose
27738 size is specified by a constant expression that is
27739 value-dependent.
27741 We checked for type- and value-dependence of the bounds in
27742 compute_array_index_type, so TYPE_DEPENDENT_P is already set. */
27743 if (TREE_CODE (type) == ARRAY_TYPE)
27745 if (TYPE_DOMAIN (type)
27746 && dependent_type_p (TYPE_DOMAIN (type)))
27747 return true;
27748 return dependent_type_p (TREE_TYPE (type));
27751 /* -- a template-id in which either the template name is a template
27752 parameter ... */
27753 if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
27754 return true;
27755 /* ... or any of the template arguments is a dependent type or
27756 an expression that is type-dependent or value-dependent. */
27757 else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
27758 && (any_dependent_template_arguments_p
27759 (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
27760 return true;
27762 /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and TRAIT_TYPEs are
27763 dependent; if the argument of the `typeof' expression is not
27764 type-dependent, then it should already been have resolved. */
27765 if (TREE_CODE (type) == TYPEOF_TYPE
27766 || TREE_CODE (type) == DECLTYPE_TYPE
27767 || TREE_CODE (type) == TRAIT_TYPE)
27768 return true;
27770 /* A template argument pack is dependent if any of its packed
27771 arguments are. */
27772 if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
27774 tree args = ARGUMENT_PACK_ARGS (type);
27775 for (tree arg : tree_vec_range (args))
27776 if (dependent_template_arg_p (arg))
27777 return true;
27780 /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
27781 be template parameters. */
27782 if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
27783 return true;
27785 if (TREE_CODE (type) == DEPENDENT_OPERATOR_TYPE)
27786 return true;
27788 if (any_dependent_type_attributes_p (TYPE_ATTRIBUTES (type)))
27789 return true;
27791 /* The standard does not specifically mention types that are local
27792 to template functions or local classes, but they should be
27793 considered dependent too. For example:
27795 template <int I> void f() {
27796 enum E { a = I };
27797 S<sizeof (E)> s;
27800 The size of `E' cannot be known until the value of `I' has been
27801 determined. Therefore, `E' must be considered dependent. */
27802 scope = TYPE_CONTEXT (type);
27803 if (scope && TYPE_P (scope))
27804 return dependent_type_p (scope);
27805 /* Don't use type_dependent_expression_p here, as it can lead
27806 to infinite recursion trying to determine whether a lambda
27807 nested in a lambda is dependent (c++/47687). */
27808 else if (scope && TREE_CODE (scope) == FUNCTION_DECL
27809 && DECL_LANG_SPECIFIC (scope)
27810 && DECL_TEMPLATE_INFO (scope)
27811 && (any_dependent_template_arguments_p
27812 (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
27813 return true;
27815 /* Other types are non-dependent. */
27816 return false;
27819 /* Returns TRUE if TYPE is dependent, in the sense of
27820 [temp.dep.type]. Note that a NULL type is considered dependent. */
27822 bool
27823 dependent_type_p (tree type)
27825 /* If there are no template parameters in scope, then there can't be
27826 any dependent types. */
27827 if (!processing_template_decl)
27829 /* If we are not processing a template, then nobody should be
27830 providing us with a dependent type. */
27831 gcc_assert (type);
27832 gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
27833 return false;
27836 /* If the type is NULL, we have not computed a type for the entity
27837 in question; in that case, the type is dependent. */
27838 if (!type)
27839 return true;
27841 /* Erroneous types can be considered non-dependent. */
27842 if (type == error_mark_node)
27843 return false;
27845 /* If we have not already computed the appropriate value for TYPE,
27846 do so now. */
27847 if (!TYPE_DEPENDENT_P_VALID (type))
27849 TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
27850 TYPE_DEPENDENT_P_VALID (type) = 1;
27853 return TYPE_DEPENDENT_P (type);
27856 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
27857 lookup. In other words, a dependent type that is not the current
27858 instantiation. */
27860 bool
27861 dependent_scope_p (tree scope)
27863 return (scope && TYPE_P (scope) && dependent_type_p (scope)
27864 && !currently_open_class (scope));
27867 /* True if we might find more declarations in SCOPE during instantiation than
27868 we can when parsing the template. */
27870 bool
27871 dependentish_scope_p (tree scope)
27873 return dependent_scope_p (scope) || any_dependent_bases_p (scope);
27876 /* T is a SCOPE_REF. Return whether it represents a non-static member of
27877 an unknown base of 'this' (and is therefore instantiation-dependent). */
27879 static bool
27880 unknown_base_ref_p (tree t)
27882 if (!current_class_ptr)
27883 return false;
27885 tree mem = TREE_OPERAND (t, 1);
27886 if (shared_member_p (mem))
27887 return false;
27889 tree cur = current_nonlambda_class_type ();
27890 if (!any_dependent_bases_p (cur))
27891 return false;
27893 tree ctx = TREE_OPERAND (t, 0);
27894 if (DERIVED_FROM_P (ctx, cur))
27895 return false;
27897 return true;
27900 /* T is a SCOPE_REF; return whether we need to consider it
27901 instantiation-dependent so that we can check access at instantiation
27902 time even though we know which member it resolves to. */
27904 static bool
27905 instantiation_dependent_scope_ref_p (tree t)
27907 if (DECL_P (TREE_OPERAND (t, 1))
27908 && CLASS_TYPE_P (TREE_OPERAND (t, 0))
27909 && !dependent_scope_p (TREE_OPERAND (t, 0))
27910 && !unknown_base_ref_p (t)
27911 && accessible_in_template_p (TREE_OPERAND (t, 0),
27912 TREE_OPERAND (t, 1)))
27913 return false;
27914 else
27915 return true;
27918 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
27919 [temp.dep.constexpr]. EXPRESSION is already known to be a constant
27920 expression. */
27922 /* Note that this predicate is not appropriate for general expressions;
27923 only constant expressions (that satisfy potential_constant_expression)
27924 can be tested for value dependence. */
27926 bool
27927 value_dependent_expression_p (tree expression)
27929 if (!processing_template_decl || expression == NULL_TREE)
27930 return false;
27932 /* A type-dependent expression is also value-dependent. */
27933 if (type_dependent_expression_p (expression))
27934 return true;
27936 switch (TREE_CODE (expression))
27938 case BASELINK:
27939 /* A dependent member function of the current instantiation. */
27940 return dependent_type_p (BINFO_TYPE (BASELINK_BINFO (expression)));
27942 case FUNCTION_DECL:
27943 /* A dependent member function of the current instantiation. */
27944 if (DECL_CLASS_SCOPE_P (expression)
27945 && dependent_type_p (DECL_CONTEXT (expression)))
27946 return true;
27947 break;
27949 case IDENTIFIER_NODE:
27950 /* A name that has not been looked up -- must be dependent. */
27951 return true;
27953 case TEMPLATE_PARM_INDEX:
27954 /* A non-type template parm. */
27955 return true;
27957 case CONST_DECL:
27958 /* A non-type template parm. */
27959 if (DECL_TEMPLATE_PARM_P (expression))
27960 return true;
27961 return value_dependent_expression_p (DECL_INITIAL (expression));
27963 case VAR_DECL:
27964 /* A constant with literal type and is initialized
27965 with an expression that is value-dependent. */
27966 if (DECL_DEPENDENT_INIT_P (expression))
27967 return true;
27968 if (DECL_HAS_VALUE_EXPR_P (expression))
27970 tree value_expr = DECL_VALUE_EXPR (expression);
27971 if (value_dependent_expression_p (value_expr)
27972 /* __PRETTY_FUNCTION__ inside a template function is dependent
27973 on the name of the function. */
27974 || (DECL_PRETTY_FUNCTION_P (expression)
27975 /* It might be used in a template, but not a template
27976 function, in which case its DECL_VALUE_EXPR will be
27977 "top level". */
27978 && value_expr == error_mark_node))
27979 return true;
27981 else if (TYPE_REF_P (TREE_TYPE (expression)))
27982 /* FIXME cp_finish_decl doesn't fold reference initializers. */
27983 return true;
27984 return false;
27986 case DYNAMIC_CAST_EXPR:
27987 case STATIC_CAST_EXPR:
27988 case CONST_CAST_EXPR:
27989 case REINTERPRET_CAST_EXPR:
27990 case CAST_EXPR:
27991 case IMPLICIT_CONV_EXPR:
27992 /* These expressions are value-dependent if the type to which
27993 the cast occurs is dependent or the expression being casted
27994 is value-dependent. */
27996 tree type = TREE_TYPE (expression);
27998 if (dependent_type_p (type))
27999 return true;
28001 /* A functional cast has a list of operands. */
28002 expression = TREE_OPERAND (expression, 0);
28003 if (!expression)
28005 /* If there are no operands, it must be an expression such
28006 as "int()". This should not happen for aggregate types
28007 because it would form non-constant expressions. */
28008 gcc_assert (cxx_dialect >= cxx11
28009 || INTEGRAL_OR_ENUMERATION_TYPE_P (type));
28011 return false;
28014 if (TREE_CODE (expression) == TREE_LIST)
28015 return any_value_dependent_elements_p (expression);
28017 if (TREE_CODE (type) == REFERENCE_TYPE
28018 && has_value_dependent_address (expression))
28019 return true;
28021 return value_dependent_expression_p (expression);
28024 case SIZEOF_EXPR:
28025 if (SIZEOF_EXPR_TYPE_P (expression))
28026 return dependent_type_p (TREE_TYPE (TREE_OPERAND (expression, 0)));
28027 /* FALLTHRU */
28028 case ALIGNOF_EXPR:
28029 case TYPEID_EXPR:
28030 /* A `sizeof' expression is value-dependent if the operand is
28031 type-dependent or is a pack expansion. */
28032 expression = TREE_OPERAND (expression, 0);
28033 if (PACK_EXPANSION_P (expression))
28034 return true;
28035 else if (TYPE_P (expression))
28036 return dependent_type_p (expression);
28037 return instantiation_dependent_uneval_expression_p (expression);
28039 case AT_ENCODE_EXPR:
28040 /* An 'encode' expression is value-dependent if the operand is
28041 type-dependent. */
28042 expression = TREE_OPERAND (expression, 0);
28043 return dependent_type_p (expression);
28045 case NOEXCEPT_EXPR:
28046 expression = TREE_OPERAND (expression, 0);
28047 return instantiation_dependent_uneval_expression_p (expression);
28049 case SCOPE_REF:
28050 /* All instantiation-dependent expressions should also be considered
28051 value-dependent. */
28052 return instantiation_dependent_scope_ref_p (expression);
28054 case COMPONENT_REF:
28055 return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
28056 || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
28058 case NONTYPE_ARGUMENT_PACK:
28059 /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
28060 is value-dependent. */
28061 for (tree arg : tree_vec_range (ARGUMENT_PACK_ARGS (expression)))
28062 if (value_dependent_expression_p (arg))
28063 return true;
28064 return false;
28066 case TRAIT_EXPR:
28068 if (dependent_type_p (TRAIT_EXPR_TYPE1 (expression)))
28069 return true;
28071 tree type2 = TRAIT_EXPR_TYPE2 (expression);
28072 if (!type2)
28073 return false;
28075 if (TREE_CODE (type2) != TREE_VEC)
28076 return dependent_type_p (type2);
28078 for (tree arg : tree_vec_range (type2))
28079 if (dependent_type_p (arg))
28080 return true;
28082 return false;
28085 case MODOP_EXPR:
28086 return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
28087 || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
28089 case ARRAY_REF:
28090 return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
28091 || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
28093 case ADDR_EXPR:
28095 tree op = TREE_OPERAND (expression, 0);
28096 return (value_dependent_expression_p (op)
28097 || has_value_dependent_address (op));
28100 case REQUIRES_EXPR:
28101 /* Treat all requires-expressions as value-dependent so
28102 we don't try to fold them. */
28103 return true;
28105 case TYPE_REQ:
28106 return dependent_type_p (TREE_OPERAND (expression, 0));
28108 case CALL_EXPR:
28110 if (value_dependent_expression_p (CALL_EXPR_FN (expression)))
28111 return true;
28112 tree fn = get_callee_fndecl (expression);
28113 int i, nargs;
28114 nargs = call_expr_nargs (expression);
28115 for (i = 0; i < nargs; ++i)
28117 tree op = CALL_EXPR_ARG (expression, i);
28118 /* In a call to a constexpr member function, look through the
28119 implicit ADDR_EXPR on the object argument so that it doesn't
28120 cause the call to be considered value-dependent. We also
28121 look through it in potential_constant_expression. */
28122 if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
28123 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
28124 && TREE_CODE (op) == ADDR_EXPR)
28125 op = TREE_OPERAND (op, 0);
28126 if (value_dependent_expression_p (op))
28127 return true;
28129 return false;
28132 case TEMPLATE_ID_EXPR:
28133 return concept_definition_p (TREE_OPERAND (expression, 0))
28134 && any_dependent_template_arguments_p (TREE_OPERAND (expression, 1));
28136 case CONSTRUCTOR:
28138 unsigned ix;
28139 tree val;
28140 if (dependent_type_p (TREE_TYPE (expression)))
28141 return true;
28142 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
28143 if (value_dependent_expression_p (val))
28144 return true;
28145 return false;
28148 case STMT_EXPR:
28149 /* Treat a GNU statement expression as dependent to avoid crashing
28150 under instantiate_non_dependent_expr; it can't be constant. */
28151 return true;
28153 case NEW_EXPR:
28154 case VEC_NEW_EXPR:
28155 /* The second operand is a type, which type_dependent_expression_p
28156 (and therefore value_dependent_expression_p) doesn't want to see. */
28157 return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
28158 || value_dependent_expression_p (TREE_OPERAND (expression, 2))
28159 || value_dependent_expression_p (TREE_OPERAND (expression, 3)));
28161 default:
28162 /* A constant expression is value-dependent if any subexpression is
28163 value-dependent. */
28164 switch (TREE_CODE_CLASS (TREE_CODE (expression)))
28166 case tcc_reference:
28167 case tcc_unary:
28168 case tcc_comparison:
28169 case tcc_binary:
28170 case tcc_expression:
28171 case tcc_vl_exp:
28173 int i, len = cp_tree_operand_length (expression);
28175 for (i = 0; i < len; i++)
28177 tree t = TREE_OPERAND (expression, i);
28179 /* In some cases, some of the operands may be missing.
28180 (For example, in the case of PREDECREMENT_EXPR, the
28181 amount to increment by may be missing.) That doesn't
28182 make the expression dependent. */
28183 if (t && value_dependent_expression_p (t))
28184 return true;
28187 break;
28188 default:
28189 break;
28191 break;
28194 /* The expression is not value-dependent. */
28195 return false;
28198 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
28199 [temp.dep.expr]. Note that an expression with no type is
28200 considered dependent. Other parts of the compiler arrange for an
28201 expression with type-dependent subexpressions to have no type, so
28202 this function doesn't have to be fully recursive. */
28204 bool
28205 type_dependent_expression_p (tree expression)
28207 if (!processing_template_decl)
28208 return false;
28210 if (expression == NULL_TREE || expression == error_mark_node)
28211 return false;
28213 gcc_checking_assert (!TYPE_P (expression));
28215 STRIP_ANY_LOCATION_WRAPPER (expression);
28217 /* An unresolved name is always dependent. */
28218 if (identifier_p (expression)
28219 || TREE_CODE (expression) == USING_DECL
28220 || TREE_CODE (expression) == WILDCARD_DECL)
28221 return true;
28223 /* A lambda-expression in template context is dependent. dependent_type_p is
28224 true for a lambda in the scope of a class or function template, but that
28225 doesn't cover all template contexts, like a default template argument. */
28226 if (TREE_CODE (expression) == LAMBDA_EXPR)
28227 return true;
28229 /* A fold expression is type-dependent. */
28230 if (TREE_CODE (expression) == UNARY_LEFT_FOLD_EXPR
28231 || TREE_CODE (expression) == UNARY_RIGHT_FOLD_EXPR
28232 || TREE_CODE (expression) == BINARY_LEFT_FOLD_EXPR
28233 || TREE_CODE (expression) == BINARY_RIGHT_FOLD_EXPR)
28234 return true;
28236 /* Some expression forms are never type-dependent. */
28237 if (TREE_CODE (expression) == SIZEOF_EXPR
28238 || TREE_CODE (expression) == ALIGNOF_EXPR
28239 || TREE_CODE (expression) == AT_ENCODE_EXPR
28240 || TREE_CODE (expression) == NOEXCEPT_EXPR
28241 || TREE_CODE (expression) == TRAIT_EXPR
28242 || TREE_CODE (expression) == TYPEID_EXPR
28243 || TREE_CODE (expression) == DELETE_EXPR
28244 || TREE_CODE (expression) == VEC_DELETE_EXPR
28245 || TREE_CODE (expression) == THROW_EXPR
28246 || TREE_CODE (expression) == REQUIRES_EXPR)
28247 return false;
28249 /* The types of these expressions depends only on the type to which
28250 the cast occurs. */
28251 if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
28252 || TREE_CODE (expression) == STATIC_CAST_EXPR
28253 || TREE_CODE (expression) == CONST_CAST_EXPR
28254 || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
28255 || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
28256 || TREE_CODE (expression) == CAST_EXPR)
28257 return dependent_type_p (TREE_TYPE (expression));
28259 /* The types of these expressions depends only on the type created
28260 by the expression. */
28261 if (TREE_CODE (expression) == NEW_EXPR
28262 || TREE_CODE (expression) == VEC_NEW_EXPR)
28264 /* For NEW_EXPR tree nodes created inside a template, either
28265 the object type itself or a TREE_LIST may appear as the
28266 operand 1. */
28267 tree type = TREE_OPERAND (expression, 1);
28268 if (TREE_CODE (type) == TREE_LIST)
28269 /* This is an array type. We need to check array dimensions
28270 as well. */
28271 return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
28272 || value_dependent_expression_p
28273 (TREE_OPERAND (TREE_VALUE (type), 1));
28274 /* Array type whose dimension has to be deduced. */
28275 else if (TREE_CODE (type) == ARRAY_TYPE
28276 && TREE_OPERAND (expression, 2) == NULL_TREE)
28277 return true;
28278 else
28279 return dependent_type_p (type);
28282 if (TREE_CODE (expression) == SCOPE_REF)
28284 tree scope = TREE_OPERAND (expression, 0);
28285 tree name = TREE_OPERAND (expression, 1);
28287 /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
28288 contains an identifier associated by name lookup with one or more
28289 declarations declared with a dependent type, or...a
28290 nested-name-specifier or qualified-id that names a member of an
28291 unknown specialization. */
28292 return (type_dependent_expression_p (name)
28293 || dependent_scope_p (scope));
28296 if (TREE_CODE (expression) == TEMPLATE_DECL
28297 && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
28298 return uses_outer_template_parms (expression);
28300 if (TREE_CODE (expression) == STMT_EXPR)
28301 expression = stmt_expr_value_expr (expression);
28303 if (BRACE_ENCLOSED_INITIALIZER_P (expression))
28305 for (auto &elt : CONSTRUCTOR_ELTS (expression))
28306 if (type_dependent_expression_p (elt.value))
28307 return true;
28308 return false;
28311 /* A static data member of the current instantiation with incomplete
28312 array type is type-dependent, as the definition and specializations
28313 can have different bounds. */
28314 if (VAR_P (expression)
28315 && DECL_CLASS_SCOPE_P (expression)
28316 && dependent_type_p (DECL_CONTEXT (expression))
28317 && VAR_HAD_UNKNOWN_BOUND (expression))
28318 return true;
28320 /* An array of unknown bound depending on a variadic parameter, eg:
28322 template<typename... Args>
28323 void foo (Args... args)
28325 int arr[] = { args... };
28328 template<int... vals>
28329 void bar ()
28331 int arr[] = { vals... };
28334 If the array has no length and has an initializer, it must be that
28335 we couldn't determine its length in cp_complete_array_type because
28336 it is dependent. */
28337 if (((VAR_P (expression) && DECL_INITIAL (expression))
28338 || COMPOUND_LITERAL_P (expression))
28339 && TREE_TYPE (expression) != NULL_TREE
28340 && TREE_CODE (TREE_TYPE (expression)) == ARRAY_TYPE
28341 && !TYPE_DOMAIN (TREE_TYPE (expression)))
28342 return true;
28344 /* Pull a FUNCTION_DECL out of a BASELINK if we can. */
28345 if (BASELINK_P (expression))
28347 if (BASELINK_OPTYPE (expression)
28348 && dependent_type_p (BASELINK_OPTYPE (expression)))
28349 return true;
28350 expression = BASELINK_FUNCTIONS (expression);
28353 /* A function or variable template-id is type-dependent if it has any
28354 dependent template arguments. */
28355 if (VAR_OR_FUNCTION_DECL_P (expression)
28356 && DECL_LANG_SPECIFIC (expression)
28357 && DECL_TEMPLATE_INFO (expression))
28359 /* Consider the innermost template arguments, since those are the ones
28360 that come from the template-id; the template arguments for the
28361 enclosing class do not make it type-dependent unless they are used in
28362 the type of the decl. */
28363 if (instantiates_primary_template_p (expression)
28364 && (any_dependent_template_arguments_p
28365 (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
28366 return true;
28369 /* Otherwise, if the function decl isn't from a dependent scope, it can't be
28370 type-dependent. Checking this is important for functions with auto return
28371 type, which looks like a dependent type. */
28372 if (TREE_CODE (expression) == FUNCTION_DECL
28373 && !(DECL_CLASS_SCOPE_P (expression)
28374 && dependent_type_p (DECL_CONTEXT (expression)))
28375 && !(DECL_LANG_SPECIFIC (expression)
28376 && DECL_UNIQUE_FRIEND_P (expression)
28377 && (!DECL_FRIEND_CONTEXT (expression)
28378 || dependent_type_p (DECL_FRIEND_CONTEXT (expression))))
28379 && !DECL_LOCAL_DECL_P (expression))
28381 gcc_assert (!dependent_type_p (TREE_TYPE (expression))
28382 || undeduced_auto_decl (expression));
28383 return false;
28386 /* Otherwise, its constraints could still depend on outer template parameters
28387 from its (dependent) scope. */
28388 if (TREE_CODE (expression) == FUNCTION_DECL
28389 /* As an optimization, check this cheaper sufficient condition first.
28390 (At this point we've established that we're looking at a member of
28391 a dependent class, so it makes sense to start treating say undeduced
28392 auto as dependent.) */
28393 && !dependent_type_p (TREE_TYPE (expression))
28394 && uses_outer_template_parms_in_constraints (expression))
28395 return true;
28397 /* Always dependent, on the number of arguments if nothing else. */
28398 if (TREE_CODE (expression) == EXPR_PACK_EXPANSION)
28399 return true;
28401 if (TREE_TYPE (expression) == unknown_type_node)
28403 if (TREE_CODE (expression) == ADDR_EXPR)
28404 return type_dependent_expression_p (TREE_OPERAND (expression, 0));
28405 if (TREE_CODE (expression) == COMPONENT_REF
28406 || TREE_CODE (expression) == OFFSET_REF)
28408 if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
28409 return true;
28410 expression = TREE_OPERAND (expression, 1);
28411 if (identifier_p (expression))
28412 return false;
28414 /* SCOPE_REF with non-null TREE_TYPE is always non-dependent. */
28415 if (TREE_CODE (expression) == SCOPE_REF)
28416 return false;
28418 /* CO_AWAIT/YIELD_EXPR with unknown type is always dependent. */
28419 if (TREE_CODE (expression) == CO_AWAIT_EXPR
28420 || TREE_CODE (expression) == CO_YIELD_EXPR)
28421 return true;
28423 if (BASELINK_P (expression))
28425 if (BASELINK_OPTYPE (expression)
28426 && dependent_type_p (BASELINK_OPTYPE (expression)))
28427 return true;
28428 expression = BASELINK_FUNCTIONS (expression);
28431 if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
28433 if (any_dependent_template_arguments_p
28434 (TREE_OPERAND (expression, 1)))
28435 return true;
28436 expression = TREE_OPERAND (expression, 0);
28437 if (identifier_p (expression))
28438 return true;
28441 gcc_assert (OVL_P (expression));
28443 for (lkp_iterator iter (expression); iter; ++iter)
28444 if (type_dependent_expression_p (*iter))
28445 return true;
28447 return false;
28450 /* The type of a non-type template parm declared with a placeholder type
28451 depends on the corresponding template argument, even though
28452 placeholders are not normally considered dependent. */
28453 if (TREE_CODE (expression) == TEMPLATE_PARM_INDEX
28454 && is_auto (TREE_TYPE (expression)))
28455 return true;
28457 gcc_assert (TREE_CODE (expression) != TYPE_DECL);
28459 /* Dependent type attributes might not have made it from the decl to
28460 the type yet. */
28461 if (DECL_P (expression)
28462 && any_dependent_type_attributes_p (DECL_ATTRIBUTES (expression)))
28463 return true;
28465 return (dependent_type_p (TREE_TYPE (expression)));
28468 /* [temp.dep.expr]/5: A class member access expression (5.2.5) is
28469 type-dependent if the expression refers to a member of the current
28470 instantiation and the type of the referenced member is dependent, or the
28471 class member access expression refers to a member of an unknown
28472 specialization.
28474 This function returns true if the OBJECT in such a class member access
28475 expression is of an unknown specialization. */
28477 bool
28478 type_dependent_object_expression_p (tree object)
28480 /* An IDENTIFIER_NODE can sometimes have a TREE_TYPE, but it's still
28481 dependent. */
28482 if (TREE_CODE (object) == IDENTIFIER_NODE)
28483 return true;
28484 tree scope = TREE_TYPE (object);
28485 return (!scope || dependent_scope_p (scope));
28488 /* walk_tree callback function for instantiation_dependent_expression_p,
28489 below. Returns non-zero if a dependent subexpression is found. */
28491 static tree
28492 instantiation_dependent_r (tree *tp, int *walk_subtrees,
28493 void * /*data*/)
28495 if (TYPE_P (*tp))
28497 /* We don't have to worry about decltype currently because decltype
28498 of an instantiation-dependent expr is a dependent type. This
28499 might change depending on the resolution of DR 1172. */
28500 *walk_subtrees = false;
28501 return NULL_TREE;
28503 enum tree_code code = TREE_CODE (*tp);
28504 switch (code)
28506 /* Don't treat an argument list as dependent just because it has no
28507 TREE_TYPE. */
28508 case TREE_LIST:
28509 case TREE_VEC:
28510 case NONTYPE_ARGUMENT_PACK:
28511 return NULL_TREE;
28513 case TEMPLATE_PARM_INDEX:
28514 if (dependent_type_p (TREE_TYPE (*tp)))
28515 return *tp;
28516 if (TEMPLATE_PARM_PARAMETER_PACK (*tp))
28517 return *tp;
28518 /* We'll check value-dependence separately. */
28519 return NULL_TREE;
28521 /* Handle expressions with type operands. */
28522 case SIZEOF_EXPR:
28523 case ALIGNOF_EXPR:
28524 case TYPEID_EXPR:
28525 case AT_ENCODE_EXPR:
28527 tree op = TREE_OPERAND (*tp, 0);
28528 if (code == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (*tp))
28529 op = TREE_TYPE (op);
28530 if (TYPE_P (op))
28532 if (dependent_type_p (op))
28533 return *tp;
28534 else
28536 *walk_subtrees = false;
28537 return NULL_TREE;
28540 break;
28543 case COMPONENT_REF:
28544 if (identifier_p (TREE_OPERAND (*tp, 1)))
28545 /* In a template, finish_class_member_access_expr creates a
28546 COMPONENT_REF with an IDENTIFIER_NODE for op1 even if it isn't
28547 type-dependent, so that we can check access control at
28548 instantiation time (PR 42277). See also Core issue 1273. */
28549 return *tp;
28550 break;
28552 case SCOPE_REF:
28553 if (instantiation_dependent_scope_ref_p (*tp))
28554 return *tp;
28555 else
28556 break;
28558 /* Treat statement-expressions as dependent. */
28559 case BIND_EXPR:
28560 return *tp;
28562 /* Treat requires-expressions as dependent. */
28563 case REQUIRES_EXPR:
28564 return *tp;
28566 case CONSTRUCTOR:
28567 if (CONSTRUCTOR_IS_DEPENDENT (*tp))
28568 return *tp;
28569 break;
28571 case TEMPLATE_DECL:
28572 case FUNCTION_DECL:
28573 /* Before C++17, a noexcept-specifier isn't part of the function type
28574 so it doesn't affect type dependence, but we still want to consider it
28575 for instantiation dependence. */
28576 if (cxx_dialect < cxx17
28577 && DECL_DECLARES_FUNCTION_P (*tp)
28578 && value_dependent_noexcept_spec_p (TREE_TYPE (*tp)))
28579 return *tp;
28580 break;
28582 default:
28583 break;
28586 if (type_dependent_expression_p (*tp))
28587 return *tp;
28588 else
28589 return NULL_TREE;
28592 /* Returns TRUE if the EXPRESSION is instantiation-dependent, in the
28593 sense defined by the ABI:
28595 "An expression is instantiation-dependent if it is type-dependent
28596 or value-dependent, or it has a subexpression that is type-dependent
28597 or value-dependent."
28599 Except don't actually check value-dependence for unevaluated expressions,
28600 because in sizeof(i) we don't care about the value of i. Checking
28601 type-dependence will in turn check value-dependence of array bounds/template
28602 arguments as needed. */
28604 bool
28605 instantiation_dependent_uneval_expression_p (tree expression)
28607 tree result;
28609 if (!processing_template_decl)
28610 return false;
28612 if (expression == error_mark_node)
28613 return false;
28615 result = cp_walk_tree_without_duplicates (&expression,
28616 instantiation_dependent_r, NULL);
28617 return result != NULL_TREE;
28620 /* As above, but also check value-dependence of the expression as a whole. */
28622 bool
28623 instantiation_dependent_expression_p (tree expression)
28625 return (instantiation_dependent_uneval_expression_p (expression)
28626 || (processing_template_decl
28627 && potential_constant_expression (expression)
28628 && value_dependent_expression_p (expression)));
28631 /* Like type_dependent_expression_p, but it also works while not processing
28632 a template definition, i.e. during substitution or mangling. */
28634 bool
28635 type_dependent_expression_p_push (tree expr)
28637 bool b;
28638 ++processing_template_decl;
28639 b = type_dependent_expression_p (expr);
28640 --processing_template_decl;
28641 return b;
28644 /* Returns TRUE if ARGS contains a type-dependent expression. */
28646 bool
28647 any_type_dependent_arguments_p (const vec<tree, va_gc> *args)
28649 if (!processing_template_decl || !args)
28650 return false;
28652 for (tree arg : *args)
28653 if (type_dependent_expression_p (arg))
28654 return true;
28656 return false;
28659 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
28660 expressions) contains any type-dependent expressions. */
28662 bool
28663 any_type_dependent_elements_p (const_tree list)
28665 for (; list; list = TREE_CHAIN (list))
28666 if (type_dependent_expression_p (TREE_VALUE (list)))
28667 return true;
28669 return false;
28672 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
28673 expressions) contains any value-dependent expressions. */
28675 bool
28676 any_value_dependent_elements_p (const_tree list)
28678 for (; list; list = TREE_CHAIN (list))
28679 if (value_dependent_expression_p (TREE_VALUE (list)))
28680 return true;
28682 return false;
28685 /* Returns TRUE if the ARG (a template argument) is dependent. */
28687 bool
28688 dependent_template_arg_p (tree arg)
28690 if (!processing_template_decl)
28691 return false;
28693 /* Assume a template argument that was wrongly written by the user
28694 is dependent. This is consistent with what
28695 any_dependent_template_arguments_p [that calls this function]
28696 does. */
28697 if (!arg || arg == error_mark_node)
28698 return true;
28700 if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
28701 arg = argument_pack_select_arg (arg);
28703 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
28704 return true;
28705 if (TREE_CODE (arg) == TEMPLATE_DECL)
28707 if (DECL_TEMPLATE_PARM_P (arg))
28708 return true;
28709 /* A member template of a dependent class is not necessarily
28710 type-dependent, but it is a dependent template argument because it
28711 will be a member of an unknown specialization to that template. */
28712 tree scope = CP_DECL_CONTEXT (arg);
28713 return TYPE_P (scope) && dependent_type_p (scope);
28715 else if (ARGUMENT_PACK_P (arg))
28717 tree args = ARGUMENT_PACK_ARGS (arg);
28718 for (tree arg : tree_vec_range (args))
28719 if (dependent_template_arg_p (arg))
28720 return true;
28721 return false;
28723 else if (TYPE_P (arg))
28724 return dependent_type_p (arg);
28725 else
28726 return value_dependent_expression_p (arg);
28729 /* Identify any expressions that use function parms. */
28731 static tree
28732 find_parm_usage_r (tree *tp, int *walk_subtrees, void*)
28734 tree t = *tp;
28735 if (TREE_CODE (t) == PARM_DECL)
28737 *walk_subtrees = 0;
28738 return t;
28740 return NULL_TREE;
28743 /* Returns true if a type specialization formed using the template
28744 arguments ARGS needs to use structural equality. */
28746 bool
28747 any_template_arguments_need_structural_equality_p (tree args)
28749 int i;
28750 int j;
28752 if (!args)
28753 return false;
28754 if (args == error_mark_node)
28755 return true;
28757 for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
28759 tree level = TMPL_ARGS_LEVEL (args, i + 1);
28760 for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
28762 tree arg = TREE_VEC_ELT (level, j);
28763 tree packed_args = NULL_TREE;
28764 int k, len = 1;
28766 if (ARGUMENT_PACK_P (arg))
28768 /* Look inside the argument pack. */
28769 packed_args = ARGUMENT_PACK_ARGS (arg);
28770 len = TREE_VEC_LENGTH (packed_args);
28773 for (k = 0; k < len; ++k)
28775 if (packed_args)
28776 arg = TREE_VEC_ELT (packed_args, k);
28778 if (error_operand_p (arg))
28779 return true;
28780 else if (TREE_CODE (arg) == TEMPLATE_DECL)
28781 continue;
28782 else if (arg == any_targ_node)
28783 /* An any_targ_node argument (added by add_defaults_to_ttp)
28784 makes the corresponding specialization not canonicalizable,
28785 since template_args_equal always return true for it. We
28786 may see this when called from bind_template_template_parm. */
28787 return true;
28788 /* Checking current_function_decl because this structural
28789 comparison is only necessary for redeclaration. */
28790 else if (!current_function_decl
28791 && dependent_template_arg_p (arg)
28792 && (cp_walk_tree_without_duplicates
28793 (&arg, find_parm_usage_r, NULL)))
28794 /* The identity of a class template specialization that uses
28795 a function parameter depends on the identity of the function.
28796 And if this specialization appeared in the trailing return
28797 type thereof, we don't know the identity of the function
28798 (e.g. if it's a redeclaration or a new function) until we
28799 form its signature and go through duplicate_decls. Thus
28800 it's unsafe to decide on a canonical type now (which depends
28801 on the DECL_CONTEXT of the function parameter, which can get
28802 mutated after the fact by duplicate_decls), so just require
28803 structural equality in this case (PR52830). */
28804 return true;
28809 return false;
28812 /* Returns true if ARGS (a collection of template arguments) contains
28813 any dependent arguments. */
28815 bool
28816 any_dependent_template_arguments_p (const_tree args)
28818 if (args == error_mark_node)
28819 return true;
28820 if (!processing_template_decl || !args)
28821 return false;
28823 for (int i = 0, depth = TMPL_ARGS_DEPTH (args); i < depth; ++i)
28825 const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
28826 for (tree arg : tree_vec_range (CONST_CAST_TREE (level)))
28827 if (dependent_template_arg_p (arg))
28828 return true;
28831 return false;
28834 /* Returns true if ARGS contains any errors. */
28836 bool
28837 any_erroneous_template_args_p (const_tree args)
28839 int i;
28840 int j;
28842 if (args == error_mark_node)
28843 return true;
28845 if (args && TREE_CODE (args) != TREE_VEC)
28847 if (tree ti = get_template_info (args))
28848 args = TI_ARGS (ti);
28849 else
28850 args = NULL_TREE;
28853 if (!args)
28854 return false;
28856 for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
28858 const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
28859 for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
28860 if (error_operand_p (TREE_VEC_ELT (level, j)))
28861 return true;
28864 return false;
28867 /* Returns TRUE if the template TMPL is type-dependent. */
28869 bool
28870 dependent_template_p (tree tmpl)
28872 if (TREE_CODE (tmpl) == OVERLOAD)
28874 for (lkp_iterator iter (tmpl); iter; ++iter)
28875 if (dependent_template_p (*iter))
28876 return true;
28877 return false;
28880 /* Template template parameters are dependent. */
28881 if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
28882 || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
28883 return true;
28884 /* So are names that have not been looked up. */
28885 if (TREE_CODE (tmpl) == SCOPE_REF || identifier_p (tmpl))
28886 return true;
28887 return false;
28890 /* Returns TRUE if the specialization TMPL<ARGS> is dependent. */
28892 bool
28893 dependent_template_id_p (tree tmpl, tree args)
28895 return (dependent_template_p (tmpl)
28896 || any_dependent_template_arguments_p (args));
28899 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
28900 are dependent. */
28902 bool
28903 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
28905 int i;
28907 if (!processing_template_decl)
28908 return false;
28910 for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
28912 tree decl = TREE_VEC_ELT (declv, i);
28913 tree init = TREE_VEC_ELT (initv, i);
28914 tree cond = TREE_VEC_ELT (condv, i);
28915 tree incr = TREE_VEC_ELT (incrv, i);
28917 if (type_dependent_expression_p (decl)
28918 || TREE_CODE (decl) == SCOPE_REF)
28919 return true;
28921 if (init && type_dependent_expression_p (init))
28922 return true;
28924 if (cond == global_namespace)
28925 return true;
28927 if (type_dependent_expression_p (cond))
28928 return true;
28930 if (COMPARISON_CLASS_P (cond)
28931 && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
28932 || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
28933 return true;
28935 if (TREE_CODE (incr) == MODOP_EXPR)
28937 if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
28938 || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
28939 return true;
28941 else if (type_dependent_expression_p (incr))
28942 return true;
28943 else if (TREE_CODE (incr) == MODIFY_EXPR)
28945 if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
28946 return true;
28947 else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
28949 tree t = TREE_OPERAND (incr, 1);
28950 if (type_dependent_expression_p (TREE_OPERAND (t, 0))
28951 || type_dependent_expression_p (TREE_OPERAND (t, 1)))
28952 return true;
28954 /* If this loop has a class iterator with != comparison
28955 with increment other than i++/++i/i--/--i, make sure the
28956 increment is constant. */
28957 if (CLASS_TYPE_P (TREE_TYPE (decl))
28958 && TREE_CODE (cond) == NE_EXPR)
28960 if (TREE_OPERAND (t, 0) == decl)
28961 t = TREE_OPERAND (t, 1);
28962 else
28963 t = TREE_OPERAND (t, 0);
28964 if (TREE_CODE (t) != INTEGER_CST)
28965 return true;
28971 return false;
28974 /* TYPE is a TYPENAME_TYPE. Returns the ordinary TYPE to which the
28975 TYPENAME_TYPE corresponds. Returns the original TYPENAME_TYPE if
28976 no such TYPE can be found. Note that this function peers inside
28977 uninstantiated templates and therefore should be used only in
28978 extremely limited situations. ONLY_CURRENT_P restricts this
28979 peering to the currently open classes hierarchy (which is required
28980 when comparing types). */
28982 tree
28983 resolve_typename_type (tree type, bool only_current_p)
28985 tree scope;
28986 tree name;
28987 tree decl;
28988 int quals;
28989 tree pushed_scope;
28990 tree result;
28992 gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
28994 scope = TYPE_CONTEXT (type);
28995 /* We shouldn't have built a TYPENAME_TYPE with a non-dependent scope. */
28996 gcc_checking_assert (uses_template_parms (scope));
28998 /* Usually the non-qualified identifier of a TYPENAME_TYPE is
28999 TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of a
29000 TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL
29001 representing the typedef. In that case TYPE_IDENTIFIER (type) is
29002 not the non-qualified identifier of the TYPENAME_TYPE anymore.
29003 So by getting the TYPE_IDENTIFIER of the _main declaration_ of
29004 the TYPENAME_TYPE instead, we avoid messing up with a possible
29005 typedef variant case. */
29006 name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
29008 /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
29009 it first before we can figure out what NAME refers to. */
29010 if (TREE_CODE (scope) == TYPENAME_TYPE)
29012 if (TYPENAME_IS_RESOLVING_P (scope))
29013 /* Given a class template A with a dependent base with nested type C,
29014 typedef typename A::C::C C will land us here, as trying to resolve
29015 the initial A::C leads to the local C typedef, which leads back to
29016 A::C::C. So we break the recursion now. */
29017 return type;
29018 else
29019 scope = resolve_typename_type (scope, only_current_p);
29021 /* If we don't know what SCOPE refers to, then we cannot resolve the
29022 TYPENAME_TYPE. */
29023 if (!CLASS_TYPE_P (scope))
29024 return type;
29025 /* If this is a typedef, we don't want to look inside (c++/11987). */
29026 if (typedef_variant_p (type))
29027 return type;
29028 /* If SCOPE isn't the template itself, it will not have a valid
29029 TYPE_FIELDS list. */
29030 if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
29031 /* scope is either the template itself or a compatible instantiation
29032 like X<T>, so look up the name in the original template. */
29033 scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
29034 /* If scope has no fields, it can't be a current instantiation. Check this
29035 before currently_open_class to avoid infinite recursion (71515). */
29036 if (!TYPE_FIELDS (scope))
29037 return type;
29038 /* If the SCOPE is not the current instantiation, there's no reason
29039 to look inside it. */
29040 if (only_current_p && !currently_open_class (scope))
29041 return type;
29042 /* Enter the SCOPE so that name lookup will be resolved as if we
29043 were in the class definition. In particular, SCOPE will no
29044 longer be considered a dependent type. */
29045 pushed_scope = push_scope (scope);
29046 /* Look up the declaration. */
29047 decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true,
29048 tf_warning_or_error);
29050 result = NULL_TREE;
29052 /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
29053 find a TEMPLATE_DECL. Otherwise, we want to find a TYPE_DECL. */
29054 tree fullname = TYPENAME_TYPE_FULLNAME (type);
29055 if (!decl)
29056 /*nop*/;
29057 else if (identifier_p (fullname)
29058 && TREE_CODE (decl) == TYPE_DECL)
29060 result = TREE_TYPE (decl);
29061 if (result == error_mark_node)
29062 result = NULL_TREE;
29064 else if (TREE_CODE (fullname) == TEMPLATE_ID_EXPR
29065 && DECL_CLASS_TEMPLATE_P (decl))
29067 /* Obtain the template and the arguments. */
29068 tree tmpl = TREE_OPERAND (fullname, 0);
29069 if (TREE_CODE (tmpl) == IDENTIFIER_NODE)
29071 /* We get here with a plain identifier because a previous tentative
29072 parse of the nested-name-specifier as part of a ptr-operator saw
29073 ::template X<A>. The use of ::template is necessary in a
29074 ptr-operator, but wrong in a declarator-id.
29076 [temp.names]: In a qualified-id of a declarator-id, the keyword
29077 template shall not appear at the top level. */
29078 pedwarn (cp_expr_loc_or_input_loc (fullname), OPT_Wpedantic,
29079 "keyword %<template%> not allowed in declarator-id");
29080 tmpl = decl;
29082 tree args = TREE_OPERAND (fullname, 1);
29083 /* Instantiate the template. */
29084 result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
29085 /*entering_scope=*/true,
29086 tf_error | tf_user);
29087 if (result == error_mark_node)
29088 result = NULL_TREE;
29091 /* Leave the SCOPE. */
29092 if (pushed_scope)
29093 pop_scope (pushed_scope);
29095 /* If we failed to resolve it, return the original typename. */
29096 if (!result)
29097 return type;
29099 /* If lookup found a typename type, resolve that too. */
29100 if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
29102 /* Ill-formed programs can cause infinite recursion here, so we
29103 must catch that. */
29104 TYPENAME_IS_RESOLVING_P (result) = 1;
29105 result = resolve_typename_type (result, only_current_p);
29106 TYPENAME_IS_RESOLVING_P (result) = 0;
29109 /* Qualify the resulting type. */
29110 quals = cp_type_quals (type);
29111 if (quals)
29112 result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
29114 return result;
29117 /* EXPR is an expression which is not type-dependent. Return a proxy
29118 for EXPR that can be used to compute the types of larger
29119 expressions containing EXPR. */
29121 tree
29122 build_non_dependent_expr (tree expr)
29124 tree orig_expr = expr;
29125 tree inner_expr;
29127 /* When checking, try to get a constant value for all non-dependent
29128 expressions in order to expose bugs in *_dependent_expression_p
29129 and constexpr. This can affect code generation, see PR70704, so
29130 only do this for -fchecking=2. */
29131 if (flag_checking > 1
29132 && cxx_dialect >= cxx11
29133 /* Don't do this during nsdmi parsing as it can lead to
29134 unexpected recursive instantiations. */
29135 && !parsing_nsdmi ()
29136 /* Don't do this during concept processing either and for
29137 the same reason. */
29138 && !processing_constraint_expression_p ())
29139 fold_non_dependent_expr (expr, tf_none);
29141 STRIP_ANY_LOCATION_WRAPPER (expr);
29143 /* Preserve OVERLOADs; the functions must be available to resolve
29144 types. */
29145 inner_expr = expr;
29146 if (TREE_CODE (inner_expr) == STMT_EXPR)
29147 inner_expr = stmt_expr_value_expr (inner_expr);
29148 if (TREE_CODE (inner_expr) == ADDR_EXPR)
29149 inner_expr = TREE_OPERAND (inner_expr, 0);
29150 if (TREE_CODE (inner_expr) == COMPONENT_REF)
29151 inner_expr = TREE_OPERAND (inner_expr, 1);
29152 if (is_overloaded_fn (inner_expr)
29153 || TREE_CODE (inner_expr) == OFFSET_REF)
29154 return orig_expr;
29155 /* There is no need to return a proxy for a variable, parameter
29156 or enumerator. */
29157 if (VAR_P (expr) || TREE_CODE (expr) == PARM_DECL
29158 || TREE_CODE (expr) == CONST_DECL)
29159 return orig_expr;
29160 /* Preserve string constants; conversions from string constants to
29161 "char *" are allowed, even though normally a "const char *"
29162 cannot be used to initialize a "char *". */
29163 if (TREE_CODE (expr) == STRING_CST)
29164 return orig_expr;
29165 /* Preserve void and arithmetic constants, as an optimization -- there is no
29166 reason to create a new node. */
29167 if (TREE_CODE (expr) == VOID_CST
29168 || TREE_CODE (expr) == INTEGER_CST
29169 || TREE_CODE (expr) == REAL_CST)
29170 return orig_expr;
29171 /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
29172 There is at least one place where we want to know that a
29173 particular expression is a throw-expression: when checking a ?:
29174 expression, there are special rules if the second or third
29175 argument is a throw-expression. */
29176 if (TREE_CODE (expr) == THROW_EXPR)
29177 return orig_expr;
29179 /* Don't wrap an initializer list, we need to be able to look inside. */
29180 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
29181 return orig_expr;
29183 /* Don't wrap a dummy object, we need to be able to test for it. */
29184 if (is_dummy_object (expr))
29185 return orig_expr;
29187 if (TREE_CODE (expr) == COND_EXPR)
29188 return build3 (COND_EXPR,
29189 TREE_TYPE (expr),
29190 build_non_dependent_expr (TREE_OPERAND (expr, 0)),
29191 (TREE_OPERAND (expr, 1)
29192 ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
29193 : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
29194 build_non_dependent_expr (TREE_OPERAND (expr, 2)));
29195 if (TREE_CODE (expr) == COMPOUND_EXPR)
29196 return build2 (COMPOUND_EXPR,
29197 TREE_TYPE (expr),
29198 TREE_OPERAND (expr, 0),
29199 build_non_dependent_expr (TREE_OPERAND (expr, 1)));
29201 /* If the type is unknown, it can't really be non-dependent */
29202 gcc_assert (TREE_TYPE (expr) != unknown_type_node);
29204 /* Otherwise, build a NON_DEPENDENT_EXPR. */
29205 return build1_loc (EXPR_LOCATION (orig_expr), NON_DEPENDENT_EXPR,
29206 TREE_TYPE (expr), expr);
29209 /* ARGS is a vector of expressions as arguments to a function call.
29210 Replace the arguments with equivalent non-dependent expressions.
29211 This modifies ARGS in place. */
29213 void
29214 make_args_non_dependent (vec<tree, va_gc> *args)
29216 unsigned int ix;
29217 tree arg;
29219 FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
29221 tree newarg = build_non_dependent_expr (arg);
29222 if (newarg != arg)
29223 (*args)[ix] = newarg;
29227 /* Returns a type which represents 'auto' or 'decltype(auto)'. We use a
29228 TEMPLATE_TYPE_PARM with a level one deeper than the actual template parms,
29229 by default. If set_canonical is true, we set TYPE_CANONICAL on it. */
29231 static tree
29232 make_auto_1 (tree name, bool set_canonical, int level = -1)
29234 if (level == -1)
29235 level = current_template_depth + 1;
29236 tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
29237 TYPE_NAME (au) = build_decl (input_location, TYPE_DECL, name, au);
29238 TYPE_STUB_DECL (au) = TYPE_NAME (au);
29239 TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
29240 (0, level, level, TYPE_NAME (au), NULL_TREE);
29241 if (set_canonical)
29242 TYPE_CANONICAL (au) = canonical_type_parameter (au);
29243 DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
29244 SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
29245 if (name == decltype_auto_identifier)
29246 AUTO_IS_DECLTYPE (au) = true;
29248 return au;
29251 tree
29252 make_decltype_auto (void)
29254 return make_auto_1 (decltype_auto_identifier, true);
29257 tree
29258 make_auto (void)
29260 return make_auto_1 (auto_identifier, true);
29263 /* Return a C++17 deduction placeholder for class template TMPL.
29264 There are represented as an 'auto' with the special level 0 and
29265 CLASS_PLACEHOLDER_TEMPLATE set. */
29267 tree
29268 make_template_placeholder (tree tmpl)
29270 tree t = make_auto_1 (auto_identifier, false, /*level=*/0);
29271 CLASS_PLACEHOLDER_TEMPLATE (t) = tmpl;
29272 /* Our canonical type depends on the placeholder. */
29273 TYPE_CANONICAL (t) = canonical_type_parameter (t);
29274 return t;
29277 /* True iff T is a C++17 class template deduction placeholder. */
29279 bool
29280 template_placeholder_p (tree t)
29282 return is_auto (t) && CLASS_PLACEHOLDER_TEMPLATE (t);
29285 /* Make a "constrained auto" type-specifier. This is an auto or
29286 decltype(auto) type with constraints that must be associated after
29287 deduction. The constraint is formed from the given concept CON
29288 and its optional sequence of template arguments ARGS.
29290 TYPE must be the result of make_auto_type or make_decltype_auto_type. */
29292 static tree
29293 make_constrained_placeholder_type (tree type, tree con, tree args)
29295 /* Build the constraint. */
29296 tree tmpl = DECL_TI_TEMPLATE (con);
29297 tree expr = tmpl;
29298 if (TREE_CODE (con) == FUNCTION_DECL)
29299 expr = ovl_make (tmpl);
29300 ++processing_template_decl;
29301 expr = build_concept_check (expr, type, args, tf_warning_or_error);
29302 --processing_template_decl;
29304 PLACEHOLDER_TYPE_CONSTRAINTS_INFO (type)
29305 = build_tree_list (current_template_parms, expr);
29307 /* Our canonical type depends on the constraint. */
29308 TYPE_CANONICAL (type) = canonical_type_parameter (type);
29310 /* Attach the constraint to the type declaration. */
29311 return TYPE_NAME (type);
29314 /* Make a "constrained auto" type-specifier. */
29316 tree
29317 make_constrained_auto (tree con, tree args)
29319 tree type = make_auto_1 (auto_identifier, false);
29320 return make_constrained_placeholder_type (type, con, args);
29323 /* Make a "constrained decltype(auto)" type-specifier. */
29325 tree
29326 make_constrained_decltype_auto (tree con, tree args)
29328 tree type = make_auto_1 (decltype_auto_identifier, false);
29329 return make_constrained_placeholder_type (type, con, args);
29332 /* Returns true if the placeholder type constraint T has any dependent
29333 (explicit) template arguments. */
29335 static bool
29336 placeholder_type_constraint_dependent_p (tree t)
29338 tree id = unpack_concept_check (t);
29339 tree args = TREE_OPERAND (id, 1);
29340 tree first = TREE_VEC_ELT (args, 0);
29341 if (ARGUMENT_PACK_P (first))
29343 args = expand_template_argument_pack (args);
29344 first = TREE_VEC_ELT (args, 0);
29346 gcc_checking_assert (TREE_CODE (first) == WILDCARD_DECL
29347 || is_auto (first));
29348 for (int i = 1; i < TREE_VEC_LENGTH (args); ++i)
29349 if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
29350 return true;
29351 return false;
29354 /* Build and return a concept definition. Like other templates, the
29355 CONCEPT_DECL node is wrapped by a TEMPLATE_DECL. This returns the
29356 the TEMPLATE_DECL. */
29358 tree
29359 finish_concept_definition (cp_expr id, tree init, tree attrs)
29361 gcc_assert (identifier_p (id));
29362 gcc_assert (processing_template_decl);
29364 location_t loc = id.get_location();
29366 /* A concept-definition shall not have associated constraints. */
29367 if (TEMPLATE_PARMS_CONSTRAINTS (current_template_parms))
29369 error_at (loc, "a concept cannot be constrained");
29370 TEMPLATE_PARMS_CONSTRAINTS (current_template_parms) = NULL_TREE;
29373 /* A concept-definition shall appear in namespace scope. Templates
29374 aren't allowed in block scope, so we only need to check for class
29375 scope. */
29376 if (TYPE_P (current_scope()) || !DECL_NAMESPACE_SCOPE_P (current_scope ()))
29378 error_at (loc, "concept %qE not in namespace scope", *id);
29379 return error_mark_node;
29382 if (current_template_depth > 1)
29384 error_at (loc, "concept %qE has multiple template parameter lists", *id);
29385 return error_mark_node;
29388 /* Initially build the concept declaration; its type is bool. */
29389 tree decl = build_lang_decl_loc (loc, CONCEPT_DECL, *id, boolean_type_node);
29390 DECL_CONTEXT (decl) = current_scope ();
29391 DECL_INITIAL (decl) = init;
29393 if (attrs)
29394 cplus_decl_attributes (&decl, attrs, 0);
29396 set_originating_module (decl, false);
29398 /* Push the enclosing template. */
29399 return push_template_decl (decl);
29402 /* Given type ARG, return std::initializer_list<ARG>. */
29404 static tree
29405 listify (tree arg)
29407 tree std_init_list = lookup_qualified_name (std_node, init_list_identifier);
29409 if (std_init_list == error_mark_node
29410 || !DECL_CLASS_TEMPLATE_P (std_init_list))
29412 gcc_rich_location richloc (input_location);
29413 maybe_add_include_fixit (&richloc, "<initializer_list>", false);
29414 error_at (&richloc,
29415 "deducing from brace-enclosed initializer list"
29416 " requires %<#include <initializer_list>%>");
29418 return error_mark_node;
29420 tree argvec = make_tree_vec (1);
29421 TREE_VEC_ELT (argvec, 0) = arg;
29423 return lookup_template_class (std_init_list, argvec, NULL_TREE,
29424 NULL_TREE, 0, tf_warning_or_error);
29427 /* Replace auto in TYPE with std::initializer_list<auto>. */
29429 static tree
29430 listify_autos (tree type, tree auto_node)
29432 tree init_auto = listify (strip_top_quals (auto_node));
29433 tree argvec = make_tree_vec (1);
29434 TREE_VEC_ELT (argvec, 0) = init_auto;
29435 if (processing_template_decl)
29436 argvec = add_to_template_args (current_template_args (), argvec);
29437 return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
29440 /* Hash traits for hashing possibly constrained 'auto'
29441 TEMPLATE_TYPE_PARMs for use by do_auto_deduction. */
29443 struct auto_hash : default_hash_traits<tree>
29445 static inline hashval_t hash (tree);
29446 static inline bool equal (tree, tree);
29449 /* Hash the 'auto' T. */
29451 inline hashval_t
29452 auto_hash::hash (tree t)
29454 if (tree c = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (t)))
29455 /* Matching constrained-type-specifiers denote the same template
29456 parameter, so hash the constraint. */
29457 return hash_placeholder_constraint (c);
29458 else
29459 /* But unconstrained autos are all separate, so just hash the pointer. */
29460 return iterative_hash_object (t, 0);
29463 /* Compare two 'auto's. */
29465 inline bool
29466 auto_hash::equal (tree t1, tree t2)
29468 if (t1 == t2)
29469 return true;
29471 tree c1 = PLACEHOLDER_TYPE_CONSTRAINTS (t1);
29472 tree c2 = PLACEHOLDER_TYPE_CONSTRAINTS (t2);
29474 /* Two unconstrained autos are distinct. */
29475 if (!c1 || !c2)
29476 return false;
29478 return equivalent_placeholder_constraints (c1, c2);
29481 /* for_each_template_parm callback for extract_autos: if t is a (possibly
29482 constrained) auto, add it to the vector. */
29484 static int
29485 extract_autos_r (tree t, void *data)
29487 hash_table<auto_hash> &hash = *(hash_table<auto_hash>*)data;
29488 if (is_auto (t) && !template_placeholder_p (t))
29490 /* All the autos were built with index 0; fix that up now. */
29491 tree *p = hash.find_slot (t, INSERT);
29492 int idx;
29493 if (*p)
29494 /* If this is a repeated constrained-type-specifier, use the index we
29495 chose before. */
29496 idx = TEMPLATE_TYPE_IDX (*p);
29497 else
29499 /* Otherwise this is new, so use the current count. */
29500 *p = t;
29501 idx = hash.elements () - 1;
29503 if (idx != TEMPLATE_TYPE_IDX (t))
29505 gcc_checking_assert (TEMPLATE_TYPE_IDX (t) == 0);
29506 gcc_checking_assert (TYPE_CANONICAL (t) != t);
29507 TEMPLATE_TYPE_IDX (t) = idx;
29508 TYPE_CANONICAL (t) = canonical_type_parameter (t);
29512 /* Always keep walking. */
29513 return 0;
29516 /* Return a TREE_VEC of the 'auto's used in type under the Concepts TS, which
29517 says they can appear anywhere in the type. */
29519 static tree
29520 extract_autos (tree type)
29522 hash_set<tree> visited;
29523 hash_table<auto_hash> hash (2);
29525 for_each_template_parm (type, extract_autos_r, &hash, &visited, true);
29527 tree tree_vec = make_tree_vec (hash.elements());
29528 for (tree elt : hash)
29530 unsigned i = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (elt));
29531 TREE_VEC_ELT (tree_vec, i)
29532 = build_tree_list (NULL_TREE, TYPE_NAME (elt));
29535 return tree_vec;
29538 /* The stem for deduction guide names. */
29539 const char *const dguide_base = "__dguide_";
29541 /* Return the name for a deduction guide for class template TMPL. */
29543 tree
29544 dguide_name (tree tmpl)
29546 tree type = (TYPE_P (tmpl) ? tmpl : TREE_TYPE (tmpl));
29547 tree tname = TYPE_IDENTIFIER (type);
29548 char *buf = (char *) alloca (1 + strlen (dguide_base)
29549 + IDENTIFIER_LENGTH (tname));
29550 memcpy (buf, dguide_base, strlen (dguide_base));
29551 memcpy (buf + strlen (dguide_base), IDENTIFIER_POINTER (tname),
29552 IDENTIFIER_LENGTH (tname) + 1);
29553 tree dname = get_identifier (buf);
29554 TREE_TYPE (dname) = type;
29555 return dname;
29558 /* True if NAME is the name of a deduction guide. */
29560 bool
29561 dguide_name_p (tree name)
29563 return (TREE_CODE (name) == IDENTIFIER_NODE
29564 && TREE_TYPE (name)
29565 && startswith (IDENTIFIER_POINTER (name), dguide_base));
29568 /* True if FN is a deduction guide. */
29570 bool
29571 deduction_guide_p (const_tree fn)
29573 if (DECL_P (fn))
29574 if (tree name = DECL_NAME (fn))
29575 return dguide_name_p (name);
29576 return false;
29579 /* True if FN is the copy deduction guide, i.e. A(A)->A. */
29581 bool
29582 copy_guide_p (const_tree fn)
29584 gcc_assert (deduction_guide_p (fn));
29585 if (!DECL_ARTIFICIAL (fn))
29586 return false;
29587 tree parms = FUNCTION_FIRST_USER_PARMTYPE (DECL_TI_TEMPLATE (fn));
29588 return (TREE_CHAIN (parms) == void_list_node
29589 && same_type_p (TREE_VALUE (parms), TREE_TYPE (DECL_NAME (fn))));
29592 /* True if FN is a guide generated from a constructor template. */
29594 bool
29595 template_guide_p (const_tree fn)
29597 gcc_assert (deduction_guide_p (fn));
29598 if (!DECL_ARTIFICIAL (fn))
29599 return false;
29600 tree tmpl = DECL_TI_TEMPLATE (fn);
29601 if (tree org = DECL_ABSTRACT_ORIGIN (tmpl))
29602 return PRIMARY_TEMPLATE_P (org);
29603 return false;
29606 /* True if FN is an aggregate initialization guide or the copy deduction
29607 guide. */
29609 bool
29610 builtin_guide_p (const_tree fn)
29612 if (!deduction_guide_p (fn))
29613 return false;
29614 if (!DECL_ARTIFICIAL (fn))
29615 /* Explicitly declared. */
29616 return false;
29617 if (DECL_ABSTRACT_ORIGIN (fn))
29618 /* Derived from a constructor. */
29619 return false;
29620 return true;
29623 /* OLDDECL is a _DECL for a template parameter. Return a similar parameter at
29624 LEVEL:INDEX, using tsubst_args and complain for substitution into non-type
29625 template parameter types. Note that the handling of template template
29626 parameters relies on current_template_parms being set appropriately for the
29627 new template. */
29629 static tree
29630 rewrite_template_parm (tree olddecl, unsigned index, unsigned level,
29631 tree tsubst_args, tsubst_flags_t complain)
29633 if (olddecl == error_mark_node)
29634 return error_mark_node;
29636 tree oldidx = get_template_parm_index (olddecl);
29638 tree newtype;
29639 if (TREE_CODE (olddecl) == TYPE_DECL
29640 || TREE_CODE (olddecl) == TEMPLATE_DECL)
29642 tree oldtype = TREE_TYPE (olddecl);
29643 newtype = cxx_make_type (TREE_CODE (oldtype));
29644 TYPE_MAIN_VARIANT (newtype) = newtype;
29646 else
29648 newtype = TREE_TYPE (olddecl);
29649 if (type_uses_auto (newtype))
29651 // Substitute once to fix references to other template parameters.
29652 newtype = tsubst (newtype, tsubst_args,
29653 complain|tf_partial, NULL_TREE);
29654 // Now substitute again to reduce the level of the auto.
29655 newtype = tsubst (newtype, current_template_args (),
29656 complain, NULL_TREE);
29658 else
29659 newtype = tsubst (newtype, tsubst_args,
29660 complain, NULL_TREE);
29663 tree newdecl
29664 = build_decl (DECL_SOURCE_LOCATION (olddecl), TREE_CODE (olddecl),
29665 DECL_NAME (olddecl), newtype);
29666 SET_DECL_TEMPLATE_PARM_P (newdecl);
29668 tree newidx;
29669 if (TREE_CODE (olddecl) == TYPE_DECL
29670 || TREE_CODE (olddecl) == TEMPLATE_DECL)
29672 newidx = TEMPLATE_TYPE_PARM_INDEX (newtype)
29673 = build_template_parm_index (index, level, level,
29674 newdecl, newtype);
29675 TEMPLATE_PARM_PARAMETER_PACK (newidx)
29676 = TEMPLATE_PARM_PARAMETER_PACK (oldidx);
29677 TYPE_STUB_DECL (newtype) = TYPE_NAME (newtype) = newdecl;
29679 if (TREE_CODE (olddecl) == TEMPLATE_DECL)
29681 DECL_TEMPLATE_RESULT (newdecl)
29682 = build_decl (DECL_SOURCE_LOCATION (olddecl), TYPE_DECL,
29683 DECL_NAME (olddecl), newtype);
29684 DECL_ARTIFICIAL (DECL_TEMPLATE_RESULT (newdecl)) = true;
29685 // First create a copy (ttargs) of tsubst_args with an
29686 // additional level for the template template parameter's own
29687 // template parameters (ttparms).
29688 tree ttparms = (INNERMOST_TEMPLATE_PARMS
29689 (DECL_TEMPLATE_PARMS (olddecl)));
29690 const int depth = TMPL_ARGS_DEPTH (tsubst_args);
29691 tree ttargs = make_tree_vec (depth + 1);
29692 for (int i = 0; i < depth; ++i)
29693 TREE_VEC_ELT (ttargs, i) = TMPL_ARGS_LEVEL (tsubst_args, i + 1);
29694 TREE_VEC_ELT (ttargs, depth)
29695 = template_parms_level_to_args (ttparms);
29696 // Substitute ttargs into ttparms to fix references to
29697 // other template parameters.
29698 ttparms = tsubst_template_parms_level (ttparms, ttargs,
29699 complain|tf_partial);
29700 // Now substitute again with args based on tparms, to reduce
29701 // the level of the ttparms.
29702 ttargs = current_template_args ();
29703 ttparms = tsubst_template_parms_level (ttparms, ttargs,
29704 complain);
29705 // Finally, tack the adjusted parms onto tparms.
29706 ttparms = tree_cons (size_int (level + 1), ttparms,
29707 copy_node (current_template_parms));
29708 // As with all template template parms, the parameter list captured
29709 // by this template template parm that corresponds to its own level
29710 // should be empty. This avoids infinite recursion when structurally
29711 // comparing two such rewritten template template parms (PR102479).
29712 gcc_assert (!TREE_VEC_LENGTH
29713 (TREE_VALUE (TREE_CHAIN (DECL_TEMPLATE_PARMS (olddecl)))));
29714 gcc_assert (TMPL_PARMS_DEPTH (TREE_CHAIN (ttparms)) == level);
29715 TREE_VALUE (TREE_CHAIN (ttparms)) = make_tree_vec (0);
29716 // All done.
29717 DECL_TEMPLATE_PARMS (newdecl) = ttparms;
29720 if (TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (olddecl)))
29721 SET_TYPE_STRUCTURAL_EQUALITY (newtype);
29722 else
29723 TYPE_CANONICAL (newtype) = canonical_type_parameter (newtype);
29725 else
29727 tree oldconst = TEMPLATE_PARM_DECL (oldidx);
29728 tree newconst
29729 = build_decl (DECL_SOURCE_LOCATION (oldconst),
29730 TREE_CODE (oldconst),
29731 DECL_NAME (oldconst), newtype);
29732 TREE_CONSTANT (newconst) = TREE_CONSTANT (newdecl)
29733 = TREE_READONLY (newconst) = TREE_READONLY (newdecl) = true;
29734 SET_DECL_TEMPLATE_PARM_P (newconst);
29735 newidx = build_template_parm_index (index, level, level,
29736 newconst, newtype);
29737 TEMPLATE_PARM_PARAMETER_PACK (newidx)
29738 = TEMPLATE_PARM_PARAMETER_PACK (oldidx);
29739 DECL_INITIAL (newdecl) = DECL_INITIAL (newconst) = newidx;
29742 return newdecl;
29745 /* As rewrite_template_parm, but for the whole TREE_LIST representing a
29746 template parameter. */
29748 static tree
29749 rewrite_tparm_list (tree oldelt, unsigned index, unsigned level,
29750 tree targs, unsigned targs_index, tsubst_flags_t complain)
29752 tree olddecl = TREE_VALUE (oldelt);
29753 tree newdecl = rewrite_template_parm (olddecl, index, level,
29754 targs, complain);
29755 if (newdecl == error_mark_node)
29756 return error_mark_node;
29757 tree newdef = tsubst_template_arg (TREE_PURPOSE (oldelt),
29758 targs, complain, NULL_TREE);
29759 tree list = build_tree_list (newdef, newdecl);
29760 TEMPLATE_PARM_CONSTRAINTS (list)
29761 = tsubst_constraint_info (TEMPLATE_PARM_CONSTRAINTS (oldelt),
29762 targs, complain, NULL_TREE);
29763 int depth = TMPL_ARGS_DEPTH (targs);
29764 TMPL_ARG (targs, depth, targs_index) = template_parm_to_arg (list);
29765 return list;
29768 /* Returns a C++17 class deduction guide template based on the constructor
29769 CTOR. As a special case, CTOR can be a RECORD_TYPE for an implicit default
29770 guide, REFERENCE_TYPE for an implicit copy/move guide, or TREE_LIST for an
29771 aggregate initialization guide. OUTER_ARGS are the template arguments
29772 for the enclosing scope of the class. */
29774 static tree
29775 build_deduction_guide (tree type, tree ctor, tree outer_args, tsubst_flags_t complain)
29777 tree tparms, targs, fparms, fargs, ci;
29778 bool memtmpl = false;
29779 bool explicit_p;
29780 location_t loc;
29781 tree fn_tmpl = NULL_TREE;
29783 if (outer_args)
29785 ++processing_template_decl;
29786 type = tsubst (type, outer_args, complain, CLASSTYPE_TI_TEMPLATE (type));
29787 --processing_template_decl;
29790 if (!DECL_DECLARES_FUNCTION_P (ctor))
29792 if (TYPE_P (ctor))
29794 bool copy_p = TYPE_REF_P (ctor);
29795 if (copy_p)
29796 fparms = tree_cons (NULL_TREE, type, void_list_node);
29797 else
29798 fparms = void_list_node;
29800 else if (TREE_CODE (ctor) == TREE_LIST)
29801 fparms = ctor;
29802 else
29803 gcc_unreachable ();
29805 tree ctmpl = CLASSTYPE_TI_TEMPLATE (type);
29806 tparms = DECL_TEMPLATE_PARMS (ctmpl);
29807 targs = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
29808 ci = NULL_TREE;
29809 fargs = NULL_TREE;
29810 loc = DECL_SOURCE_LOCATION (ctmpl);
29811 explicit_p = false;
29813 else
29815 ++processing_template_decl;
29816 bool ok = true;
29818 complain |= tf_dguide;
29820 fn_tmpl
29821 = (TREE_CODE (ctor) == TEMPLATE_DECL ? ctor
29822 : DECL_TI_TEMPLATE (ctor));
29823 if (outer_args)
29824 fn_tmpl = tsubst (fn_tmpl, outer_args, complain, ctor);
29825 ctor = DECL_TEMPLATE_RESULT (fn_tmpl);
29827 tparms = DECL_TEMPLATE_PARMS (fn_tmpl);
29828 /* If type is a member class template, DECL_TI_ARGS (ctor) will have
29829 fully specialized args for the enclosing class. Strip those off, as
29830 the deduction guide won't have those template parameters. */
29831 targs = get_innermost_template_args (DECL_TI_ARGS (ctor),
29832 TMPL_PARMS_DEPTH (tparms));
29833 /* Discard the 'this' parameter. */
29834 fparms = FUNCTION_ARG_CHAIN (ctor);
29835 fargs = TREE_CHAIN (DECL_ARGUMENTS (ctor));
29836 ci = get_constraints (ctor);
29837 loc = DECL_SOURCE_LOCATION (ctor);
29838 explicit_p = DECL_NONCONVERTING_P (ctor);
29840 if (PRIMARY_TEMPLATE_P (fn_tmpl))
29842 memtmpl = true;
29844 /* For a member template constructor, we need to flatten the two
29845 template parameter lists into one, and then adjust the function
29846 signature accordingly. This gets...complicated. */
29847 tree save_parms = current_template_parms;
29849 /* For a member template we should have two levels of parms/args, one
29850 for the class and one for the constructor. We stripped
29851 specialized args for further enclosing classes above. */
29852 const int depth = 2;
29853 gcc_assert (TMPL_ARGS_DEPTH (targs) == depth);
29855 /* Template args for translating references to the two-level template
29856 parameters into references to the one-level template parameters we
29857 are creating. */
29858 tree tsubst_args = copy_node (targs);
29859 TMPL_ARGS_LEVEL (tsubst_args, depth)
29860 = copy_node (TMPL_ARGS_LEVEL (tsubst_args, depth));
29862 /* Template parms for the constructor template. */
29863 tree ftparms = TREE_VALUE (tparms);
29864 unsigned flen = TREE_VEC_LENGTH (ftparms);
29865 /* Template parms for the class template. */
29866 tparms = TREE_CHAIN (tparms);
29867 tree ctparms = TREE_VALUE (tparms);
29868 unsigned clen = TREE_VEC_LENGTH (ctparms);
29869 /* Template parms for the deduction guide start as a copy of the
29870 template parms for the class. We set current_template_parms for
29871 lookup_template_class_1. */
29872 current_template_parms = tparms = copy_node (tparms);
29873 tree new_vec = TREE_VALUE (tparms) = make_tree_vec (flen + clen);
29874 for (unsigned i = 0; i < clen; ++i)
29875 TREE_VEC_ELT (new_vec, i) = TREE_VEC_ELT (ctparms, i);
29877 /* Now we need to rewrite the constructor parms to append them to the
29878 class parms. */
29879 for (unsigned i = 0; i < flen; ++i)
29881 unsigned index = i + clen;
29882 unsigned level = 1;
29883 tree oldelt = TREE_VEC_ELT (ftparms, i);
29884 tree newelt
29885 = rewrite_tparm_list (oldelt, index, level,
29886 tsubst_args, i, complain);
29887 if (newelt == error_mark_node)
29888 ok = false;
29889 TREE_VEC_ELT (new_vec, index) = newelt;
29892 /* Now we have a final set of template parms to substitute into the
29893 function signature. */
29894 targs = template_parms_to_args (tparms);
29895 fparms = tsubst_arg_types (fparms, tsubst_args, NULL_TREE,
29896 complain, ctor);
29897 if (fparms == error_mark_node)
29898 ok = false;
29899 if (ci)
29901 if (outer_args)
29902 /* FIXME: We'd like to avoid substituting outer template
29903 arguments into the constraint ahead of time, but the
29904 construction of tsubst_args assumes that outer arguments
29905 are already substituted in. */
29906 ci = tsubst_constraint_info (ci, outer_args, complain, ctor);
29907 ci = tsubst_constraint_info (ci, tsubst_args, complain, ctor);
29910 /* Parms are to have DECL_CHAIN tsubsted, which would be skipped if
29911 cp_unevaluated_operand. */
29912 cp_evaluated ev;
29913 fargs = tsubst (fargs, tsubst_args, complain, ctor);
29914 current_template_parms = save_parms;
29916 else
29918 /* Substitute in the same arguments to rewrite class members into
29919 references to members of an unknown specialization. */
29920 cp_evaluated ev;
29921 fparms = tsubst_arg_types (fparms, targs, NULL_TREE, complain, ctor);
29922 fargs = tsubst (fargs, targs, complain, ctor);
29923 if (ci)
29925 if (outer_args)
29926 /* FIXME: As above. */
29927 ci = tsubst_constraint_info (ci, outer_args, complain, ctor);
29928 ci = tsubst_constraint_info (ci, targs, complain, ctor);
29932 --processing_template_decl;
29933 if (!ok)
29934 return error_mark_node;
29937 if (!memtmpl)
29939 /* Copy the parms so we can set DECL_PRIMARY_TEMPLATE. */
29940 tparms = copy_node (tparms);
29941 INNERMOST_TEMPLATE_PARMS (tparms)
29942 = copy_node (INNERMOST_TEMPLATE_PARMS (tparms));
29945 tree fntype = build_function_type (type, fparms);
29946 tree ded_fn = build_lang_decl_loc (loc,
29947 FUNCTION_DECL,
29948 dguide_name (type), fntype);
29949 DECL_ARGUMENTS (ded_fn) = fargs;
29950 DECL_ARTIFICIAL (ded_fn) = true;
29951 DECL_NONCONVERTING_P (ded_fn) = explicit_p;
29952 tree ded_tmpl = build_template_decl (ded_fn, tparms, /*member*/false);
29953 DECL_ARTIFICIAL (ded_tmpl) = true;
29954 DECL_TEMPLATE_INFO (ded_fn) = build_template_info (ded_tmpl, targs);
29955 DECL_PRIMARY_TEMPLATE (ded_tmpl) = ded_tmpl;
29956 if (DECL_P (ctor))
29957 DECL_ABSTRACT_ORIGIN (ded_tmpl) = fn_tmpl;
29958 if (ci)
29959 set_constraints (ded_tmpl, ci);
29961 return ded_tmpl;
29964 /* Add to LIST the member types for the reshaped initializer CTOR. */
29966 static tree
29967 collect_ctor_idx_types (tree ctor, tree list, tree elt = NULL_TREE)
29969 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (ctor);
29970 tree idx, val; unsigned i;
29971 FOR_EACH_CONSTRUCTOR_ELT (v, i, idx, val)
29973 tree ftype = elt ? elt : TREE_TYPE (idx);
29974 if (BRACE_ENCLOSED_INITIALIZER_P (val)
29975 && CONSTRUCTOR_BRACES_ELIDED_P (val))
29977 tree subelt = NULL_TREE;
29978 if (TREE_CODE (ftype) == ARRAY_TYPE)
29979 subelt = TREE_TYPE (ftype);
29980 list = collect_ctor_idx_types (val, list, subelt);
29981 continue;
29983 tree arg = NULL_TREE;
29984 if (i == v->length() - 1
29985 && PACK_EXPANSION_P (ftype))
29986 /* Give the trailing pack expansion parameter a default argument to
29987 match aggregate initialization behavior, even if we deduce the
29988 length of the pack separately to more than we have initializers. */
29989 arg = build_constructor (init_list_type_node, NULL);
29990 /* if ei is of array type and xi is a braced-init-list or string literal,
29991 Ti is an rvalue reference to the declared type of ei */
29992 STRIP_ANY_LOCATION_WRAPPER (val);
29993 if (TREE_CODE (ftype) == ARRAY_TYPE
29994 && (BRACE_ENCLOSED_INITIALIZER_P (val)
29995 || TREE_CODE (val) == STRING_CST))
29997 if (TREE_CODE (val) == STRING_CST)
29998 ftype = cp_build_qualified_type
29999 (ftype, cp_type_quals (ftype) | TYPE_QUAL_CONST);
30000 ftype = (cp_build_reference_type
30001 (ftype, BRACE_ENCLOSED_INITIALIZER_P (val)));
30003 list = tree_cons (arg, ftype, list);
30006 return list;
30009 /* Return whether ETYPE is, or is derived from, a specialization of TMPL. */
30011 static bool
30012 is_spec_or_derived (tree etype, tree tmpl)
30014 if (!etype || !CLASS_TYPE_P (etype))
30015 return false;
30017 etype = cv_unqualified (etype);
30018 tree type = TREE_TYPE (tmpl);
30019 tree tparms = (INNERMOST_TEMPLATE_PARMS
30020 (DECL_TEMPLATE_PARMS (tmpl)));
30021 tree targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
30022 int err = unify (tparms, targs, type, etype,
30023 UNIFY_ALLOW_DERIVED, /*explain*/false);
30024 ggc_free (targs);
30025 return !err;
30028 static tree alias_ctad_tweaks (tree, tree);
30030 /* Return a C++20 aggregate deduction candidate for TYPE initialized from
30031 INIT. */
30033 static tree
30034 maybe_aggr_guide (tree tmpl, tree init, vec<tree,va_gc> *args)
30036 if (cxx_dialect < cxx20)
30037 return NULL_TREE;
30039 if (init == NULL_TREE)
30040 return NULL_TREE;
30042 if (DECL_ALIAS_TEMPLATE_P (tmpl))
30044 tree under = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30045 tree tinfo = get_template_info (under);
30046 if (tree guide = maybe_aggr_guide (TI_TEMPLATE (tinfo), init, args))
30047 return alias_ctad_tweaks (tmpl, guide);
30048 return NULL_TREE;
30051 /* We might be creating a guide for a class member template, e.g.,
30053 template<typename U> struct A {
30054 template<typename T> struct B { T t; };
30057 At this point, A will have been instantiated. Below, we need to
30058 use both A<U>::B<T> (TEMPLATE_TYPE) and A<int>::B<T> (TYPE) types. */
30059 const bool member_template_p
30060 = (DECL_TEMPLATE_INFO (tmpl)
30061 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (tmpl)));
30062 tree type = TREE_TYPE (tmpl);
30063 tree template_type = (member_template_p
30064 ? TREE_TYPE (DECL_TI_TEMPLATE (tmpl))
30065 : type);
30066 if (!CP_AGGREGATE_TYPE_P (template_type))
30067 return NULL_TREE;
30069 /* No aggregate candidate for copy-initialization. */
30070 if (args->length() == 1)
30072 tree val = (*args)[0];
30073 if (is_spec_or_derived (TREE_TYPE (val), tmpl))
30074 return NULL_TREE;
30077 /* If we encounter a problem, we just won't add the candidate. */
30078 tsubst_flags_t complain = tf_none;
30080 tree parms = NULL_TREE;
30081 if (BRACE_ENCLOSED_INITIALIZER_P (init))
30083 init = reshape_init (template_type, init, complain);
30084 if (init == error_mark_node)
30085 return NULL_TREE;
30086 parms = collect_ctor_idx_types (init, parms);
30087 /* If we're creating a deduction guide for a member class template,
30088 we've used the original template pattern type for the reshape_init
30089 above; this is done because we want PARMS to be a template parameter
30090 type, something that can be deduced when used as a function template
30091 parameter. At this point the outer class template has already been
30092 partially instantiated (we deferred the deduction until the enclosing
30093 scope is non-dependent). Therefore we have to partially instantiate
30094 PARMS, so that its template level is properly reduced and we don't get
30095 mismatches when deducing types using the guide with PARMS. */
30096 if (member_template_p)
30098 ++processing_template_decl;
30099 parms = tsubst (parms, DECL_TI_ARGS (tmpl), complain, init);
30100 --processing_template_decl;
30103 else if (TREE_CODE (init) == TREE_LIST)
30105 int len = list_length (init);
30106 for (tree field = TYPE_FIELDS (type);
30107 len;
30108 --len, field = DECL_CHAIN (field))
30110 field = next_aggregate_field (field);
30111 if (!field)
30112 return NULL_TREE;
30113 tree ftype = finish_decltype_type (field, true, complain);
30114 parms = tree_cons (NULL_TREE, ftype, parms);
30117 else
30118 /* Aggregate initialization doesn't apply to an initializer expression. */
30119 return NULL_TREE;
30121 if (parms)
30123 tree last = parms;
30124 parms = nreverse (parms);
30125 TREE_CHAIN (last) = void_list_node;
30126 tree guide = build_deduction_guide (type, parms, NULL_TREE, complain);
30127 return guide;
30130 return NULL_TREE;
30133 /* UGUIDES are the deduction guides for the underlying template of alias
30134 template TMPL; adjust them to be deduction guides for TMPL. */
30136 static tree
30137 alias_ctad_tweaks (tree tmpl, tree uguides)
30139 /* [over.match.class.deduct]: When resolving a placeholder for a deduced
30140 class type (9.2.8.2) where the template-name names an alias template A,
30141 the defining-type-id of A must be of the form
30143 typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
30145 as specified in 9.2.8.2. The guides of A are the set of functions or
30146 function templates formed as follows. For each function or function
30147 template f in the guides of the template named by the simple-template-id
30148 of the defining-type-id, the template arguments of the return type of f
30149 are deduced from the defining-type-id of A according to the process in
30150 13.10.2.5 with the exception that deduction does not fail if not all
30151 template arguments are deduced. Let g denote the result of substituting
30152 these deductions into f. If substitution succeeds, form a function or
30153 function template f' with the following properties and add it to the set
30154 of guides of A:
30156 * The function type of f' is the function type of g.
30158 * If f is a function template, f' is a function template whose template
30159 parameter list consists of all the template parameters of A (including
30160 their default template arguments) that appear in the above deductions or
30161 (recursively) in their default template arguments, followed by the
30162 template parameters of f that were not deduced (including their default
30163 template arguments), otherwise f' is not a function template.
30165 * The associated constraints (13.5.2) are the conjunction of the
30166 associated constraints of g and a constraint that is satisfied if and only
30167 if the arguments of A are deducible (see below) from the return type.
30169 * If f is a copy deduction candidate (12.4.1.8), then f' is considered to
30170 be so as well.
30172 * If f was generated from a deduction-guide (12.4.1.8), then f' is
30173 considered to be so as well.
30175 * The explicit-specifier of f' is the explicit-specifier of g (if
30176 any). */
30178 tsubst_flags_t complain = tf_warning_or_error;
30179 tree atype = TREE_TYPE (tmpl);
30180 tree aguides = NULL_TREE;
30181 tree fullatparms = DECL_TEMPLATE_PARMS (tmpl);
30182 tree atparms = INNERMOST_TEMPLATE_PARMS (fullatparms);
30183 unsigned natparms = TREE_VEC_LENGTH (atparms);
30184 tree utype = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30185 for (ovl_iterator iter (uguides); iter; ++iter)
30187 tree f = *iter;
30188 tree in_decl = f;
30189 location_t loc = DECL_SOURCE_LOCATION (f);
30190 tree ret = TREE_TYPE (TREE_TYPE (f));
30191 tree fprime = f;
30192 if (TREE_CODE (f) == TEMPLATE_DECL)
30194 processing_template_decl_sentinel ptds (/*reset*/false);
30195 ++processing_template_decl;
30197 /* Deduce template arguments for f from the type-id of A. */
30198 tree ftparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (f));
30199 unsigned len = TREE_VEC_LENGTH (ftparms);
30200 tree targs = make_tree_vec (len);
30201 int err = unify (ftparms, targs, ret, utype, UNIFY_ALLOW_NONE, false);
30202 if (err)
30203 /* CWG2664: Discard any deductions, still build the guide. */
30204 for (unsigned i = 0; i < len; ++i)
30205 TREE_VEC_ELT (targs, i) = NULL_TREE;
30207 /* The number of parms for f' is the number of parms of A used in
30208 the deduced arguments plus non-deduced parms of f. */
30209 unsigned ndlen = 0;
30210 unsigned j;
30211 for (unsigned i = 0; i < len; ++i)
30212 if (TREE_VEC_ELT (targs, i) == NULL_TREE)
30213 ++ndlen;
30214 find_template_parameter_info ftpi (fullatparms);
30215 ftpi.find_in_recursive (targs);
30216 unsigned nusedatparms = ftpi.num_found ();
30217 unsigned nfparms = nusedatparms + ndlen;
30218 tree gtparms = make_tree_vec (nfparms);
30220 /* Set current_template_parms as in build_deduction_guide. */
30221 auto ctp = make_temp_override (current_template_parms);
30222 current_template_parms = copy_node (DECL_TEMPLATE_PARMS (tmpl));
30223 TREE_VALUE (current_template_parms) = gtparms;
30225 j = 0;
30226 unsigned level = 1;
30228 /* First copy over the used parms of A. */
30229 tree atargs = make_tree_vec (natparms);
30230 for (unsigned i = 0; i < natparms; ++i)
30232 tree elt = TREE_VEC_ELT (atparms, i);
30233 if (ftpi.found (elt))
30235 unsigned index = j++;
30236 tree nelt = rewrite_tparm_list (elt, index, level,
30237 atargs, i, complain);
30238 TREE_VEC_ELT (gtparms, index) = nelt;
30241 gcc_checking_assert (j == nusedatparms);
30243 /* Adjust the deduced template args for f to refer to the A parms
30244 with their new indexes. */
30245 if (nusedatparms && nusedatparms != natparms)
30246 targs = tsubst_template_args (targs, atargs, complain, in_decl);
30248 /* Now rewrite the non-deduced parms of f. */
30249 for (unsigned i = 0; ndlen && i < len; ++i)
30250 if (TREE_VEC_ELT (targs, i) == NULL_TREE)
30252 --ndlen;
30253 unsigned index = j++;
30254 tree oldlist = TREE_VEC_ELT (ftparms, i);
30255 tree list = rewrite_tparm_list (oldlist, index, level,
30256 targs, i, complain);
30257 TREE_VEC_ELT (gtparms, index) = list;
30259 gtparms = build_tree_list (size_one_node, gtparms);
30261 /* Substitute the deduced arguments plus the rewritten template
30262 parameters into f to get g. This covers the type, copyness,
30263 guideness, and explicit-specifier. */
30264 tree g;
30266 /* Parms are to have DECL_CHAIN tsubsted, which would be skipped
30267 if cp_unevaluated_operand. */
30268 cp_evaluated ev;
30269 g = tsubst_decl (DECL_TEMPLATE_RESULT (f), targs, complain);
30271 if (g == error_mark_node)
30272 continue;
30273 if (nfparms == 0)
30275 /* The targs are all non-dependent, so g isn't a template. */
30276 fprime = g;
30277 ret = TREE_TYPE (TREE_TYPE (fprime));
30278 goto non_template;
30280 DECL_USE_TEMPLATE (g) = 0;
30281 fprime = build_template_decl (g, gtparms, false);
30282 DECL_TEMPLATE_RESULT (fprime) = g;
30283 TREE_TYPE (fprime) = TREE_TYPE (g);
30284 tree gtargs = template_parms_to_args (gtparms);
30285 DECL_TEMPLATE_INFO (g) = build_template_info (fprime, gtargs);
30286 DECL_PRIMARY_TEMPLATE (fprime) = fprime;
30288 /* Substitute the associated constraints. */
30289 tree ci = get_constraints (f);
30290 if (ci)
30291 ci = tsubst_constraint_info (ci, targs, complain, in_decl);
30292 if (ci == error_mark_node)
30293 continue;
30295 /* Add a constraint that the return type matches the instantiation of
30296 A with the same template arguments. */
30297 ret = TREE_TYPE (TREE_TYPE (fprime));
30298 if (!same_type_p (atype, ret)
30299 /* FIXME this should mean they don't compare as equivalent. */
30300 || dependent_alias_template_spec_p (atype, nt_opaque))
30302 tree same = finish_trait_expr (loc, CPTK_IS_DEDUCIBLE, tmpl, ret);
30303 ci = append_constraint (ci, same);
30306 if (ci)
30308 remove_constraints (fprime);
30309 set_constraints (fprime, ci);
30312 else
30314 /* For a non-template deduction guide, if the arguments of A aren't
30315 deducible from the return type, don't add the candidate. */
30316 non_template:
30317 if (!type_targs_deducible_from (tmpl, ret))
30318 continue;
30321 aguides = lookup_add (fprime, aguides);
30324 return aguides;
30327 /* True iff template arguments for TMPL can be deduced from TYPE.
30328 Used to implement CPTK_IS_DEDUCIBLE for alias CTAD according to
30329 [over.match.class.deduct].
30331 This check is specified in terms of partial specialization, so the behavior
30332 should be parallel to that of get_partial_spec_bindings. */
30334 bool
30335 type_targs_deducible_from (tree tmpl, tree type)
30337 tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
30338 int len = TREE_VEC_LENGTH (tparms);
30339 tree targs = make_tree_vec (len);
30340 bool tried_array_deduction = (cxx_dialect < cxx17);
30342 /* If tmpl is a class template, this is trivial: it's deducible if TYPE is a
30343 specialization of TMPL. */
30344 if (DECL_CLASS_TEMPLATE_P (tmpl))
30345 return (CLASS_TYPE_P (type)
30346 && CLASSTYPE_TEMPLATE_INFO (type)
30347 && CLASSTYPE_TI_TEMPLATE (type) == tmpl);
30349 /* Otherwise it's an alias template. */
30350 again:
30351 if (unify (tparms, targs, TREE_TYPE (tmpl), type,
30352 UNIFY_ALLOW_NONE, false))
30353 return false;
30355 /* We don't fail on an undeduced targ the second time through (like
30356 get_partial_spec_bindings) because we're going to try defaults. */
30357 for (int i = 0; i < len; ++i)
30358 if (! TREE_VEC_ELT (targs, i))
30360 tree tparm = TREE_VEC_ELT (tparms, i);
30361 tparm = TREE_VALUE (tparm);
30363 if (!tried_array_deduction
30364 && TREE_CODE (tparm) == TYPE_DECL)
30366 try_array_deduction (tparms, targs, TREE_TYPE (tmpl));
30367 tried_array_deduction = true;
30368 if (TREE_VEC_ELT (targs, i))
30369 goto again;
30371 /* If the type parameter is a parameter pack, then it will be deduced
30372 to an empty parameter pack. This is another case that doesn't model
30373 well as partial specialization. */
30374 if (template_parameter_pack_p (tparm))
30376 tree arg;
30377 if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
30379 arg = make_node (NONTYPE_ARGUMENT_PACK);
30380 TREE_CONSTANT (arg) = 1;
30382 else
30383 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
30384 ARGUMENT_PACK_ARGS (arg) = make_tree_vec (0);
30385 TREE_VEC_ELT (targs, i) = arg;
30389 /* Maybe add in default template args. This seems like a flaw in the
30390 specification in terms of partial specialization, since it says the
30391 partial specialization has the the template parameter list of A, but a
30392 partial specialization can't have default targs. */
30393 targs = coerce_template_parms (tparms, targs, tmpl, tf_none);
30394 if (targs == error_mark_node)
30395 return false;
30397 /* I believe we don't need the template_template_parm_bindings_ok_p call
30398 because coerce_template_parms did coerce_template_template_parms. */
30400 return constraints_satisfied_p (tmpl, targs);
30403 /* Return artificial deduction guides built from the constructors of class
30404 template TMPL. */
30406 static tree
30407 ctor_deduction_guides_for (tree tmpl, tsubst_flags_t complain)
30409 tree outer_args = outer_template_args (tmpl);
30410 tree type = TREE_TYPE (most_general_template (tmpl));
30412 tree cands = NULL_TREE;
30414 for (ovl_iterator iter (CLASSTYPE_CONSTRUCTORS (type)); iter; ++iter)
30416 /* Skip inherited constructors. */
30417 if (iter.using_p ())
30418 continue;
30420 tree guide = build_deduction_guide (type, *iter, outer_args, complain);
30421 cands = lookup_add (guide, cands);
30424 /* Add implicit default constructor deduction guide. */
30425 if (!TYPE_HAS_USER_CONSTRUCTOR (type))
30427 tree guide = build_deduction_guide (type, type, outer_args,
30428 complain);
30429 cands = lookup_add (guide, cands);
30432 /* Add copy guide. */
30434 tree gtype = build_reference_type (type);
30435 tree guide = build_deduction_guide (type, gtype, outer_args,
30436 complain);
30437 cands = lookup_add (guide, cands);
30440 return cands;
30443 static GTY((deletable)) hash_map<tree, tree_pair_p> *dguide_cache;
30445 /* Return the non-aggregate deduction guides for deducible template TMPL. The
30446 aggregate candidate is added separately because it depends on the
30447 initializer. Set ANY_DGUIDES_P if we find a non-implicit deduction
30448 guide. */
30450 static tree
30451 deduction_guides_for (tree tmpl, bool &any_dguides_p, tsubst_flags_t complain)
30453 tree guides = NULL_TREE;
30454 if (DECL_ALIAS_TEMPLATE_P (tmpl))
30456 tree under = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30457 tree tinfo = get_template_info (under);
30458 guides = deduction_guides_for (TI_TEMPLATE (tinfo), any_dguides_p,
30459 complain);
30461 else
30463 guides = lookup_qualified_name (CP_DECL_CONTEXT (tmpl),
30464 dguide_name (tmpl),
30465 LOOK_want::NORMAL, /*complain*/false);
30466 if (guides == error_mark_node)
30467 guides = NULL_TREE;
30468 else
30469 any_dguides_p = true;
30472 /* Cache the deduction guides for a template. We also remember the result of
30473 lookup, and rebuild everything if it changes; should be very rare. */
30474 tree_pair_p cache = NULL;
30475 if (tree_pair_p &r
30476 = hash_map_safe_get_or_insert<hm_ggc> (dguide_cache, tmpl))
30478 cache = r;
30479 if (cache->purpose == guides)
30480 return cache->value;
30482 else
30484 r = cache = ggc_cleared_alloc<tree_pair_s> ();
30485 cache->purpose = guides;
30488 tree cands = NULL_TREE;
30489 if (DECL_ALIAS_TEMPLATE_P (tmpl))
30490 cands = alias_ctad_tweaks (tmpl, guides);
30491 else
30493 cands = ctor_deduction_guides_for (tmpl, complain);
30494 for (ovl_iterator it (guides); it; ++it)
30495 cands = lookup_add (*it, cands);
30498 cache->value = cands;
30499 return cands;
30502 /* Return whether TMPL is a (class template argument-) deducible template. */
30504 bool
30505 ctad_template_p (tree tmpl)
30507 /* A deducible template is either a class template or is an alias template
30508 whose defining-type-id is of the form
30510 typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
30512 where the nested-name-specifier (if any) is non-dependent and the
30513 template-name of the simple-template-id names a deducible template. */
30515 if (DECL_CLASS_TEMPLATE_P (tmpl)
30516 || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
30517 return true;
30518 if (!DECL_ALIAS_TEMPLATE_P (tmpl))
30519 return false;
30520 tree orig = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30521 if (tree tinfo = get_template_info (orig))
30522 return ctad_template_p (TI_TEMPLATE (tinfo));
30523 return false;
30526 /* Deduce template arguments for the class template placeholder PTYPE for
30527 template TMPL based on the initializer INIT, and return the resulting
30528 type. */
30530 static tree
30531 do_class_deduction (tree ptype, tree tmpl, tree init,
30532 int flags, tsubst_flags_t complain)
30534 /* We should have handled this in the caller. */
30535 if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
30536 return ptype;
30538 /* If the class was erroneous, don't try to deduce, because that
30539 can generate a lot of diagnostic. */
30540 if (TREE_TYPE (tmpl)
30541 && TYPE_LANG_SPECIFIC (TREE_TYPE (tmpl))
30542 && CLASSTYPE_ERRONEOUS (TREE_TYPE (tmpl)))
30543 return ptype;
30545 /* Wait until the enclosing scope is non-dependent. */
30546 if (DECL_CLASS_SCOPE_P (tmpl)
30547 && dependent_type_p (DECL_CONTEXT (tmpl)))
30548 return ptype;
30550 /* Initializing one placeholder from another. */
30551 if (init
30552 && (TREE_CODE (init) == TEMPLATE_PARM_INDEX
30553 || (TREE_CODE (init) == EXPR_PACK_EXPANSION
30554 && (TREE_CODE (PACK_EXPANSION_PATTERN (init))
30555 == TEMPLATE_PARM_INDEX)))
30556 && is_auto (TREE_TYPE (init))
30557 && CLASS_PLACEHOLDER_TEMPLATE (TREE_TYPE (init)) == tmpl)
30558 return cp_build_qualified_type (TREE_TYPE (init), cp_type_quals (ptype));
30560 if (!ctad_template_p (tmpl))
30562 if (complain & tf_error)
30563 error ("non-deducible template %qT used without template arguments", tmpl);
30564 return error_mark_node;
30566 else if (cxx_dialect < cxx20 && DECL_ALIAS_TEMPLATE_P (tmpl))
30568 if (complain & tf_error)
30570 /* Be permissive with equivalent alias templates. */
30571 tree u = get_underlying_template (tmpl);
30572 diagnostic_t dk = (u == tmpl) ? DK_ERROR : DK_PEDWARN;
30573 bool complained
30574 = emit_diagnostic (dk, input_location, 0,
30575 "alias template deduction only available "
30576 "with %<-std=c++20%> or %<-std=gnu++20%>");
30577 if (u == tmpl)
30578 return error_mark_node;
30579 else if (complained)
30581 inform (input_location, "use %qD directly instead", u);
30582 tmpl = u;
30585 else
30586 return error_mark_node;
30589 /* Wait until the initializer is non-dependent. */
30590 if (type_dependent_expression_p (init))
30591 return ptype;
30593 /* Don't bother with the alias rules for an equivalent template. */
30594 tmpl = get_underlying_template (tmpl);
30596 tree type = TREE_TYPE (tmpl);
30598 bool try_list_cand = false;
30599 bool list_init_p = false;
30601 releasing_vec rv_args = NULL;
30602 vec<tree,va_gc> *&args = *&rv_args;
30603 if (init == NULL_TREE)
30604 args = make_tree_vector ();
30605 else if (BRACE_ENCLOSED_INITIALIZER_P (init))
30607 list_init_p = true;
30608 try_list_cand = true;
30609 if (CONSTRUCTOR_NELTS (init) == 1
30610 && !CONSTRUCTOR_IS_DESIGNATED_INIT (init))
30612 /* As an exception, the first phase in 16.3.1.7 (considering the
30613 initializer list as a single argument) is omitted if the
30614 initializer list consists of a single expression of type cv U,
30615 where U is a specialization of C or a class derived from a
30616 specialization of C. */
30617 tree elt = CONSTRUCTOR_ELT (init, 0)->value;
30618 if (is_spec_or_derived (TREE_TYPE (elt), tmpl))
30619 try_list_cand = false;
30621 if (try_list_cand || is_std_init_list (type))
30622 args = make_tree_vector_single (init);
30623 else
30624 args = make_tree_vector_from_ctor (init);
30626 else if (TREE_CODE (init) == TREE_LIST)
30627 args = make_tree_vector_from_list (init);
30628 else
30629 args = make_tree_vector_single (init);
30631 /* Do this now to avoid problems with erroneous args later on. */
30632 args = resolve_args (args, complain);
30633 if (args == NULL)
30634 return error_mark_node;
30636 bool any_dguides_p = false;
30637 tree cands = deduction_guides_for (tmpl, any_dguides_p, complain);
30638 if (cands == error_mark_node)
30639 return error_mark_node;
30641 /* Prune explicit deduction guides in copy-initialization context (but
30642 not copy-list-initialization). */
30643 bool elided = false;
30644 if (!list_init_p && (flags & LOOKUP_ONLYCONVERTING))
30646 for (lkp_iterator iter (cands); !elided && iter; ++iter)
30647 if (DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
30648 elided = true;
30650 if (elided)
30652 /* Found a nonconverting guide, prune the candidates. */
30653 tree pruned = NULL_TREE;
30654 for (lkp_iterator iter (cands); iter; ++iter)
30655 if (!DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
30656 pruned = lookup_add (*iter, pruned);
30658 cands = pruned;
30662 if (!any_dguides_p)
30663 if (tree guide = maybe_aggr_guide (tmpl, init, args))
30664 cands = lookup_add (guide, cands);
30666 tree fndecl = error_mark_node;
30668 /* If this is list-initialization and the class has a list guide, first
30669 try deducing from the list as a single argument, as [over.match.list]. */
30670 if (try_list_cand)
30672 tree list_cands = NULL_TREE;
30673 for (tree dg : lkp_range (cands))
30674 if (is_list_ctor (dg))
30675 list_cands = lookup_add (dg, list_cands);
30676 if (list_cands)
30677 fndecl = perform_dguide_overload_resolution (list_cands, args, tf_none);
30678 if (fndecl == error_mark_node)
30680 /* That didn't work, now try treating the list as a sequence of
30681 arguments. */
30682 release_tree_vector (args);
30683 args = make_tree_vector_from_ctor (init);
30684 args = resolve_args (args, complain);
30685 if (args == NULL)
30686 return error_mark_node;
30690 if (elided && !cands)
30692 error ("cannot deduce template arguments for copy-initialization"
30693 " of %qT, as it has no non-explicit deduction guides or "
30694 "user-declared constructors", type);
30695 return error_mark_node;
30697 else if (!cands && fndecl == error_mark_node)
30699 error ("cannot deduce template arguments of %qT, as it has no viable "
30700 "deduction guides", type);
30701 return error_mark_node;
30704 if (fndecl == error_mark_node)
30705 fndecl = perform_dguide_overload_resolution (cands, args, tf_none);
30707 if (fndecl == error_mark_node)
30709 if (complain & tf_warning_or_error)
30711 error ("class template argument deduction failed:");
30712 perform_dguide_overload_resolution (cands, args, complain);
30713 if (elided)
30714 inform (input_location, "explicit deduction guides not considered "
30715 "for copy-initialization");
30717 return error_mark_node;
30719 /* [over.match.list]/1: In copy-list-initialization, if an explicit
30720 constructor is chosen, the initialization is ill-formed. */
30721 else if (flags & LOOKUP_ONLYCONVERTING)
30723 if (DECL_NONCONVERTING_P (fndecl))
30725 if (complain & tf_warning_or_error)
30727 // TODO: Pass down location from cp_finish_decl.
30728 error ("class template argument deduction for %qT failed: "
30729 "explicit deduction guide selected in "
30730 "copy-list-initialization", type);
30731 inform (DECL_SOURCE_LOCATION (fndecl),
30732 "explicit deduction guide declared here");
30735 return error_mark_node;
30739 /* If CTAD succeeded but the type doesn't have any explicit deduction
30740 guides, this deduction might not be what the user intended. */
30741 if (fndecl != error_mark_node && !any_dguides_p && (complain & tf_warning))
30743 if ((!DECL_IN_SYSTEM_HEADER (fndecl)
30744 || global_dc->dc_warn_system_headers)
30745 && warning (OPT_Wctad_maybe_unsupported,
30746 "%qT may not intend to support class template argument "
30747 "deduction", type))
30748 inform (input_location, "add a deduction guide to suppress this "
30749 "warning");
30752 return cp_build_qualified_type (TREE_TYPE (TREE_TYPE (fndecl)),
30753 cp_type_quals (ptype));
30756 /* Return true if INIT is an unparenthesized id-expression or an
30757 unparenthesized class member access. Used for the argument of
30758 decltype(auto). */
30760 bool
30761 unparenthesized_id_or_class_member_access_p (tree init)
30763 STRIP_ANY_LOCATION_WRAPPER (init);
30765 /* We need to be able to tell '(r)' and 'r' apart (when it's of
30766 reference type). Only the latter is an id-expression. */
30767 if (REFERENCE_REF_P (init)
30768 && !REF_PARENTHESIZED_P (init))
30769 init = TREE_OPERAND (init, 0);
30770 return (DECL_P (init)
30771 || ((TREE_CODE (init) == COMPONENT_REF
30772 || TREE_CODE (init) == SCOPE_REF)
30773 && !REF_PARENTHESIZED_P (init)));
30776 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
30777 from INIT. AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.
30778 The CONTEXT determines the context in which auto deduction is performed
30779 and is used to control error diagnostics. FLAGS are the LOOKUP_* flags.
30781 OUTER_TARGS is used during template argument deduction (context == adc_unify)
30782 to properly substitute the result. It's also used in the adc_unify and
30783 adc_requirement contexts to communicate the necessary template arguments
30784 to satisfaction. OUTER_TARGS is ignored in other contexts.
30786 Additionally for adc_unify contexts TMPL is the template for which TYPE
30787 is a template parameter type.
30789 For partial-concept-ids, extra args from OUTER_TARGS, TMPL and the current
30790 scope may be appended to the list of deduced template arguments prior to
30791 determining constraint satisfaction as appropriate. */
30793 tree
30794 do_auto_deduction (tree type, tree init, tree auto_node,
30795 tsubst_flags_t complain /* = tf_warning_or_error */,
30796 auto_deduction_context context /* = adc_unspecified */,
30797 tree outer_targs /* = NULL_TREE */,
30798 int flags /* = LOOKUP_NORMAL */,
30799 tree tmpl /* = NULL_TREE */)
30801 if (type == error_mark_node || init == error_mark_node)
30802 return error_mark_node;
30804 if (init && type_dependent_expression_p (init)
30805 && context != adc_unify)
30806 /* Defining a subset of type-dependent expressions that we can deduce
30807 from ahead of time isn't worth the trouble. */
30808 return type;
30810 /* Similarly, we can't deduce from another undeduced decl. */
30811 if (init && undeduced_auto_decl (init))
30812 return type;
30814 /* We may be doing a partial substitution, but we still want to replace
30815 auto_node. */
30816 complain &= ~tf_partial;
30818 if (init && BRACE_ENCLOSED_INITIALIZER_P (init))
30820 /* We don't recurse here because we can't deduce from a nested
30821 initializer_list. */
30822 if (CONSTRUCTOR_ELTS (init))
30823 for (constructor_elt &elt : CONSTRUCTOR_ELTS (init))
30824 elt.value = resolve_nondeduced_context (elt.value, complain);
30826 else if (init)
30827 init = resolve_nondeduced_context (init, complain);
30829 /* In C++23, we must deduce the type to int&& for code like
30830 decltype(auto) f(int&& x) { return (x); }
30832 auto&& f(int x) { return x; }
30833 so we use treat_lvalue_as_rvalue_p. But don't do it for
30834 decltype(auto) f(int x) { return x; }
30835 where we should deduce 'int' rather than 'int&&'; transmogrifying
30836 INIT to an rvalue would break that. */
30837 tree r;
30838 if (cxx_dialect >= cxx23
30839 && context == adc_return_type
30840 && (!AUTO_IS_DECLTYPE (auto_node)
30841 || !unparenthesized_id_or_class_member_access_p (init))
30842 && (r = treat_lvalue_as_rvalue_p (maybe_undo_parenthesized_ref (init),
30843 /*return*/true)))
30844 init = r;
30846 if (tree ctmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node))
30847 /* C++17 class template argument deduction. */
30848 return do_class_deduction (type, ctmpl, init, flags, complain);
30850 if (init == NULL_TREE || TREE_TYPE (init) == NULL_TREE)
30851 /* Nothing we can do with this, even in deduction context. */
30852 return type;
30854 location_t loc = cp_expr_loc_or_input_loc (init);
30856 /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
30857 with either a new invented type template parameter U or, if the
30858 initializer is a braced-init-list (8.5.4), with
30859 std::initializer_list<U>. */
30860 if (BRACE_ENCLOSED_INITIALIZER_P (init))
30862 if (!DIRECT_LIST_INIT_P (init))
30863 type = listify_autos (type, auto_node);
30864 else if (CONSTRUCTOR_NELTS (init) == 1)
30865 init = CONSTRUCTOR_ELT (init, 0)->value;
30866 else
30868 if (complain & tf_warning_or_error)
30870 if (permerror (loc, "direct-list-initialization of "
30871 "%<auto%> requires exactly one element"))
30872 inform (loc,
30873 "for deduction to %<std::initializer_list%>, use copy-"
30874 "list-initialization (i.e. add %<=%> before the %<{%>)");
30876 type = listify_autos (type, auto_node);
30880 if (type == error_mark_node || init == error_mark_node)
30881 return error_mark_node;
30883 tree targs;
30884 if (context == adc_decomp_type
30885 && auto_node == type
30886 && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
30888 /* [dcl.struct.bind]/1 - if decomposition declaration has no ref-qualifiers
30889 and initializer has array type, deduce cv-qualified array type. */
30890 targs = make_tree_vec (1);
30891 TREE_VEC_ELT (targs, 0) = TREE_TYPE (init);
30893 else if (AUTO_IS_DECLTYPE (auto_node))
30895 const bool id = unparenthesized_id_or_class_member_access_p (init);
30896 tree deduced = finish_decltype_type (init, id, complain);
30897 deduced = canonicalize_type_argument (deduced, complain);
30898 if (deduced == error_mark_node)
30899 return error_mark_node;
30900 targs = make_tree_vec (1);
30901 TREE_VEC_ELT (targs, 0) = deduced;
30903 else
30905 if (error_operand_p (init))
30906 return error_mark_node;
30908 tree parms = build_tree_list (NULL_TREE, type);
30909 tree tparms;
30911 if (flag_concepts_ts)
30912 tparms = extract_autos (type);
30913 else
30915 tparms = make_tree_vec (1);
30916 TREE_VEC_ELT (tparms, 0)
30917 = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
30920 targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
30921 int val = type_unification_real (tparms, targs, parms, &init, 1, 0,
30922 DEDUCE_CALL,
30923 NULL, /*explain_p=*/false);
30924 if (val > 0)
30926 if (processing_template_decl)
30927 /* Try again at instantiation time. */
30928 return type;
30929 if (type && type != error_mark_node
30930 && (complain & tf_error))
30931 /* If type is error_mark_node a diagnostic must have been
30932 emitted by now. Also, having a mention to '<type error>'
30933 in the diagnostic is not really useful to the user. */
30935 if (cfun
30936 && FNDECL_USED_AUTO (current_function_decl)
30937 && (auto_node
30938 == DECL_SAVED_AUTO_RETURN_TYPE (current_function_decl))
30939 && LAMBDA_FUNCTION_P (current_function_decl))
30940 error_at (loc, "unable to deduce lambda return type from %qE",
30941 init);
30942 else
30943 error_at (loc, "unable to deduce %qT from %qE", type, init);
30944 type_unification_real (tparms, targs, parms, &init, 1, 0,
30945 DEDUCE_CALL,
30946 NULL, /*explain_p=*/true);
30948 return error_mark_node;
30952 /* Check any placeholder constraints against the deduced type. */
30953 if (processing_template_decl && context == adc_unify)
30954 /* Constraints will be checked after deduction. */;
30955 else if (tree constr = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (auto_node)))
30957 if (processing_template_decl)
30959 gcc_checking_assert (context == adc_variable_type
30960 || context == adc_return_type
30961 || context == adc_decomp_type);
30962 gcc_checking_assert (!type_dependent_expression_p (init));
30963 /* If the constraint is dependent, we need to wait until
30964 instantiation time to resolve the placeholder. */
30965 if (placeholder_type_constraint_dependent_p (constr))
30966 return type;
30969 if (context == adc_return_type
30970 || context == adc_variable_type
30971 || context == adc_decomp_type)
30972 if (tree fn = current_function_decl)
30973 if (DECL_TEMPLATE_INFO (fn) || LAMBDA_FUNCTION_P (fn))
30975 outer_targs = DECL_TEMPLATE_INFO (fn)
30976 ? DECL_TI_ARGS (fn) : NULL_TREE;
30977 if (LAMBDA_FUNCTION_P (fn))
30979 /* As in satisfy_declaration_constraints. */
30980 tree regen_args = lambda_regenerating_args (fn);
30981 if (outer_targs)
30982 outer_targs = add_to_template_args (regen_args, outer_targs);
30983 else
30984 outer_targs = regen_args;
30988 tree full_targs = outer_targs;
30989 if (context == adc_unify && tmpl)
30990 full_targs = add_outermost_template_args (tmpl, full_targs);
30991 full_targs = add_to_template_args (full_targs, targs);
30993 /* HACK: Compensate for callers not always communicating all levels of
30994 outer template arguments by filling in the outermost missing levels
30995 with dummy levels before checking satisfaction. We'll still crash
30996 if the constraint depends on a template argument belonging to one of
30997 these missing levels, but this hack otherwise allows us to handle a
30998 large subset of possible constraints (including all non-dependent
30999 constraints). */
31000 if (int missing_levels = (TEMPLATE_TYPE_ORIG_LEVEL (auto_node)
31001 - TMPL_ARGS_DEPTH (full_targs)))
31003 tree dummy_levels = make_tree_vec (missing_levels);
31004 for (int i = 0; i < missing_levels; ++i)
31005 TREE_VEC_ELT (dummy_levels, i) = make_tree_vec (0);
31006 full_targs = add_to_template_args (dummy_levels, full_targs);
31009 if (!constraints_satisfied_p (auto_node, full_targs))
31011 if (complain & tf_warning_or_error)
31013 auto_diagnostic_group d;
31014 switch (context)
31016 case adc_unspecified:
31017 case adc_unify:
31018 error_at (loc, "placeholder constraints not satisfied");
31019 break;
31020 case adc_variable_type:
31021 case adc_decomp_type:
31022 error_at (loc, "deduced initializer does not satisfy "
31023 "placeholder constraints");
31024 break;
31025 case adc_return_type:
31026 error_at (loc, "deduced return type does not satisfy "
31027 "placeholder constraints");
31028 break;
31029 case adc_requirement:
31030 error_at (loc, "deduced expression type does not satisfy "
31031 "placeholder constraints");
31032 break;
31034 diagnose_constraints (loc, auto_node, full_targs);
31036 return error_mark_node;
31040 if (TEMPLATE_TYPE_LEVEL (auto_node) == 1)
31041 /* The outer template arguments are already substituted into type
31042 (but we still may have used them for constraint checking above). */;
31043 else if (context == adc_unify)
31044 targs = add_to_template_args (outer_targs, targs);
31045 else if (processing_template_decl)
31046 targs = add_to_template_args (current_template_args (), targs);
31047 return tsubst (type, targs, complain, NULL_TREE);
31050 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
31051 result. */
31053 tree
31054 splice_late_return_type (tree type, tree late_return_type)
31056 if (late_return_type)
31058 gcc_assert (is_auto (type) || seen_error ());
31059 return late_return_type;
31062 if (tree auto_node = find_type_usage (type, is_auto))
31063 if (TEMPLATE_TYPE_LEVEL (auto_node) <= current_template_depth)
31065 /* In an abbreviated function template we didn't know we were dealing
31066 with a function template when we saw the auto return type, so rebuild
31067 the return type using an auto with the correct level. */
31068 tree new_auto = make_auto_1 (TYPE_IDENTIFIER (auto_node), false);
31069 tree auto_vec = make_tree_vec (1);
31070 TREE_VEC_ELT (auto_vec, 0) = new_auto;
31071 tree targs = add_outermost_template_args (current_template_args (),
31072 auto_vec);
31073 /* Also rebuild the constraint info in terms of the new auto. */
31074 if (tree ci = PLACEHOLDER_TYPE_CONSTRAINTS_INFO (auto_node))
31075 PLACEHOLDER_TYPE_CONSTRAINTS_INFO (new_auto)
31076 = build_tree_list (current_template_parms,
31077 tsubst_constraint (TREE_VALUE (ci), targs,
31078 tf_none, NULL_TREE));
31079 TYPE_CANONICAL (new_auto) = canonical_type_parameter (new_auto);
31080 return tsubst (type, targs, tf_none, NULL_TREE);
31082 return type;
31085 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto' or
31086 'decltype(auto)' or a deduced class template. */
31088 bool
31089 is_auto (const_tree type)
31091 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
31092 && (TYPE_IDENTIFIER (type) == auto_identifier
31093 || TYPE_IDENTIFIER (type) == decltype_auto_identifier))
31094 return true;
31095 else
31096 return false;
31099 /* for_each_template_parm callback for type_uses_auto. */
31102 is_auto_r (tree tp, void */*data*/)
31104 return is_auto (tp);
31107 /* Returns the TEMPLATE_TYPE_PARM in TYPE representing `auto' iff TYPE contains
31108 a use of `auto'. Returns NULL_TREE otherwise. */
31110 tree
31111 type_uses_auto (tree type)
31113 if (type == NULL_TREE)
31114 return NULL_TREE;
31115 else if (flag_concepts_ts)
31117 /* The Concepts TS allows multiple autos in one type-specifier; just
31118 return the first one we find, do_auto_deduction will collect all of
31119 them. */
31120 if (uses_template_parms (type))
31121 return for_each_template_parm (type, is_auto_r, /*data*/NULL,
31122 /*visited*/NULL, /*nondeduced*/false);
31123 else
31124 return NULL_TREE;
31126 else
31127 return find_type_usage (type, is_auto);
31130 /* Report ill-formed occurrences of auto types in ARGUMENTS. If
31131 concepts are enabled, auto is acceptable in template arguments, but
31132 only when TEMPL identifies a template class. Return TRUE if any
31133 such errors were reported. */
31135 bool
31136 check_auto_in_tmpl_args (tree tmpl, tree args)
31138 if (!flag_concepts_ts)
31139 /* Only the concepts TS allows 'auto' as a type-id; it'd otherwise
31140 have already been rejected by the parser more generally. */
31141 return false;
31143 /* If there were previous errors, nevermind. */
31144 if (!args || TREE_CODE (args) != TREE_VEC)
31145 return false;
31147 /* If TMPL is an identifier, we're parsing and we can't tell yet
31148 whether TMPL is supposed to be a type, a function or a variable.
31149 We'll only be able to tell during template substitution, so we
31150 expect to be called again then. If concepts are enabled and we
31151 know we have a type, we're ok. */
31152 if (identifier_p (tmpl)
31153 || (DECL_P (tmpl)
31154 && (DECL_TYPE_TEMPLATE_P (tmpl)
31155 || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))))
31156 return false;
31158 /* Quickly search for any occurrences of auto; usually there won't
31159 be any, and then we'll avoid allocating the vector. */
31160 if (!type_uses_auto (args))
31161 return false;
31163 bool errors = false;
31165 tree vec = extract_autos (args);
31166 for (int i = 0; i < TREE_VEC_LENGTH (vec); i++)
31168 tree xauto = TREE_VALUE (TREE_VEC_ELT (vec, i));
31169 error_at (DECL_SOURCE_LOCATION (xauto),
31170 "invalid use of %qT in template argument", xauto);
31171 errors = true;
31174 return errors;
31177 /* Recursively walk over && expressions searching for EXPR. Return a reference
31178 to that expression. */
31180 static tree *find_template_requirement (tree *t, tree key)
31182 if (*t == key)
31183 return t;
31184 if (TREE_CODE (*t) == TRUTH_ANDIF_EXPR)
31186 if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 0), key))
31187 return p;
31188 if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 1), key))
31189 return p;
31191 return 0;
31194 /* Convert the generic type parameters in PARM that match the types given in the
31195 range [START_IDX, END_IDX) from the current_template_parms into generic type
31196 packs. */
31198 tree
31199 convert_generic_types_to_packs (tree parm, int start_idx, int end_idx)
31201 tree current = current_template_parms;
31202 int depth = TMPL_PARMS_DEPTH (current);
31203 current = INNERMOST_TEMPLATE_PARMS (current);
31204 tree replacement = make_tree_vec (TREE_VEC_LENGTH (current));
31206 for (int i = 0; i < start_idx; ++i)
31207 TREE_VEC_ELT (replacement, i)
31208 = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
31210 for (int i = start_idx; i < end_idx; ++i)
31212 /* Create a distinct parameter pack type from the current parm and add it
31213 to the replacement args to tsubst below into the generic function
31214 parameter. */
31215 tree node = TREE_VEC_ELT (current, i);
31216 tree o = TREE_TYPE (TREE_VALUE (node));
31217 tree t = copy_type (o);
31218 TEMPLATE_TYPE_PARM_INDEX (t)
31219 = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (o),
31220 t, 0, 0, tf_none);
31221 TREE_TYPE (TEMPLATE_TYPE_DECL (t)) = t;
31222 TYPE_STUB_DECL (t) = TYPE_NAME (t) = TEMPLATE_TYPE_DECL (t);
31223 TYPE_MAIN_VARIANT (t) = t;
31224 TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
31225 TYPE_CANONICAL (t) = canonical_type_parameter (t);
31226 TREE_VEC_ELT (replacement, i) = t;
31228 /* Replace the current template parameter with new pack. */
31229 TREE_VALUE (node) = TREE_CHAIN (t);
31231 /* Surgically adjust the associated constraint of adjusted parameter
31232 and it's corresponding contribution to the current template
31233 requirements. */
31234 if (tree constr = TEMPLATE_PARM_CONSTRAINTS (node))
31236 tree id = unpack_concept_check (constr);
31237 TREE_VEC_ELT (TREE_OPERAND (id, 1), 0) = t;
31238 tree fold = finish_left_unary_fold_expr (constr, TRUTH_ANDIF_EXPR);
31239 TEMPLATE_PARM_CONSTRAINTS (node) = fold;
31241 /* If there was a constraint, we also need to replace that in
31242 the template requirements, which we've already built. */
31243 tree *reqs = &TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
31244 reqs = find_template_requirement (reqs, constr);
31245 *reqs = fold;
31249 for (int i = end_idx, e = TREE_VEC_LENGTH (current); i < e; ++i)
31250 TREE_VEC_ELT (replacement, i)
31251 = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
31253 /* If there are more levels then build up the replacement with the outer
31254 template parms. */
31255 if (depth > 1)
31256 replacement = add_to_template_args (template_parms_to_args
31257 (TREE_CHAIN (current_template_parms)),
31258 replacement);
31260 return tsubst (parm, replacement, tf_none, NULL_TREE);
31263 /* __integer_pack(N) in a pack expansion expands to a sequence of numbers from
31264 0..N-1. */
31266 void
31267 declare_integer_pack (void)
31269 tree ipfn = push_library_fn (get_identifier ("__integer_pack"),
31270 build_function_type_list (integer_type_node,
31271 integer_type_node,
31272 NULL_TREE),
31273 NULL_TREE, ECF_CONST);
31274 DECL_DECLARED_CONSTEXPR_P (ipfn) = true;
31275 set_decl_built_in_function (ipfn, BUILT_IN_FRONTEND,
31276 CP_BUILT_IN_INTEGER_PACK);
31279 /* Walk the decl or type specialization table calling FN on each
31280 entry. */
31282 void
31283 walk_specializations (bool decls_p,
31284 void (*fn) (bool decls_p, spec_entry *entry, void *data),
31285 void *data)
31287 spec_hash_table *table = decls_p ? decl_specializations
31288 : type_specializations;
31289 spec_hash_table::iterator end (table->end ());
31290 for (spec_hash_table::iterator iter (table->begin ()); iter != end; ++iter)
31291 fn (decls_p, *iter, data);
31294 /* Lookup the specialization of *ELT, in the decl or type
31295 specialization table. Return the SPEC that's already there, or
31296 NULL if nothing. */
31298 tree
31299 match_mergeable_specialization (bool decl_p, spec_entry *elt)
31301 hash_table<spec_hasher> *specializations
31302 = decl_p ? decl_specializations : type_specializations;
31303 hashval_t hash = spec_hasher::hash (elt);
31304 auto *slot = specializations->find_slot_with_hash (elt, hash, NO_INSERT);
31306 if (slot)
31307 return (*slot)->spec;
31309 return NULL_TREE;
31312 /* Return flags encoding whether SPEC is on the instantiation and/or
31313 specialization lists of TMPL. */
31315 unsigned
31316 get_mergeable_specialization_flags (tree tmpl, tree decl)
31318 unsigned flags = 0;
31320 for (tree inst = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
31321 inst; inst = TREE_CHAIN (inst))
31322 if (TREE_VALUE (inst) == decl)
31324 flags |= 1;
31325 break;
31328 if (CLASS_TYPE_P (TREE_TYPE (decl))
31329 && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl))
31330 && CLASSTYPE_USE_TEMPLATE (TREE_TYPE (decl)) == 2)
31331 /* Only need to search if DECL is a partial specialization. */
31332 for (tree part = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
31333 part; part = TREE_CHAIN (part))
31334 if (TREE_VALUE (part) == decl)
31336 flags |= 2;
31337 break;
31340 return flags;
31343 /* Add a new specialization described by SPEC. DECL is the
31344 maybe-template decl and FLAGS is as returned from
31345 get_mergeable_specialization_flags. */
31347 void
31348 add_mergeable_specialization (bool decl_p, bool alias_p, spec_entry *elt,
31349 tree decl, unsigned flags)
31351 hashval_t hash = spec_hasher::hash (elt);
31352 if (decl_p)
31354 auto *slot = decl_specializations->find_slot_with_hash (elt, hash, INSERT);
31356 gcc_checking_assert (!*slot);
31357 auto entry = ggc_alloc<spec_entry> ();
31358 *entry = *elt;
31359 *slot = entry;
31361 if (alias_p)
31363 elt->spec = TREE_TYPE (elt->spec);
31364 gcc_checking_assert (elt->spec);
31368 if (!decl_p || alias_p)
31370 auto *slot = type_specializations->find_slot_with_hash (elt, hash, INSERT);
31372 /* We don't distinguish different constrained partial type
31373 specializations, so there could be duplicates. Everything else
31374 must be new. */
31375 if (!(flags & 2 && *slot))
31377 gcc_checking_assert (!*slot);
31379 auto entry = ggc_alloc<spec_entry> ();
31380 *entry = *elt;
31381 *slot = entry;
31385 if (flags & 1)
31386 DECL_TEMPLATE_INSTANTIATIONS (elt->tmpl)
31387 = tree_cons (elt->args, decl, DECL_TEMPLATE_INSTANTIATIONS (elt->tmpl));
31389 if (flags & 2)
31391 /* A partial specialization. */
31392 tree cons = tree_cons (elt->args, decl,
31393 DECL_TEMPLATE_SPECIALIZATIONS (elt->tmpl));
31394 TREE_TYPE (cons) = decl_p ? TREE_TYPE (elt->spec) : elt->spec;
31395 DECL_TEMPLATE_SPECIALIZATIONS (elt->tmpl) = cons;
31399 /* Set up the hash tables for template instantiations. */
31401 void
31402 init_template_processing (void)
31404 decl_specializations = hash_table<spec_hasher>::create_ggc (37);
31405 type_specializations = hash_table<spec_hasher>::create_ggc (37);
31407 if (cxx_dialect >= cxx11)
31408 declare_integer_pack ();
31411 /* Print stats about the template hash tables for -fstats. */
31413 void
31414 print_template_statistics (void)
31416 fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
31417 "%f collisions\n", (long) decl_specializations->size (),
31418 (long) decl_specializations->elements (),
31419 decl_specializations->collisions ());
31420 fprintf (stderr, "type_specializations: size %ld, %ld elements, "
31421 "%f collisions\n", (long) type_specializations->size (),
31422 (long) type_specializations->elements (),
31423 type_specializations->collisions ());
31426 #if CHECKING_P
31428 namespace selftest {
31430 /* Verify that build_non_dependent_expr () works, for various expressions,
31431 and that location wrappers don't affect the results. */
31433 static void
31434 test_build_non_dependent_expr ()
31436 location_t loc = BUILTINS_LOCATION;
31438 /* Verify constants, without and with location wrappers. */
31439 tree int_cst = build_int_cst (integer_type_node, 42);
31440 ASSERT_EQ (int_cst, build_non_dependent_expr (int_cst));
31442 tree wrapped_int_cst = maybe_wrap_with_location (int_cst, loc);
31443 ASSERT_TRUE (location_wrapper_p (wrapped_int_cst));
31444 ASSERT_EQ (wrapped_int_cst, build_non_dependent_expr (wrapped_int_cst));
31446 tree string_lit = build_string (4, "foo");
31447 TREE_TYPE (string_lit) = char_array_type_node;
31448 string_lit = fix_string_type (string_lit);
31449 ASSERT_EQ (string_lit, build_non_dependent_expr (string_lit));
31451 tree wrapped_string_lit = maybe_wrap_with_location (string_lit, loc);
31452 ASSERT_TRUE (location_wrapper_p (wrapped_string_lit));
31453 ASSERT_EQ (wrapped_string_lit,
31454 build_non_dependent_expr (wrapped_string_lit));
31457 /* Verify that type_dependent_expression_p () works correctly, even
31458 in the presence of location wrapper nodes. */
31460 static void
31461 test_type_dependent_expression_p ()
31463 location_t loc = BUILTINS_LOCATION;
31465 tree name = get_identifier ("foo");
31467 /* If no templates are involved, nothing is type-dependent. */
31468 gcc_assert (!processing_template_decl);
31469 ASSERT_FALSE (type_dependent_expression_p (name));
31471 ++processing_template_decl;
31473 /* Within a template, an unresolved name is always type-dependent. */
31474 ASSERT_TRUE (type_dependent_expression_p (name));
31476 /* Ensure it copes with NULL_TREE and errors. */
31477 ASSERT_FALSE (type_dependent_expression_p (NULL_TREE));
31478 ASSERT_FALSE (type_dependent_expression_p (error_mark_node));
31480 /* A USING_DECL in a template should be type-dependent, even if wrapped
31481 with a location wrapper (PR c++/83799). */
31482 tree using_decl = build_lang_decl (USING_DECL, name, NULL_TREE);
31483 TREE_TYPE (using_decl) = integer_type_node;
31484 ASSERT_TRUE (type_dependent_expression_p (using_decl));
31485 tree wrapped_using_decl = maybe_wrap_with_location (using_decl, loc);
31486 ASSERT_TRUE (location_wrapper_p (wrapped_using_decl));
31487 ASSERT_TRUE (type_dependent_expression_p (wrapped_using_decl));
31489 --processing_template_decl;
31492 /* Run all of the selftests within this file. */
31494 void
31495 cp_pt_cc_tests ()
31497 test_build_non_dependent_expr ();
31498 test_type_dependent_expression_p ();
31501 } // namespace selftest
31503 #endif /* #if CHECKING_P */
31505 #include "gt-cp-pt.h"